<template>
  <div v-loading="loading" class="ecrf-list-container">
    <el-form v-if="taskInfo" ref="questions" size="small" :model="questionForm" class="ecrf-form">
      <template v-if="taskInfo.CriterionType === 16">
        <FormItem v-for="question of questions" :key="question.Id" :question="question" :question-form="questionForm"
          :reading-task-state="readingTaskState" :visit-task-id="visitTaskId" :calculation-list="calculationList"
          @setFormItemData="setFormItemData" @resetFormItemData="resetFormItemData" />
      </template>
      <template v-else>
        <QuestionFormItem v-for="question of questions" :key="question.Id" :visit-task-id="visitTaskId"
          :question="question" :question-form="questionForm" :reading-task-state="readingTaskState"
          :criterion-id="criterionId" :calculation-list="calculationList" :is-baseline="isBaseline"
          @resetFormItemData="resetFormItemData" @setFormItemData="setFormItemData" />
      </template>

      <el-form-item v-if="readingTaskState < 2">
        <div style="text-align:center;">
          <el-button v-if="taskInfo && taskInfo.IseCRFShowInDicomReading" type="primary" @click="skipTask">
            {{ $t('trials:readingReport:button:skip') }}
          </el-button>
          <el-button type="primary" @click="handleSave">
            {{ $t('common:button:save') }}
          </el-button>
          <el-button v-if="taskInfo && taskInfo.IseCRFShowInDicomReading" type="primary" @click="handleSubmit">
            {{ $t('common:button:submit') }}
          </el-button>
        </div>
      </el-form-item>
    </el-form>

    <!-- 签名框 -->
    <el-dialog v-if="signVisible" :visible.sync="signVisible" :close-on-click-modal="false" width="600px"
      custom-class="base-dialog-wrapper">
      <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 { getCustomTableQuestionAnswer, changeDicomReadingQuestionAnswer, submitVisitTaskQuestionsInDto, getQuestionCalculateRelation, verifyVisitTaskQuestions } from '@/api/trials'
