<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;" v-if="!isPreview">
        <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('submit')">
            {{ $t('trials:researchForm:button:submit') }}
          </el-button>
          <!-- 审核通过 -->
          <el-button v-if="(state === 1 && hasPermi(['role:spm', 'role:cpm']))" type="primary" size="small"
            @click="handleSubmit('approve')">
            {{ $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" :isPreview="isPreview" />
      </el-card>

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

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

      <!-- 其他信息调研 -->
      <el-card shadow="hover" class="mt10">
        <!-- 注意事项 -->
        <h4>{{ $t('trials:equiptResearch:form:precautions') }}</h4>
        <ol v-if="siteSurveyNoteInfo">
          <div v-if="$i18n.locale === 'zh'" v-html="siteSurveyNoteInfo.ReplaceContentCN" />
          <div v-else v-html="siteSurveyNoteInfo.ReplaceContent" />
        </ol>
        <ol v-else>
          <!-- 只要有可能，请确保受试者使用上述指定的扫描仪器采集影像。 -->
          <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>
      <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 },
  props: {
    isPreview: {
      type: Boolean,
      default: false
    }
  },
  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,
      siteSurveyNoteInfo: {}
    }
  },
  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
          if (res.Result.SiteSurveyFiledConfig && res.Result.SiteSurveyFiledConfig.ModifyFiledList.length > 0) {
            this.siteSurveyNoteInfo = res.Result.SiteSurveyFiledConfig.ModifyFiledList.find(i => i.NeedModifyFiled === 'SiteSurveyNote')
          }
          this.siteSurveyNoteInfo.IsCloseEquipmentSurvey = res.Result.SiteSurveyFiledConfig.IsCloseEquipmentSurvey
          this.state = res.Result.TrialSiteSurvey.State
          this.siteId = res.Result.TrialSiteSurvey.TrialSiteId
          this.$refs['baseResearchInfo'].initForm(res.Result.TrialInfo, res.Result.TrialSiteSurvey, res.Result.SiteSurveyFiledConfig ? res.Result.SiteSurveyFiledConfig.NotShowFieldList : null)
          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, !(res.Result.SiteSurveyFiledConfig && res.Result.SiteSurveyFiledConfig.ModifyFiledList.length > 0))
          this.isExistIncorrect = res.Result.TrialSiteUserSurveyList.every(item => item.IsCorrect === false)
        }
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    // 提交
    handleSubmit(type) {
      if (this.userTypeEnumInt === 0) {
        this.loading = true
        this.$refs['baseResearchInfo'].handleSave(true).then(res => {
          this.loading = false
          if (res) {
            this.submit(type)
          }
        }).catch(() => { this.loading = false })
      } else {
        this.submit(type)
      }
    },
    submit(type) {
      // 是否确认提交
      this.$confirm(this.userTypeEnumInt === 0 ? this.$t('trials:researchForm:message:submitWarning') : this.$t('trials:researchForm:message:submitWarning2'), {
        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'))
            if (type === 'approve') {
              this.$message.success(this.$t('common:message:approvedSuccessfully'))
            } else {
              this.$message.success(this.$t('trials:researchForm: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:approvedSuccessfully'))
          }
        }).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')
    },
    // 退出
    async handleBack() {
      await this.$store.dispatch('user/logout')
      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;
  }

  ::v-deep.el-card__body {
    padding: 10px;
  }

  // >>>.el-dialog__body{
  //   padding: 10px 20px 20px 20px;
  // }

  ::v-deep.full-dialog-container {
    .el-dialog__body {
      height: calc(100% - 80px);
    }
  }

  ::v-deep.dialog-container {
    // margin-top: 50px !important;
    width: 75%;
    height: 80%;

    .el-dialog__body {
      padding: 10px;
      height: calc(100% - 80px);
    }
  }

}
</style>
