<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>
        <!-- 审核问题 -->
        <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"
        />
      </div>
      <div>
        <!-- 结论 -->
        <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"
        />
      </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>
      <!-- 质询 -->
      <el-button v-if="auditInfo.MedicalReviewInfo && isSendMessage" type="primary" @click="handleQc">
        {{ $t('trials:medicalFeedback:title:qaRecord') }}
      </el-button>
      <!-- 审核完成 -->
      <el-button v-if="auditInfo.MedicalReviewInfo && [14, 30].includes(userTypeEnumInt) && auditInfo.AuditState !== 2" type="primary" @click="handleAudit">
        {{ $t('trials:medicalFeedback:button:auditCompleted') }}
      </el-button>

      <el-button v-if="auditInfo.MedicalReviewInfo && [14, 30].includes(userTypeEnumInt) && auditInfo.AuditState !== 2" type="primary" @click="getNextTask">
        {{ $t('trials:medicalFeedback: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
    }
  },
  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.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleAudit() {
      if (!this.$refs['auditConclusions'].isClosedDialog && this.$refs['auditConclusions'].form.IsHaveQuestion) {
        // 请先关闭质询！
        this.$alert(this.$t('trials:medicalFeedback:message:closeQC'), {
          callback: action => {}
        })
        return
      }
      this.loading = true
      this.$refs['auditIssues'].handleSave(false).then(() => {
        this.$refs['auditConclusions'].handleSave(false).then(() => {
          this.loading = false
          this.isSendMessage = this.$refs['auditConclusions'].form.IsHaveQuestion
          const { MedicalAudit } = const_.processSignature
          this.signCode = MedicalAudit
          this.signVisible = true
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
        this.loading = false
      })
      // Promise.all([this.$refs['auditIssues'].handleSave(false), this.$refs['auditConclusions'].handleSave(false)])
      //   .then(() => {
      //     this.loading = false
      //     const { MedicalAudit } = const_.processSignature
      //     this.signCode = MedicalAudit
      //     this.signVisible = true
      //   }).catch(() => {
      //     this.loading = false
      //   })
    },
    handleSave() {
      this.loading = true
      this.$refs['auditIssues'].handleSave(false).then(() => {
        this.$refs['auditConclusions'].handleSave(false).then(() => {
          this.loading = false
          this.isSendMessage = this.$refs['auditConclusions'].form.IsHaveQuestion
        }).catch(() => {
          this.loading = false
        })
      }).catch(() => {
        this.loading = false
      })
    },
    handleQc() {
      this.$refs['auditConclusions'].handleReply()
    },
    // 获取下一任务
    getNextTask() {
      this.loading = true
      this.$refs['auditIssues'].save().then(auditIssuesRes => {
        if (!auditIssuesRes) {
          this.disPatchNextTask(false)
        } else {
          this.$refs['auditConclusions'].save().then(auditConclusionsRes => {
            this.disPatchNextTask(!!(auditIssuesRes && auditConclusionsRes))
          }).catch(_ => {
            this.loading = false
          })
        }
      }).catch(_ => {
        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;

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