<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 type="primary" size="small" v-if="!isLog" @click="viewLog">
            {{ $t('trials:researchForm:button:log') }}
          </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" :IsOnlyUploadFile="IsOnlyUploadFile"
          :IsSupportUploadFile="IsSupportUploadFile" :isPM="isPM" />
      </el-card>

      <!-- 人员调查 -->
      <el-card shadow="hover" class="mt10">
        <!-- 历史人员 -->
        <h4>{{ $t('trials:staffResearch:title:historicalStaff') }}</h4>
        <HistoricalParticipant ref="historicalParticipant" :isPreview="isPreview" :isPM="isPM"
          @refreshPage="refreshPage" @getList="initPage" />
        <!-- <h4>{{ $t('trials:staffResearch:title:staff') }}</h4> -->
        <!-- 新增人员 -->
        <h4>{{ $t('trials:staffResearch:title:newStaff') }}</h4>
        <ParticipantList ref="researchParticipants" :isPreview="isPreview" :isPM="isPM" @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" :isPM="isPM" />
      </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 class="history-dialog-content">
        <HistoricalRecord :trial-id="trialId" :site-id="siteId" :trial-site-survey-id="trialSiteSurveyId" />
      </div>
    </el-dialog>

    <el-dialog v-if="logVisible" :visible.sync="logVisible"
      :custom-class="isFullscreen ? 'full-log-dialog-container' : 'log-dialog-container'" :close-on-click-modal="false"
      :fullscreen="isFullscreen" :show-close="false" width="60%" append-to-body>
      <span slot="title" class="dialog-footer">
        <div style="display: flex;flex-direction: row;justify-content: space-between;">
          <div>
            {{ $t('trials:researchForm:button:log') }}
          </div>
          <div>
            <svg-icon :icon-class="isFullscreen ? 'exit-fullscreen' : 'fullscreen'"
              style="vertical-align: baseline;cursor: pointer;font-size: 20px;" @click="toggleLogFullscreen" />
            <svg-icon icon-class="dClose" style="cursor: pointer;font-size: 25px;margin-left: 10px;"
              @click="logVisible = false" />
          </div>
        </div>
      </span>
      <div class="log-dialog-content">
        <LogList :trial-site-survey-id="trialSiteSurveyId" />
      </div>
    </el-dialog>

  </div>
</template>
<script>
import { getSiteSurveyInfo, trialSurveySubmit, submissionRejection, getSiteSurveyLogList } from '@/api/research'
import { getQueryString, changeURLStatic } 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 { mapMutations } from 'vuex'
import TopLang from './topLang'
import HistoricalRecord from './components/HistoricalRecord'
import LogList from './components/LogList'
import store from '@/store'
export default {
  name: 'QuestionForm',
  components: { BaseInfo, HistoricalParticipant, ParticipantList, EquipmentList, TopLang, HistoricalRecord, LogList },
  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: {},
      IsSupportUploadFile: false,
      IsOnlyUploadFile: false,
      logVisible: false,
      isLog: false,
      logId: null
    }
  },
  mounted() {
    let lang = this.$route.query.lang
    if (!lang) {
      const language = navigator.language
      lang = 'en'
      if (language.includes("zh")) {
        lang = 'zh'
      }
    }
    this.$i18n.locale = lang
    this.setLanguage(lang)
    this.$updateDictionary()
    this.trialSiteSurveyId = getQueryString('trialSiteSurveyId')
    this.logId = getQueryString('logId')
    if (this.logId) this.isLog = true
    if (this.$router.currentRoute.query.TokenKey) {
      store.dispatch('user/setToken', this.$router.currentRoute.query.TokenKey)
      changeURLStatic('TokenKey', '')
    }
    this.initPage()
    if (zzSessionStorage.getItem('userTypeEnumInt')) {
      this.userTypeEnumInt = zzSessionStorage.getItem('userTypeEnumInt') * 1
    }
  },
  computed: {
    isPM() {
      return this.hasPermi(['role:pm', 'role:spm', 'role:cpm', 'role:apm']) && this.state !== 3 && this.IsOnlyUploadFile
    }
  },
  methods: {
    ...mapMutations({ setLanguage: 'lang/setLanguage' }),
    // 初始化页面
    initPage() {
      this.loading = true
      if (this.isLog) {
        getSiteSurveyLogList({ trialSiteSurveyId: this.trialSiteSurveyId, Id: this.logId }).then(r => {
          if (r.Result && r.Result[0].Json) {
            let res = {
              Result: JSON.parse(r.Result[0].Json)
            }
            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.IsSupportUploadFile = res.Result.SiteSurveyFiledConfig.IsSupportUploadFile
              this.IsOnlyUploadFile = res.Result.SiteSurveyFiledConfig.IsOnlyUploadFile
              this.siteSurveyNoteInfo.IsCloseEquipmentSurvey = res.Result.SiteSurveyFiledConfig.IsCloseEquipmentSurvey
              this.state = 3
              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.EquipmentControlFieldList)
              this.isExistIncorrect = res.Result.TrialSiteUserSurveyList.every(item => item.IsCorrect === false)
            }
            this.loading = false
          }
        }).catch((err) => { console.log(err); this.loading = false })
      } else {
        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.IsSupportUploadFile = res.Result.SiteSurveyFiledConfig.IsSupportUploadFile
            this.IsOnlyUploadFile = res.Result.SiteSurveyFiledConfig.IsOnlyUploadFile
            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.EquipmentControlFieldList)
            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, type === 'approve').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.$refs['baseResearchInfo'].handleSave(true, true).then(res => {
        this.$confirm(this.$t('trials:researchForm:message:auditWarning'), {
          type: 'warning',
          distinguishCancelAndClose: true
        }).then(() => {
          if (res) {
            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`
            }
            this.loading = false
            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
            })
          }
        })
      })
    },
    // 驳回
    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
    },
    toggleLogFullscreen() {
      this.isFullscreen = !this.isFullscreen
    },
    viewLog() {
      this.isFullscreen = false
      this.logVisible = 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);
    }
  }

  .history-dialog-content,
  .log-dialog-content {
    height: 100%;
    margin: 0;
  }

  .log-dialog-content {
    overflow: hidden;
  }

}
</style>
<style lang="scss">
.full-log-dialog-container,
.log-dialog-container {
  overflow: hidden;
}

.full-log-dialog-container {
  display: flex;
  flex-direction: column;
}

.full-log-dialog-container .el-dialog__body {
  flex: 1;
  min-height: 0;
  padding: 10px;
  overflow: hidden;
}

.log-dialog-container .el-dialog__body {
  height: calc(100% - 80px);
  padding: 10px;
  overflow: hidden;
}

.full-log-dialog-container .log-dialog-content,
.log-dialog-container .log-dialog-content {
  height: 100%;
  overflow: hidden;
}
</style>
