<template>
  <div v-loading="loading" class="question-form-wrapper">
    <div class="header-wrapper">
      <h2 style="text-align:center;">
        <!-- 中心调研表 -->
        {{ $t('trials:researchForm:title:question') }}
      </h2>
      <div style="display: flex;justify-content: space-between;">
        <div>{{ $t('trials:researchForm:title:state') }}<el-tag>{{ $fd('ResearchRecord', state) }}</el-tag></div>

      </div>
    </div>
    <div class="center-wrapper">
      <!-- 基本信息 -->
      <el-card shadow="hover">
        <BaseInfo ref="baseResearchInfo" :is-history="true" />
      </el-card>

      <!-- 人员调查 -->
      <el-card shadow="hover" class="mt10">
        <!-- <h4>{{ $t('trials:staffResearch:title:staff') }}</h4>-->
        <!-- 历史人员 -->
        <h4>{{ $t('trials:staffResearch:title:historicalStaff') }}</h4>
        <HistoricalParticipant ref="historicalParticipant" :is-history="true" @refreshPage="refreshPage"
          @getList="initPage" />
        <!-- 新增人员 -->
        <h4>{{ $t('trials:staffResearch:title:newStaff') }}</h4>
        <ParticipantList ref="researchParticipants" :is-history="true" @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" :is-history="true" />
      </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="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>
            历史记录
          </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"
        />
      </div>
    </el-dialog> -->

  </div>
</template>
<script>
import { getSiteSurveyInfo, trialSurveySubmit, submissionRejection } from '@/api/research'
import BaseInfo from './BaseInfo'
import HistoricalParticipant from './HistoricalParticipant'
import ParticipantList from './ParticipantList'
import EquipmentList from './EquipmentList'
// import HistoricalRecord from './HistoricalRecord'
export default {
  name: 'QuestionForm',
  components: { BaseInfo, HistoricalParticipant, ParticipantList, EquipmentList },
  props: {
    trialSiteSurveyId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      trialId: this.$route.query.trialId,
      siteId: '',
      loading: false,
      state: null,
      userTypeEnumInt: 0,
      isExistIncorrect: false,
      rejectVisible: false,
      rejectForm: { reason: '' },
      btnLoading: false,
      isFullscreen: false,
      historyVisible: false,
      siteSurveyNoteInfo: {}
    }
  },
  mounted() {
    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
          var historicalArr = []
          var newArr = []
          res.Result.TrialSiteUserSurveyList.map(i => {
            if (i.IsHistoryUser) {
              historicalArr.push(i)
            } else {
              newArr.push(i)
            }
          })
          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)
          this.$refs['historicalParticipant'].initList(historicalArr, res.Result.TrialSiteSurvey)
          this.$refs['researchParticipants'].initList(newArr, res.Result.TrialSiteSurvey)
          // this.$refs['researchParticipants'].initList(res.Result.TrialSiteUserSurveyList, 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() {
      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}`
        }
        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;
  }

  ::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>
