<template>
  <div v-loading="loading" class="medical-audit-wrapper">
    <div class="medical-audit-content">
      <div>
        <h3>
          <!-- 评估结果  -->
          {{ $t('trials:medicalFeedback:title:result') }}<span v-if="auditInfo.SubjectCode">({{ auditInfo.SubjectCode }} | {{ auditInfo.TaskBlindName }} | {{ $fd('ArmEnum', auditInfo.ArmEnum) }})</span></h3>
        <HistoricAssessment
          v-if="Object.keys(auditInfo).length > 0"
          :audit-info="auditInfo"
          :row-data="rowData"
        />
      </div>
      <div style="margin-top:15px;">
        <!-- 审核问题 -->
        <h3>{{ $t('trials:medicalFeedback:title:auditQuestions') }}</h3>
        <Issues
          v-if="auditInfo.QuestionAnswerList && auditInfo.QuestionAnswerList.length>0"
          ref="auditIssues"
          :question-answer-list="auditInfo.QuestionAnswerList"
          :task-medical-review-id="taskMedicalReviewId"
          :audit-state="auditInfo.AuditState"
          :is-send-message="isSendMessage"
        />
      </div>
      <div style="margin-top:10px;">
        <!-- 结论 -->
        <h3>{{ $t('trials:medicalFeedback:title:conclusions') }}</h3>
        <Conclusions
          v-if="auditInfo.MedicalReviewInfo && Object.keys(auditInfo.MedicalReviewInfo).length > 0"
          ref="auditConclusions"
          :medical-review-info="auditInfo.MedicalReviewInfo"
          :audit-state="auditInfo.AuditState"
          :visit-task-id="visitTaskId"
          :subject-code="auditInfo.SubjectCode"
          :task-blind-name="auditInfo.TaskBlindName"
          @getMedicalAuditList="getMedicalAuditList"
          @setIsHaveQuestion="setIsHaveQuestion"
          @handleSign="handleSign"
        />
      </div>
    </div>
    <div class="medical-audit-bottom-btn">
      <el-divider />
      <!-- 取消 -->
      <!-- <el-button v-if="auditInfo.MedicalReviewInfo" @click="handleCancel">
        {{ $t('common:button:cancel') }}
      </el-button> -->
      <!-- 保存 -->
      <!-- <el-button v-if="auditInfo.MedicalReviewInfo && [14, 30].includes(userTypeEnumInt) && auditInfo.AuditState !== 2" type="primary" @click="handleSave">
        {{ $t('common:button:save') }}
      </el-button> -->
      <!-- 发起质询 -->
      <!-- hasPermi(['trials:trials-panel:reading:mim-medical-audit:edit']) -->
      <el-button v-if="hasPermi(['trials:trials-panel:reading:mim-medical-audit:edit']) && !isSendMessage && isHaveQuestion" type="primary" @click="handleLaunch">
        {{ $t('trials:medicalFeedback:title:launch') }}
      </el-button>
      <!-- 质询记录 -->
      <el-button v-if="isSendMessage" type="primary" @click="handleQc">
        {{ $t('trials:medicalFeedback:title:qaRecord') }}
      </el-button>
      <!-- 审核完成 -->
      <el-button v-if="hasPermi(['trials:trials-panel:reading:mim-medical-audit:edit']) && (isHaveQuestion === false || (auditInfo.IsClosedDialog && isSendMessage)) && auditInfo.AuditState !== 2" type="primary" @click="handleAudit">
        {{ $t('trials:medicalFeedback:button:auditCompleted') }}
      </el-button>
      <!-- 跳过 -->
      <el-button v-if="hasPermi(['trials:trials-panel:reading:mim-medical-audit:edit']) && auditInfo.AuditState !== 2" type="primary" @click="getNextTask">
        {{ $t('trials:medicalFeedback:button:nextTask') }}
      </el-button>
      <!-- IR下一任务 -->
      <el-button v-if="hasPermi(['trials:trials-panel:medicalFeedback:nextTask']) && auditInfo.AuditState === 1" type="primary" @click="getNextIRTask">
        {{ $t('trials:irmedicalFeedback:button:nextTask') }}
      </el-button>
    </div>

    <!--签名框 -->
    <el-dialog
      v-if="signVisible"
      :visible.sync="signVisible"
      :close-on-click-modal="false"
      width="600px"
      custom-class="base-dialog-wrapper"
      append-to-body
    >
      <div slot="title">
        <span
          style="font-size:18px;"
        >
          {{ $t('common:dialogTitle:sign') }}
        </span>
        <span
          style="font-size:12px;margin-left:5px"
        >
          {{ `(${$t('common:label:sign')}${ currentUser })` }}
        </span>
      </div>
      <SignForm
        ref="signForm"
        :sign-code-enum="signCode"
        @closeDialog="closeSignDialog"
      />
    </el-dialog>
  </div>
