<template>
  <div v-loading="loading" style="min-height:400px;" class="ecrf-wrapper">
    <el-form
      v-if="isRender"
      ref="questions"
      size="small"
      :model="questionForm"
    >
      <template v-if="formType===2">
        <el-tabs v-model="activeName">
          <el-tab-pane
            v-for="q of questions"
            :key="q.PageName"
            :label="q.PageName"
            :name="q.PageName"
          >
            <div v-if="q.Childrens.length>0" :class="{'tabContent':publicQuestions.length>0}">
              <FormItem
                v-for="question of q.Childrens"
                :key="question.Id"
                :question="question"
                :question-form="questionForm"
                :reading-task-state="readingTaskState"
                :visit-task-id="visitTaskId"
                @setFormItemData="setFormItemData"
                @resetFormItemData="resetFormItemData"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
        <el-divider v-if="publicQuestions.length>0" content-position="left">
          <!-- 公共分页 -->
        </el-divider>
        <div v-for="q of publicQuestions" :key="q.PageName">
          <h4>{{ q.PageName }}</h4>
          <template v-if="q.Childrens.length>0">
            <FormItem
              v-for="question of q.Childrens"
              :key="question.Id"
              :question="question"
              :question-form="questionForm"
              :reading-task-state="readingTaskState"
              :visit-task-id="visitTaskId"
              @setFormItemData="setFormItemData"
              @resetFormItemData="resetFormItemData"
            />
          </template>
        </div>
      </template>
      <template v-else>
        <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>

      <!-- <FormItem
        v-for="question of questions"
        :key="question.Id"
        :question="question"
        :question-form="questionForm"
        :reading-task-state="readingTaskState"
        @resetFormItemData="resetFormItemData"
      /> -->
      <!-- <el-form-item v-if="readingTaskState < 2">
        <div style="text-align:center;">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </el-form-item> -->

      <el-form-item v-if="readingTaskState < 2">
        <div style="text-align:center;">
          <el-button type="primary" @click="skipTask" v-if="iseCRFShowInDicomReading">
            {{ $t('trials:readingReport:button:skip') }}
          </el-button>
          <el-button type="primary" @click="handleSave"> 
            {{ $t('common:button:save') }}
          </el-button>
          <el-button type="primary" @click="handleSubmit" v-if="iseCRFShowInDicomReading">
            {{ $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 { getTrialReadingQuestion, saveVisitTaskQuestions, submitVisitTaskQuestionsInDto, getQuestionCalculateRelation } from '@/api/trials'
import { setSkipReadingCache } from '@/api/reading'
import const_ from '@/const/sign-code'
import FormItem from './FormItem'
import SignForm from '@/views/trials/components/newSignForm'
// import { getToken } from '@/utils/auth'
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
export default {
  name: 'ECRF',
  components: {
    FormItem,
    SignForm
  },
  props: {
    trialId: {
      type: String,
      required: true
    },
    subjectId: {
      type: String,
      required: true
    },
    criterionId: {
      type: String,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    iseCRFShowInDicomReading: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      questions: [],
      questionForm: {},
      publicQuestions: [],
      isRender: false,
      signVisible: false,
      signCode: null,
      currentUser: zzSessionStorage.getItem('userName'),
      readingTaskState: 0,
      activeName: 0,
      formType: null,
      classArr: [],
      calculationList: []
    }
  },
  mounted() {
    this.getQuestionCalculateRelation()
    this.getQuestions()
    DicomEvent.$on('refreshQuestionAnswer', _ => {
      this.getQuestions()
    })
  },
  methods: {
    async getQuestions() {
      this.loading = true
      try {
        const param = {
          readingQuestionCriterionTrialId: this.criterionId,
          visitTaskId: this.visitTaskId
        }
        const res = await getTrialReadingQuestion(param)
        if (res.IsSuccess) {
          this.readingTaskState = res.OtherInfo.readingTaskState
          this.formType = res.OtherInfo.FormType
          if (res.OtherInfo.FormType === 2) {
            if (res.Result.MultiPage.length > 0) {
              res.Result.MultiPage.map((v) => {
                if (v.Type === 'group' && v.Childrens.length === 0) return
                if (!v.IsPage && v.Type !== 'group' && v.Type !== 'summary') {
                  this.$set(this.questionForm, v.Id, v.Answer ? v.Answer : null)
                }
                if (v.Type === 'class') {
                  this.classArr.push({triggerId: v.ClassifyQuestionId, classId: v.Id, classifyAlgorithms: v.ClassifyAlgorithms, classifyType: v.ClassifyType})
                }
                if (v.Childrens.length > 0) {
                  this.setChild(v.Childrens)
                }
              })
              this.questions = res.Result.MultiPage
              this.activeName = res.Result.MultiPage[0].PageName
            }
            if (res.Result.PublicPage.length > 0) {
              res.Result.PublicPage.map((v) => {
                if (v.Type === 'group' && v.Childrens.length === 0) return
                if (!v.IsPage && v.Type !== 'group' && v.Type !== 'summary') {
                  this.$set(this.questionForm, v.Id, v.Answer ? v.Answer : null)
                }
                if (v.Type === 'class') {
                  this.classArr.push({triggerId: v.ClassifyQuestionId, classId: v.Id, classifyAlgorithms: v.ClassifyAlgorithms, classifyType: v.ClassifyType})
                }
                if (v.Childrens.length > 0) {
                  this.setChild(v.Childrens)
                }
              })
              this.publicQuestions = res.Result.PublicPage
            }
          } else {
            res.Result.SinglePage.map((v) => {
              if (v.Type === 'group' && v.Childrens.length === 0) return
              if (!v.IsPage && v.Type !== 'group' && v.Type !== 'summary') {
                this.$set(this.questionForm, v.Id, v.Answer ? v.Answer : null)
              }
              if (v.Type === 'class') {
                this.classArr.push({triggerId: v.ClassifyQuestionId, classId: v.Id, classifyAlgorithms: v.ClassifyAlgorithms, classifyType: v.ClassifyType})
              }
              if (v.Childrens.length > 0) {
                this.setChild(v.Childrens)
              }
            })
            this.questions = res.Result.SinglePage
          }
          this.isRender = true
        }
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    setChild(obj) {
      obj.forEach(i => {
        if (i.Type !== 'group' && i.Type !== 'summary' && i.Id) {
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
        }
        if (i.Type === 'class') {
          this.classArr.push({triggerId: i.ClassifyQuestionId, classId: i.Id, classifyAlgorithms: i.ClassifyAlgorithms, classifyType: i.ClassifyType})
        }
        if (i.Childrens && i.Childrens.length > 0) {
          this.setChild(i.Childrens)
        }
      })
    },
    async getQuestionCalculateRelation() {
      try {
        let res = await getQuestionCalculateRelation({TrialReadingCriterionId: this.criterionId})
        this.calculationList = res.Result
      } catch(e) {
        console.log(e)
      }
    },
    async handleSave() {
      const valid = await this.$refs['questions'].validate()
      if (!valid) return
      this.loading = true
      const answers = []
      for (const k in this.questionForm) {
        answers.push({ readingQuestionTrialId: k, answer: this.questionForm[k] })
      }
      const params = {
        trialId: this.trialId,
        visitTaskId: this.visitTaskId,
        readingQuestionCriterionTrialId: this.criterionId,
        answerList: answers
      }
      try {
        const res = await saveVisitTaskQuestions(params)
        if (res.IsSuccess) {
          DicomEvent.$emit('getReportInfo', true)
          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
      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) {
          DicomEvent.$emit('getReportInfo', true)
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.isEdit = false
          this.$refs['signForm'].btnLoading = false
          this.signVisible = false
          this.readingTaskState = 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
            let list = JSON.parse(i.classifyAlgorithms)
            if (i.classifyType === 0) {
              let o = list.find(v => {
                return (
                  parseFloat(obj.val) >= parseFloat(v.gt) &&
                  parseFloat(obj.val) < parseFloat(v.lt)
                )
              })
              answer = o ? o.label : null 
            } else if (i.classifyType === 1) {
              let 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>
.tabContent{
  height:400px;
  overflow-y: auto;
}
</style>