import { setSkipReadingCache } from '@/api/reading'
import const_ from '@/const/sign-code'
import store from '@/store'
import { mapGetters } from 'vuex'
import FormItem from './FormItem'
import QuestionFormItem from '@/views/trials/trials-panel/reading/dicoms/customize/CustomizeQuestionFormItem'
import SignForm from '@/views/trials/components/newSignForm'
export default {
  name: 'EcrfList',
  components: {
    QuestionFormItem,
    SignForm,
    FormItem
  },
  props: {
    visitTaskInfo: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      trialId: '',
      criterionId: '',
      visitTaskId: '',
      loading: false,
      questions: [],
      questionForm: {},
      publicQuestions: [],
      signVisible: false,
      signCode: null,
      currentUser: zzSessionStorage.getItem('userName'),
      readingTaskState: 2,
      activeName: 0,
      classArr: [],
      calculationList: [],
      taskInfo: null,
      isBaseline: false,
      digitPlaces: 2
    }
  },
  computed: {
    ...mapGetters(['currentTaskState'])
  },
  watch: {
    'visitTaskInfo.VisitTaskId': {
      immediate: true,
      handler(id) {
        this.trialId = this.$route.query.trialId
        this.criterionId = this.$route.query.TrialReadingCriterionId
        if (!id) return
        this.visitTaskId = id
        this.getQuestionCalculateRelation()
        this.getQuestions()
      }
    },
    currentTaskState: {
      immediate: true,
      handler(state) {
        console.log(state)
        if (state === 2) {
          this.readingTaskState = 2
        }
      }
    }
  },
  mounted() {
    this.taskInfo = JSON.parse(localStorage.getItem('taskInfo'))
    this.isBaseline = this.taskInfo.IsBaseLine
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
  },
  methods: {
    async getQuestions(visitTaskId) {
      this.loading = true
      try {
        const param = {
          visitTaskId: this.visitTaskId
        }
        const res = await getCustomTableQuestionAnswer(param)
        if (res.IsSuccess) {
          this.readingTaskState = res.OtherInfo.ReadingTaskState
          res.Result.SinglePage.map((v) => {
            if (v.Type === 'group' && v.Childrens.length === 0) return
            if (!v.IsPage && v.Type !== 'group' && v.Type !== 'summary' && v.Type !== 'table' && v.Type !== 'basicTable' && v.Type !== 'number') {
              this.$set(this.questionForm, v.Id, v.Answer)
            }
            if (v.Type === 'table' || v.Type === 'basicTable') {
              this.$set(this.questionForm, v.Id, v.TableQuestions.Answers)
            }
            if (v.Type === 'class') {
              this.classArr.push({ triggerId: v.ClassifyQuestionId, classId: v.Id, classifyAlgorithms: v.ClassifyAlgorithms, classifyType: v.ClassifyType })
            }
            if (v.Type === 'number') {
              this.$set(this.questionForm, v.Id, isNaN(parseFloat(v.Answer)) ? v.Answer : parseFloat(v.Answer).toFixed(this.digitPlaces))
            }
            if (v.Childrens.length > 0) {
              this.setChild(v.Childrens)
            }
          })
          this.questions = res.Result.SinglePage
          this.loading = false
        }
      } catch (e) {
        console.log(e)
        this.loading = false
      }
    },
    setChild(obj) {
      obj.forEach(i => {
        if (i.Type !== 'group' && i.Type !== 'summary' && i.Id && i.Type !== 'table' && i.Type !== 'basicTable') {
          this.$set(this.questionForm, i.Id, i.Answer)
        }
        if (i.Type === 'table' || i.Type === 'basicTable') {
          i.TableQuestions.Questions.forEach(o => {
            if (o.Type === 'number') {
              i.TableQuestions.Answers.forEach((ite, index) => {
                this.$set(i.TableQuestions.Answers[index], o.Id, !isNaN(parseFloat(i.TableQuestions.Answers[index][o.Id])) ? parseFloat(i.TableQuestions.Answers[index][o.Id]).toFixed(this.digitPlaces) : i.TableQuestions.Answers[index][o.Id])
              })
            }
          })
          this.$set(this.questionForm, i.Id, i.TableQuestions.Answers)
        }
        if (i.Type === 'class') {
          this.classArr.push({ triggerId: i.ClassifyQuestionId, classId: i.Id, classifyAlgorithms: i.ClassifyAlgorithms, classifyType: i.ClassifyType })
        }
        if (i.Type === 'number') {
          this.$set(this.questionForm, i.Id, isNaN(parseFloat(i.Answer)) ? i.Answer : parseFloat(i.Answer).toFixed(this.digitPlaces))
        }
        if (i.Childrens && i.Childrens.length > 0) {
          this.setChild(i.Childrens)
        }
      })
    },
    async getQuestionCalculateRelation() {
      try {
        const res = await getQuestionCalculateRelation({ TrialReadingCriterionId: this.criterionId })
        this.calculationList = res.Result
      } catch (e) {
        console.log(e)
      }
    },
    async handleSave(isMsg) {
      const valid = await this.$refs['questions'].validate()
      if (!valid) return
      this.loading = true
      try {
        var answers = []
        for (const k in this.questionForm) {
          if (this.questionForm[k] instanceof Array) { } else {
            answers.push({ id: k, answer: this.questionForm[k] })
          }
        }
        var params = {
          visitTaskId: this.visitTaskId,
          answers: answers
        }
        const res = await changeDicomReadingQuestionAnswer(params)
        if (res.IsSuccess) {
          if (isMsg) {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          }
          this.loading = false
        }
      } catch (e) {
        this.loading = false
      }
    },
    async handleSubmit() {
      const valid = await this.$refs['questions'].validate()
      if (!valid) return
      await this.handleSave(false)
      await verifyVisitTaskQuestions({ visitTaskId: this.visitTaskId })
      const { ImageAssessmentReportConfirmation } = const_.processSignature
      this.signCode = ImageAssessmentReportConfirmation
      this.signVisible = true
    },
    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名并确认
    async signConfirm(signInfo) {
      this.loading = true
      var answers = []
      for (const k in this.questionForm) {
        answers.push({ readingQuestionTrialId: k, answer: this.questionForm[k] })
      }
      var params = {
        data: {
          trialId: this.trialId,
          visitTaskId: this.visitTaskId,
          readingQuestionCriterionTrialId: this.criterionId,
          answerList: answers
        },
        signInfo: signInfo
      }
      try {
        const res = await submitVisitTaskQuestionsInDto(params)
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.isEdit = false
          this.$refs['signForm'].btnLoading = false
          this.signVisible = false
          this.readingTaskState = 2
          this.taskInfo.ReadingTaskState = 2
          localStorage.setItem('taskInfo', JSON.stringify(this.taskInfo))
          store.dispatch('noneDicomReview/setCurrentTaskState', 2)
          window.opener.postMessage('refreshTaskList', window.location)
          const confirm = await this.$confirm(
            this.$t('trials:noneDicoms:message:msg1'),
            {
              type: 'warning',
              distinguishCancelAndClose: true
            }
          )
          if (confirm !== 'confirm') return
          window.location.reload()
        }
      } catch (e) {
        this.loading = false
        this.$refs['signForm'].btnLoading = false
      }
    },
    async skipTask() {
      try {
        // 是否确认跳过？
        const confirm = await this.$confirm(
          this.$t('trials:readingReport:message:skipConfirm'),
          {
            type: 'warning',
            distinguishCancelAndClose: true
          }
        )
        if (confirm !== 'confirm') return
        this.loading = true
        const res = await setSkipReadingCache({ visitTaskId: this.visitTaskId })
        this.loading = false
        if (res.IsSuccess) {
          window.location.reload()
        }
      } catch (e) {
        this.loading = false
        console.log(e)
      }
    },
    resetFormItemData(v) {
      this.questionForm[v] = null
    },
    setFormItemData(obj) {
      this.$set(this.questionForm, obj.key, JSON.parse(JSON.stringify(obj.val)))
      this.classArr.map(i => {
        if (i.triggerId === obj.key) {
          let answer = null
          const list = JSON.parse(i.classifyAlgorithms)
          if (i.classifyType === 0) {
            const o = list.find(v => {
              return (
                parseFloat(obj.val) >= parseFloat(v.gt) &&
                parseFloat(obj.val) < parseFloat(v.lt)
              )
            })
            answer = o ? o.label : 'NE'
          } else if (i.classifyType === 1) {
            const o = list.find(v => {
              return v.val.includes(obj.val)
            })
            answer = o ? o.label : null
          }
          this.$set(this.questionForm, i.classId, answer)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.ecrf-list-container {
  min-height: 400px;
  color: #ddd;

  .ecrf-form {
    ::v-deep .el-form-item__label {
      color: #ddd;
    }

  }

  ::v-deep .el-table,
  .el-table__expanded-cell {
    background-color: #000;
    color: #fff;
    border-color: #444444;
  }

  ::v-deep .el-table th,
  .el-table tr {
    background-color: #000;
    color: #fff;
    border-color: #444444;
  }

  ::v-deep .el-table__body tr>td {
    background-color: #000 !important;
    color: #fff;
    border-color: #444444;
  }

  ::v-deep .el-table__body tr:hover>td {
    background-color: #858282 !important;
    color: #fff;
    border-color: #444444;
  }

  ::v-deep .el-table--border th.gutter:last-of-type {
    border: none;
  }

  ::v-deep .el-dialog {
    background: #1e1e1e;
    border: 1px solid #ddd;
    color: #ddd;

    .el-dialog__title {
      color: #fff;
    }

    .el-input .el-input__inner {
      background-color: transparent;
      color: #ddd;
      border: 1px solid #5e5e5e;
    }

    .el-input.is-disabled .el-input__inner {
      background-color: #646464a1;
    }

    .el-form-item__label {
      color: #dfdfdf
    }
  }
}
</style>