</template>
<script>
import { getMedicalReviewReadingTask, FinishMedicalReview } from '@/api/trials'
import HistoricAssessment from './HistoricAssessment'
import Issues from './Issues'
import Conclusions from './Conclusions'
import SignForm from '@/views/trials/components/newSignForm'
import const_ from '@/const/sign-code'
export default {
  name: 'MedicalAudit',
  components: {
    HistoricAssessment,
    Issues,
    Conclusions,
    SignForm
  },
  props: {
    taskMedicalReviewId: {
      type: String,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    rowData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      loading: false,
      auditInfo: {},
      signText: '',
      signCode: null,
      currentUser: zzSessionStorage.getItem('userName'),
      signVisible: false,
      userTypeEnumInt: zzSessionStorage.getItem('userTypeEnumInt') * 1,
      isSendMessage: false,
      isHaveQuestion: false
    }
  },
  mounted() {
    this.getInfos()
  },
  methods: {
    getInfos() {
      this.loading = true
      var params = {
        trialId: this.$route.query.trialId,
        taskMedicalReviewId: this.taskMedicalReviewId
      }
      getMedicalReviewReadingTask(params).then(res => {
        this.auditInfo = { ...res.Result }
        this.isSendMessage = res.Result.IsSendMessage
        this.isHaveQuestion = res.Result.MedicalReviewInfo.IsHaveQuestion
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleAudit() {
      if (this.$refs['auditConclusions'].isClosedDialog && this.$refs['auditConclusions'].form.IsHaveQuestion) {
        this.isSendMessage = this.$refs['auditConclusions'].form.IsHaveQuestion
        this.handleSign()
      } else if (!this.$refs['auditConclusions'].form.IsHaveQuestion) {
        const loading = this.$loading({ fullscreen: true })
        this.$refs['auditIssues'].handleSave(false).then(() => {
          this.$refs['auditConclusions'].handleSave(false).then(() => {
            this.isSendMessage = this.$refs['auditConclusions'].form.IsHaveQuestion
            this.handleSign()
            loading.close()
          }).catch(() => {
            loading.close()
          })
        }).catch(() => {
          loading.close()
        })
      }
    },
    handleSign() {
      const { MedicalAudit } = const_.processSignature
      this.signCode = MedicalAudit
      this.signVisible = true
    },
    handleSave() {
      const loading = this.$loading({ fullscreen: true })
      this.$refs['auditIssues'].handleSave(false).then(() => {
        this.$refs['auditConclusions'].handleSave(false).then(() => {
          this.isSendMessage = this.$refs['auditConclusions'].form.IsHaveQuestion
          this.$emit('getList')
          loading.close()
        }).catch(() => {
          loading.close()
        })
      }).catch(() => {
        loading.close()
      })
    },
    async handleLaunch() {
      var auditIssuesValid = await this.$refs['auditIssues'].validForm()
      var auditConclusionsValid = await this.$refs['auditConclusions'].validForm()
      if (auditIssuesValid && auditConclusionsValid) {
        this.$confirm(this.$t('trials:medicalFeedback:message:launchqc'), {
          type: 'warning',
          distinguishCancelAndClose: true
        })
          .then(() => {
            this.handleSave()
          }).catch(() => {})
      }
    },
    handleQc() {
      this.$refs['auditConclusions'].handleReply()
    },
    setIsHaveQuestion(isHaveQuestion) {
      this.isHaveQuestion = isHaveQuestion
    },
    // 获取下一任务
    getNextTask() {
      this.disPatchNextTask(this.auditInfo.AuditState >= 2)
    },
    getNextIRTask() {
      // 是否确认进入下一任务？
      this.$confirm(this.$t('trials:medicalFeedback:message:goNextTask04'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.loading = true
          this.$emit('nextTask', this.taskMedicalReviewId)
        })
        .catch(action => {
          this.loading = false
        })
    },
    disPatchNextTask(isComplete) {
      // '是否确认进入下一个医学审核任务？' : '当前医学审核任务未完成，是否确认进入下一个医学审核任务？'
      var message = isComplete ? this.$t('trials:medicalFeedback:message:goNextTask02') : this.$t('trials:medicalFeedback:message:goNextTask03')

      this.$confirm(message, {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.loading = true
          this.$emit('nextTask', this.taskMedicalReviewId)
        })
        .catch(action => {
          this.loading = false
        })
    },
    // 关闭签名框并设置确认状态
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名确认
    signConfirm(signInfo) {
      this.loading = true
      const params = {
        data: {
          taskMedicalReviewId: this.taskMedicalReviewId
        },
        signInfo: signInfo
      }
      FinishMedicalReview(params).then(res => {
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.$refs['signForm'].btnLoading = false
          this.signVisible = false
        }

        this.loading = false
        // this.$emit('close')
        this.$emit('getList')
        this.auditInfo.AuditState = 2
        this.$confirm(this.$t('trials:medicalFeedback:message:goNextTask01'), {
          type: 'warning',
          distinguishCancelAndClose: true
        })
          .then(() => {
            this.loading = true
            this.$emit('nextTask', this.taskMedicalReviewId)
          })
          .catch(action => {

          })
      }).catch(_ => {
        this.loading = false
        this.$refs['signForm'].btnLoading = false
      })
    },
    nextTask() {
      this.$emit('nextTask', this.taskMedicalReviewId)
    },
    handleCancel() {
      this.$emit('close')
    },
    getMedicalAuditList() {
      this.$emit('getList')
    }
  }
}
</script>
<style lang="scss" scoped>
.medical-audit-wrapper{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  margin-left: 15px;

  .medical-audit-content{
    flex: 1;
    display: flex;
    flex-direction: column;
    // justify-content: space-between;
    height: 100%;
    overflow-y: auto;
  }
  .medical-audit-bottom-btn{
    height: 100px;
    width: 100%;
    text-align: center;
  }
}
</style>
