<template>
  <div v-loading="loading" class="question-form-wrapper">
    <div class="header-wrapper">
      <h2 style="text-align:center;">
        <!-- 中心调研表 -->
        {{ $t('trials:researchForm:title:question') }}
      </h2>
      <TopLang style="position: fixed;top: 40px;right: 40px" />
      <div style="display: flex;justify-content: space-between;">
        <div>{{ $t('trials:researchForm:title:researchSurveyStatus') }} <el-tag>{{ $fd('ResearchRecord', state) }}</el-tag></div>
        <div>
          <!-- 提交 -->
          <el-button
            v-if="(state === 0 && userTypeEnumInt === 0)"
            type="primary"
            size="small"
            @click="handleSubmit"
          >
            {{ $t('trials:researchForm:button:submit') }}
          </el-button>
          <!-- 审核通过 -->
          <el-button
            v-if="(state === 1 && hasPermi(['role:spm','role:cpm']))"
            type="primary"
            size="small"
            @click="handleSubmit"
          >
            {{ $t('trials:researchForm:button:auditPasses') }}
          </el-button>
          <!-- 审核通过 -->
          <el-button
            v-if="(state === 2 && hasPermi(['role:pm','role:apm']))"
            type="primary"
            size="small"
            @click="generateAccount"
          >
            {{ $t('trials:researchForm:button:auditPasses') }}
          </el-button>
          <!-- 驳回 -->
          <el-button
            v-if="((state === 1 && hasPermi(['role:spm','role:cpm'])) || (state === 2 && hasPermi(['role:pm','role:apm'])))"
            type="primary"
            size="small"
            @click="handleReject"
          >
            {{ $t('trials:researchForm:button:auditRejected') }}
          </el-button>
          <!-- 历史记录 -->
          <el-button
            v-if="userTypeEnumInt === 0"
            type="primary"
            size="small"
            @click="handleHistory"
          >
            {{ $t('trials:researchForm:button:historicalRecord') }}
          </el-button>
          <!-- 退出 -->
          <el-button
            v-if="userTypeEnumInt === 0"
            type="primary"
            size="small"
            @click="handleBack"
          >
            {{ $t('trials:researchForm:button:loginOut') }}
          </el-button>
        </div>
      </div>
    </div>
    <div class="center-wrapper">
      <!-- 基本信息 -->
      <el-card shadow="hover">
        <BaseInfo ref="baseResearchInfo" />
      </el-card>

      <!-- 人员调查 -->
      <el-card shadow="hover" class="mt10">
        <!-- 历史人员 -->
        <h4>{{ $t('trials:staffResearch:title:historicalStaff') }}</h4>
        <HistoricalParticipant ref="historicalParticipant" @refreshPage="refreshPage" @getList="initPage" />
        <!-- <h4>{{ $t('trials:staffResearch:title:staff') }}</h4> -->
        <!-- 新增人员 -->
        <h4>{{ $t('trials:staffResearch:title:newStaff') }}</h4>
        <ParticipantList ref="researchParticipants" @refreshPage="refreshPage" @getList="initPage" />
      </el-card>

      <!-- 设备调研 -->
      <el-card shadow="hover" class="mt10">
        <h4>{{ $t('trials:equiptResearch:title:equiptResearch') }}</h4>
        <EquipmentList ref="researchEquipments" />
      </el-card>

      <!-- 其他信息调研 -->
      <el-card shadow="hover" class="mt10">
        <!-- 注意事项 -->
        <h4>{{ $t('trials:equiptResearch:form:precautions') }}</h4>
        <ol>
          <!-- 只要有可能，请确保受试者使用上述指定的扫描仪器采集影像。 -->
          <li>{{ $t('trials:equiptResearch:form:item1') }}</li>
          <!-- 请确保对每位受试者的扫描参数在整个研究过程中保持一致。 -->
          <li>{{ $t('trials:equiptResearch:form:item2') }}</li>
          <!-- 试验过程中，如果有任何人员、设备或扫描仪器的替换，请立即通知我们。 -->
          <li>{{ $t('trials:equiptResearch:form:item3') }}</li>
          <!-- 请保存好原始（未经压缩的；非重建的）数据。 -->
          <li>{{ $t('trials:equiptResearch:form:item4') }}</li>
        </ol>
      </el-card>
    </div>

    <el-dialog
      v-if="rejectVisible"
      :visible.sync="rejectVisible"
      :close-on-click-modal="false"
      :title="$t('trials:researchForm:dialogTitle:reject')"
      width="600px"
      custom-class="base-dialog-wrapper"
      :append-to-body="userTypeEnumInt !== 0"
    >
      <el-form ref="rejectForm" :model="rejectForm" label-width="100px">
        <div class="base-dialog-body">
          <!-- 驳回原因 -->
          <el-form-item
            :label="$t('trials:researchForm:form:rejectReson')"
            prop="reason"
            :rules="[
              { required: true, message: $t('trials:researchForm:formRule:specify')}
            ]"
          >
            <el-input
              v-model="rejectForm.reason"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4}"
              style="width:100%;"
            />
          </el-form-item>
        </div>
        <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
          <el-form-item>
            <!-- 取消 -->
            <el-button size="small" type="primary" :disabled="btnLoading" @click="rejectVisible = false">
              {{ $t('common:button:cancel') }}
            </el-button>
            <!-- 保存 -->
            <el-button size="small" type="primary" :loading="btnLoading" @click="reject">
              {{ $t('common:button:save') }}
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>

    <el-dialog
      :visible.sync="historyVisible"
      :custom-class="isFullscreen?'full-dialog-container':'dialog-container'"
      :close-on-click-modal="false"
      :fullscreen="isFullscreen"
      :show-close="false"
    >
      <span slot="title" class="dialog-footer">
        <div style="display: flex;flex-direction: row;justify-content: space-between;">
          <div>
            {{ $t('trials:researchForm:button:historicalRecord') }}
          </div>
          <div>
            <svg-icon :icon-class="isFullscreen?'exit-fullscreen':'fullscreen'" style="vertical-align: baseline;cursor: pointer;font-size: 20px;" @click="isFullscreen=!isFullscreen" />
            <svg-icon icon-class="dClose" style="cursor: pointer;font-size: 25px;margin-left: 10px;" @click="historyVisible = false" />
          </div>
        </div>
      </span>
      <div style="height:100%;margin:0;">
        <HistoricalRecord
          :trial-id="trialId"
          :site-id="siteId"
          :trial-site-survey-id="trialSiteSurveyId"
        />
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { getSiteSurveyInfo, trialSurveySubmit, submissionRejection } from '@/api/research'
import { getQueryString } from '@/utils/history.js'
import BaseInfo from './components/BaseInfo'
import HistoricalParticipant from './components/HistoricalParticipant'
import ParticipantList from './components/ParticipantList'
import EquipmentList from './components/EquipmentList'

import TopLang from './topLang'
import HistoricalRecord from './components/HistoricalRecord'
export default {
  name: 'QuestionForm',
  components: { BaseInfo, HistoricalParticipant, ParticipantList, EquipmentList, TopLang, HistoricalRecord },
  data() {
    return {
      trialId: this.$route.query.trialId,
      siteId: '',
      trialSiteSurveyId: '',
      loading: false,
      state: null,
      userTypeEnumInt: 0,
      isExistIncorrect: false,
      rejectVisible: false,
      rejectForm: { reason: '' },
      btnLoading: false,
      isFullscreen: false,
      historyVisible: false
    }
  },
  mounted() {
    this.trialSiteSurveyId = getQueryString('trialSiteSurveyId')
    this.initPage()
    if (zzSessionStorage.getItem('userTypeEnumInt')) {
      this.userTypeEnumInt = zzSessionStorage.getItem('userTypeEnumInt') * 1
    }
  },
  methods: {
    // 初始化页面
    initPage() {
      this.loading = true
      getSiteSurveyInfo(this.trialId, this.trialSiteSurveyId).then(res => {
        if (res.Result) {
          // this.trialSiteSurveyEquipmentType = res.Result.TrialInfo.TrialSiteSurveyEquipmentType
          // this.trialSiteSurveyUserRoles = res.Result.TrialInfo.TrialSiteSurveyUserRoles
          this.state = res.Result.TrialSiteSurvey.State
          this.siteId = res.Result.TrialSiteSurvey.SiteId
          this.$refs['baseResearchInfo'].initForm(res.Result.TrialInfo, res.Result.TrialSiteSurvey)
          var historicalArr = []
          var newArr = []
          res.Result.TrialSiteUserSurveyList.map(i => {
            if (i.IsHistoryUser) {
              historicalArr.push(i)
            } else {
              newArr.push(i)
            }
          })

          this.$refs['historicalParticipant'].initList(historicalArr, res.Result.TrialSiteSurvey)
          this.$refs['researchParticipants'].initList(newArr, res.Result.TrialSiteSurvey)
          this.$refs['researchEquipments'].initList(res.Result.TrialSiteEquipmentSurveyList, res.Result.TrialSiteSurvey)
          this.isExistIncorrect = res.Result.TrialSiteUserSurveyList.every(item => item.IsCorrect === false)
        }
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    // 提交
    handleSubmit() {
      if (this.userTypeEnumInt === 0) {
        // if (this.$refs['researchParticipants'].list.length === 0 && this.$refs['researchEquipments'].list.length === 0) {
        //   this.$alert(this.$t('trials:researchForm:message:saveWarning'))
        //   return
        // }
        // var list = this.$refs['researchParticipants'].list
        // var cIdx = list.findIndex(i => parseInt(i.TrialRoleCode) === 1)
        // var pIdx = list.findIndex(i => parseInt(i.TrialRoleCode) === 4)
        // if (cIdx === -1 || pIdx === -1) {
        //   // 提交时校验必须crc角色和影像负责人角色至少有1个
        //   this.$alert(this.$t('trials:researchForm:message:saveWarning1'))
        //   return
        // }

        this.loading = true
        this.$refs['baseResearchInfo'].handleSave(true).then(res => {
          this.loading = false
          if (res) {
            this.submit()
          }
        }).catch(() => { this.loading = false })
      } else {
        this.submit()
      }
    },
    submit() {
      // 是否确认提交
      this.$confirm(this.$t('trials:researchForm:message:submitWarning'), {
        type: 'warning',
        distinguishCancelAndClose: true
      }).then(() => {
        this.loading = true
        var param = {
          TrialId: this.trialId,
          TrialSiteSurveyId: this.trialSiteSurveyId
        }
        trialSurveySubmit(param).then((res) => {
          this.loading = false
          if (res.IsSuccess) {
            this.initPage()
            if (this.userTypeEnumInt !== 0) {
              this.$emit('refreshPage')
            }
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          }
        }).catch(() => { this.loading = false })
      }).catch(() => {})
    },
    // 生成账号
    generateAccount() {
      // 是否确认审核通过？
      this.$confirm(this.$t('trials:researchForm:message:auditWarning'), {
        type: 'warning',
        distinguishCancelAndClose: true
      }).then(() => {
        // 校验必须至少有1个crc账号和至少1个SR账号
        // var list = this.$refs['researchParticipants'].list
        // var cIdx = list.findIndex(i => i.UserTypeEnum === 5)
        // var sIdx = list.findIndex(i => i.UserTypeEnum === 9)
        // if (cIdx === -1 || sIdx === -1) {
        //   this.$alert(this.$t('trials:researchForm:message:saveWarning2'))
        //   return
        // }
        this.loading = true
        var param = {
          TrialId: this.trialId,
          TrialSiteSurveyId: this.trialSiteSurveyId,
          LoginUrl: `${location.protocol}//${location.host}/login`,
          BaseUrl: `${location.protocol}//${location.host}/login`,
          RouteUrl: `${location.protocol}//${location.host}/email-recompose`
        }
        trialSurveySubmit(param).then((res) => {
          this.loading = false
          if (res.IsSuccess) {
            this.initPage()
            this.$emit('refreshPage')
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          }
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {})
    },
    // 驳回
    handleReject() {
      this.rejectForm.reason = ''
      this.rejectVisible = true
    },
    reject() {
      this.$refs['rejectForm'].validate(valid => {
        if (!valid) return
        this.btnLoading = true
        const param = {
          trialId: this.trialId,
          trialSiteSurveyId: this.trialSiteSurveyId,
          latestBackReason: this.rejectForm.reason,
          routeUrl: `${location.protocol}//${location.host}/researchLogin?trialId=${this.trialId}&lang=${this.$i18n.locale}`
        }
        submissionRejection(param).then((res) => {
          this.btnLoading = false
          if (res.IsSuccess) {
            this.rejectVisible = false
            this.initPage()
            this.$emit('refreshPage')
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          }
        }).catch(() => { this.btnLoading = false })
      })
    },
    // 刷新父页面
    refreshPage() {
      this.$emit('refreshPage')
    },
    // 退出
    handleBack() {
      this.$router.push({ path: `/researchLogin?trialId=${this.trialId}&lang=${this.$i18n.locale}` })
    },
    handleHistory() {
      this.isFullscreen = false
      this.historyVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>
.question-form-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  .mt10{
    margin-top: 10px;
  }
  .header-wrapper{
    width: 70%;
    margin: 20px auto;
  }
  .center-wrapper{
    flex: 1;
    width: 70%;
    margin: 0px auto;
    padding-bottom: 20px;
    overflow-y: auto;
  }
  /deep/.el-card__body{
    padding: 10px;
  }
  // >>>.el-dialog__body{
  //   padding: 10px 20px 20px 20px;
  // }

  /deep/.full-dialog-container{
   .el-dialog__body{
      height: calc(100% - 80px);
    }
  }
  /deep/.dialog-container{
    // margin-top: 50px !important;
    width:75%;
    height:80%;
    .el-dialog__body{
      padding: 10px;
      height: calc(100% - 80px);
    }
  }

}
</style>
