<template>
  <div v-loading="loading" class="ecrf-wrapper">
    <el-form v-if="questions.length > 0" ref="questions" size="small" :model="questionForm">
      <template v-for="question of questions">
        <QuestionItem v-if="question.QuestionClassify === 0" :key="question.Id" :question="question"
          :question-form="questionForm" :reading-task-state="readingTaskState" :visit-task-id="visitTaskId"
          :pet5p-s="questionForm[pet5PSId]" :lung-is-inside-volume="lungIsInsideVolume"
          :liver-is-inside-volume="liverIsInsideVolume" @setFormItemData="setFormItemData"
          @resetFormItemData="resetFormItemData" @handleReadingChart="handleReadingChart" />
      </template>
      <el-form-item v-if="readingTaskState < 2">
        <div style="text-align:right">
          <el-button :loading="saveLoading" :disabled="saveLoading || !questionFormChangeState" :type="questionFormChangeState ? 'primary' : null" size="mini"
            @click="handleSave">{{ $t('common:button:save') }}</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>

import { saveTaskQuestion, getDicomReadingQuestionAnswer, getReadingCalculationData } from '@/api/trials'
import { getToken } from '@/utils/auth'
import QuestionItem from './QuestionItem'
import { mapGetters } from 'vuex'
import FusionEvent from './FusionEvent'

export default {
  name: 'ECRF',
  components: {
    QuestionItem
  },
  data() {
    return {
      loading: false,
      questions: [],
      questionForm: {},
      readingTaskState: 2,
      isBaseLineTask: false,
      visitTaskId: '',
      measurements: [],
      currentQsId: '',
      pet5PSId: '',
      pet5PSCommentsId: '',
      calculatePet5PS: null,
      liverSuvmaxId: '',
      lungSuvmaxId: '',
      suvmaxId: '',
      questionFormChangeState: false,
      questionFormChangeNum: 0,
      lungIsInsideVolume: true,
      liverIsInsideVolume: true,
      uptakeFromBaselineId: '',
      focalFDGId: '',
      baseLinePET5PS: null,
      liverRender: true,
      lungRender: true,
      saveLoading: false
    }
  },
  computed: {
    ...mapGetters(['currentReadingTaskState'])
  },
  watch: {
    questionForm: {
      deep: true,
      immediate: false,
      handler(v) {
        if (this.questionFormChangeNum === 0) {
          this.questionFormChangeNum++
        } else {
          this.questionFormChangeState = true
        }
      }
    },
    currentReadingTaskState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.readingTaskState = val
        }
      }
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.visitTaskId = this.$route.query.visitTaskId
    this.readingTaskState = parseInt(this.$route.query.readingTaskState)
    this.isBaseLineTask = this.$route.query.isBaseLineTask === 'true'
    this.initPage()
    FusionEvent.$on('resetSuvQuestions', () => {
      console.log('resetSuvQuestions')
      this.resetSuvQuestions()
    })
    FusionEvent.$on('addAnnotation', obj => {
      // this.$set(obj, 'SaveEnum', 1)
      this.addAnnotation(obj)
    })
    FusionEvent.$on('removeAnnotation', obj => {
      this.$set(obj, 'SaveEnum', 0)
      this.removeAnnotation(obj)
    })
    FusionEvent.$on('locateAnnotation', obj => {
      this.locateAnnotation(obj)
    })
    FusionEvent.$on('saveAnnotation', obj => {
      this.saveAnnotation(obj)
    })
    FusionEvent.$on('viewAnnotations', obj => {
      console.log('viewAnnotations')
      this.viewAnnotations(obj)
    })
  },
  beforeDestroy() {
    FusionEvent.$off('refreshQuestions')
    FusionEvent.$off('resetSuvQuestions')
    FusionEvent.$off('addAnnotation')
    FusionEvent.$off('removeAnnotation')
    FusionEvent.$off('locateAnnotation')
  },
  methods: {
    handleReadingChart(e) {
      this.$emit('handleReadingChart', e)
    },
    getQuestions1() {
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)

      if (idx > -1) {
        this.readingTaskState = this.visitTaskList[idx].ReadingTaskState
        var questions = this.visitTaskList[idx].Questions
        this.questions =
          questions.map((v) => {
            if (v.QuestionClassify === 0) {
              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.Childrens.length > 0) {
                this.setChild(v.Childrens)
              }
            }
          })
        this.questions = questions
      }
    },
    async initPage() {
      if (!this.isBaseLineTask) {
        this.loading = true
        var res = await getReadingCalculationData({ visitTaskId: this.visitTaskId })
        this.baseLinePET5PS = res.Result.BaseLinePET5PS
        this.calculatePet5PS = res.Result.CalculatePET5PS
        this.loading = false
      }
      this.initList(true)
    },
    async initList(isInit) {
      this.loading = true
      try {
        const params = {
          trialId: this.trialId,
          visitTaskId: this.visitTaskId,
          questionClassify: 0
        }
        const res = await getDicomReadingQuestionAnswer(params)
        if (res.IsSuccess) {
          const questions = res.Result

          questions.map((v) => {
            v.IsBaseLineTask = this.isBaseLineTask
            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.Childrens.length > 0) {
              this.setChild(v.Childrens)
            }
          })
          console.log(this.questionForm, questions)
          this.questions = questions
          this.setPet5PSCommentDisplay()
          this.measurements = []
          res.OtherInfo.QuestionMarkInfoList.forEach(i => {
            if (i.OtherMeasureData) {
              i.OtherMeasureData = JSON.parse(i.OtherMeasureData)
              if (i.QuestionType === 51 && isInit) {
                this.liverRender = false
              } else if (i.QuestionType === 52 && isInit) {
                this.lungRender = false
              }
            }
            this.measurements.push(i)
          })
        }
        this.loading = false
      } catch (e) {
        console.log(e)
        this.loading = false
      }
    },
    setChild(obj) {
      obj.forEach(i => {
        i.IsBaseLineTask = this.isBaseLineTask
        if (i.QuestionClassify === 0) {
          if (i.Type !== 'group' && i.Type !== 'summary' && i.Id) {
            this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
          }
          if (i.QuestionType === 51) {
            // 肝脏血池SUVmax(51);
            this.liverSuvmaxId = i.Id
            this.$set(i, 'SaveEnum', 0)
          }
          if (i.QuestionType === 52) {
            // 纵膈血池SUVmax(52);
            this.lungSuvmaxId = i.Id
            this.$set(i, 'SaveEnum', 0)
          }
          if (i.QuestionType === 53) {
            // SUVmax;
            this.suvmaxId = i.Id
          }
          if (i.QuestionType === 55) {
            // PET 5PS评分
            this.pet5PSId = i.Id
          }
          if (i.QuestionType === 59) {
            // 修改PET 5PS评分备注
            this.pet5PSCommentsId = i.Id
          }
          if (i.QuestionType === 56) {
            // 与基线相比摄取值变化
            this.uptakeFromBaselineId = i.Id
          }
          if (i.QuestionType === 57) {
            // 骨髓中存在局灶性FDG亲和病灶的证据
            this.focalFDGId = i.Id
          }
          if (i.Childrens && i.Childrens.length > 0) {
            this.setChild(i.Childrens)
          }
        }
      })
    },
    handleSave() {
      if (this.saveLoading) return
      this.saveLoading = true
      this.$refs['questions'].validate((valid) => {
        if (!valid) {
          this.saveLoading = false
          return
        }
        // 是否有标记未保存
        var existUnSave = this.checkAnnotationStatus(this.questions)
        if (existUnSave) {
          this.$alert(this.$t('trials:lugano:message:saveWarning1'), this.$t('trials:lugano:fusionDialog:warning'))
          this.saveLoading = false
          return
        }
        this.saveQuestionsForm()
        // else if (pet5PS > 1 && (!liverSUVmax || !lungSUVmax)) {
        //   this.$alert('pet 5ps评分不为1，X或者NE，需要进行标记！', '提示', {
        //     // confirmButtonText: '确定',
        //     callback: action => {

        //     }
        //   })
        // }
      })
    },
    async saveQuestionsForm() {
      this.loading = true
      try {
        var answers = []
        for (const k in this.questionForm) {
          answers.push({ id: k, answer: this.questionForm[k] })
        }
        var params = {
          visitTaskId: this.visitTaskId,
          answers: answers
        }
        const res = await saveTaskQuestion(1, params)
        if (res.IsSuccess) {
          window.opener.postMessage({ type: 'petctLesionUpdate' }, window.location)
          this.loading = false
          this.questionFormChangeState = false
          this.saveLoading = false
          this.$message({ message: this.$t('common:message:savedSuccessfully'), type: 'success', duration: 2000 })
        }
      } catch (e) {
        console.log(e)
        this.loading = false
        this.saveLoading = false
      }
    },
    checkAnnotationStatus(obj) {
      for (let i = 0; i < obj.length; i++) {
        if (obj[i].SaveEnum === 1) {
          return true
        }
        if (obj[i].Childrens && obj[i].Childrens.length > 0) {
          if (this.checkAnnotationStatus(obj[i].Childrens)) {
            return true
          }
        }
      }
    },
    addAnnotation(obj) {
      const { Id, QuestionType } = obj
      this.currentQsId = Id
      var idx = this.measurements.findIndex(i => i.QuestionId === Id)
      var orderMarkName = QuestionType === 51 ? 'Liver' : QuestionType === 52 ? 'Mediastinum' : ''
      if (idx === -1) {
        // 脾脏长度(48); 肝脏血池SUVmax(51); 纵膈血池SUVmax(52)
        this.measurements.push({ QuestionId: Id, QuestionType: QuestionType, StudyId: '', SeriesId: '', InstanceId: '', MarkTool: '', PicturePath: '', NumberOfFrames: '', OtherMeasureData: '', OrderMarkName: orderMarkName })
      } else {
        if (!this.measurements[idx].OrderMarkName) {
          this.measurements[idx].OrderMarkName = orderMarkName
        }
        if (!this.measurements[idx].QuestionType) {
          this.measurements[idx].QuestionType = QuestionType
        }
      }
      this.$emit('setNonTargetMeasurementStatus', { status: true, toolName: 'CircleROI' })
    },

    removeAnnotation(obj) {
      const { Id } = obj
      var idx = this.measurements.findIndex(i => i.QuestionId === Id)
      if (idx === -1) return
      this.$set(this.questionForm, Id, '')

      if (!this.questionForm[this.liverSuvmaxId] && !this.questionForm[this.lungSuvmaxId]) {
        this.clearPet5PS()
      }
      // var pet5PS = this.setpet5PS()
      // this.questionForm[this.pet5PSId] = pet5PS
      // this.calculatePet5PS = pet5PS
      // this.setPet5PSCommentDisplay()
      // this.setUptakeFormBaseline()
      FusionEvent.$emit('removeAnnotation', { otherMeasureData: this.measurements[idx].OtherMeasureData, type: 'clear' })
      var remark = this.measurements[idx].OtherMeasureData.data.remark
      remark === 'Liver' ? this.liverIsInsideVolume = true : remark === 'Mediastinum' ? this.lungIsInsideVolume = true : ''
      this.setQuestionStatus(this.questions, this.measurements[idx].QuestionType)
      this.measurements.splice(idx, 1)
    },
    locateAnnotation(obj) {
      console.log('locateAnnotation')
      const { Id } = obj
      var idx = this.measurements.findIndex(i => i.QuestionId === Id)
      if (idx === -1) return
      var otherMeasureData = this.measurements[idx].OtherMeasureData

      FusionEvent.$emit('imageLocation', { otherMeasureData: otherMeasureData })
    },
    clearPet5PS() {
      this.questionForm[this.pet5PSId] = ''
      this.questionForm[this.uptakeFromBaselineId] = ''
      for (let i = 0; i < this.questions[0].Childrens[0].Childrens.length; i++) {
        if (this.questions[0].Childrens[0].Childrens[i].QuestionType === 59) {
          this.questions[0].Childrens[0].Childrens[i].ShowQuestion = 2
          this.questions[0].Childrens[0].Childrens[i].IsRequired = 3
          this.questionForm[this.pet5PSCommentsId] = ''
          break
        }
      }
    },
    saveAnnotation(question) {
      if ((question.QuestionType === 51 && !this.liverIsInsideVolume) || (question.QuestionType === 52 && !this.lungIsInsideVolume)) {
        // 当前标记在图像外
        this.$alert(this.$t('trials:reading:lugano:warnning:outsideVolume'), this.$t('trials:lugano:fusionDialog:warning'), {
          callback: action => {

          }
        })
        return
      }
      // 肝脏血池SUVmax
      const liverSUVmax = !isNaN(parseFloat(this.questionForm[this.liverSuvmaxId])) ? parseFloat(this.questionForm[this.liverSuvmaxId]) : 0
      // 纵膈血池SUVmax
      const lungSUVmax = !isNaN(parseFloat(this.questionForm[this.lungSuvmaxId])) ? parseFloat(this.questionForm[this.lungSuvmaxId]) : 0
      // const pet5PS = !isNaN(parseInt(this.questionForm[this.pet5PSId])) ? parseInt(this.questionForm[this.pet5PSId]) : 0
      if (liverSUVmax && lungSUVmax && (liverSUVmax <= lungSUVmax)) {
        // '当前肝脏血池SUVmax≤纵隔血池血池SUVmax，请确认！'
        this.$confirm(this.$t('trials:lugano:message:validLung'), this.$t('trials:lugano:fusionDialog:warning'), {
          type: 'warning'
        }).then(() => {
          this.handleSaveAnnotation(question)
        }).catch(() => {

        })
      } else {
        this.handleSaveAnnotation(question)
      }
    },
    handleSaveAnnotation(question) {
      const loading = this.$loading({ fullscreen: true })
      // 获取截图
      var answers = []
      var questionMarkInfoList = []
      var annotationObj = this.measurements.find(i => i.QuestionType === question.QuestionType)
      var obj = annotationObj ? Object.assign({}, annotationObj) : null
      FusionEvent.$emit('getScreenshots', { otherMeasureData: obj ? obj.OtherMeasureData : null }, async val => {
        var pictureObj = null
        var picturePath = null
        if (obj && obj.OtherMeasureData) {
          pictureObj = await this.uploadScreenshots(`${new Date().getTime()}`, val)
          picturePath = pictureObj.isSuccess ? this.$getObjectName(pictureObj.result.url) : ''
          var otherMeasureData = Object.assign({}, obj.OtherMeasureData)
          for (const k in otherMeasureData.data.cachedStats) {
            otherMeasureData.data.cachedStats[k].pointsInShape = []
          }
          obj.OtherMeasureData = JSON.stringify(otherMeasureData)
          obj.OtherPicturePath = picturePath
          questionMarkInfoList.push(obj)
        }
        for (const k in this.questionForm) {
          if (k === question.Id) {
            answers.push({ id: k, answer: this.questionForm[k] })
            break
          }
        }
        try {
          var params = {
            visitTaskId: this.visitTaskId,
            answers,
            questionMarkInfoList
          }
          const qsType = question.QuestionType === 51 ? 2 : question.QuestionType === 52 ? 3 : null

          const res = await saveTaskQuestion(qsType, params)
          if (res.IsSuccess) {
            this.$set(question, 'SaveEnum', 0)
            window.opener.postMessage({ type: 'petctLesionUpdate' }, window.location)
            loading.close()
            this.$message({ message: this.$t('common:message:savedSuccessfully'), type: 'success', duration: 2000 })
            this.resetSuvQuestions(1)
          }
          loading.close()
        } catch (e) {
          console.log(e)
          loading.close()
        }
      })
    },
    viewAnnotations(question) {
      var token = getToken()
      var subjectCode = this.$route.query.subjectCode
      var path = `/historyScreenshot?&subjectCode=${subjectCode}&visitTaskId=${this.visitTaskId}&questionType=${question.QuestionType}&TokenKey=${token}`
      FusionEvent.$emit('viewHistoryScreenshot', path)
    },
    setMeasuredData(measurement) {
      if (measurement.data.isHandleOutsideImage) {
        this.setOutsideMeasuredData(measurement)
      } else {
        var idx = -1
        if (this.currentQsId) {
          // 新增
          idx = this.measurements.findIndex(i => i.QuestionId === this.currentQsId)
          this.currentQsId = ''
        } else {
          // 编辑
          idx = this.measurements.findIndex(i => i.OrderMarkName === measurement.data.data.remark)
        }
        if (idx === -1) return
        var obj = this.measurements[idx]
        var remark = obj.QuestionType === 51 ? 'Liver' : obj.QuestionType === 52 ? 'Mediastinum' : ''
        obj.QuestionType === 51 ? this.liverIsInsideVolume = true : obj.QuestionType === 52 ? this.lungIsInsideVolume = true : ''
        measurement.data.data.remark = remark
        this.measurements[idx].OtherMeasureData = measurement.data
        this.measurements[idx].OtherMarkTool = measurement.data.metadata.toolName

        //  添加标记
        var data = {
          OtherMeasureData: measurement.data,
          QuestionId: obj.QuestionId,
          VisitTaskId: this.visitTaskId,
          OrderMarkName: remark
        }
        if (measurement.type === 'CircleROI') {
          this.$set(this.questionForm, obj.QuestionId, measurement.suvMax || null)
        }
        // if (measurement.type === 'CircleROI') {
        //   const suvMax = measurement.suvMax

        //   if (this.questionForm[obj.QuestionId] !== suvMax) {
        //     this.setPet5PSCommentDisplay()
        //     this.$set(this.questionForm, obj.QuestionId, suvMax || null)
        //     var pet5PS = this.setpet5PS()
        //     this.questionForm[this.pet5PSId] = pet5PS
        //     this.calculatePet5PS = pet5PS
        //     this.setUptakeFormBaseline()
        //   }
        // }
        FusionEvent.$emit('addOrUpdateAnnotations', { data })
        this.questionFormChangeState = true
        if (obj.QuestionType === 51 && !this.liverRender) {
          this.liverRender = true
        } else if (obj.QuestionType === 52 && !this.lungRender) {
          this.lungRender = true
        } else {
          this.setQuestionStatus(this.questions, this.measurements[idx].QuestionType)
        }
      }
    },
    setQuestionStatus(obj, questionType) {
      for (let i = 0; i < obj.length; i++) {
        if (obj[i].QuestionType === questionType) {
          this.$set(obj[i], 'SaveEnum', 1)
          return true
        }
        if (obj[i].Childrens && obj[i].Childrens.length > 0) {
          if (this.setQuestionStatus(obj[i].Childrens, questionType)) {
            return true
          }
        }
      }
    },
    setOutsideMeasuredData(measurement) {
      if ((measurement.data.remark === 'Liver' && this.liverIsInsideVolume === false) || (measurement.data.remark === 'Mediastinum' && this.lungIsInsideVolume === false)) {
        return
      }

      var idx = -1
      if (this.currentQsId) {
        // 新增
        idx = this.measurements.findIndex(i => i.QuestionId === this.currentQsId)
        this.currentQsId = ''
      } else {
        // 编辑
        idx = this.measurements.findIndex(i => i.OrderMarkName === measurement.data.data.remark)
      }
      if (idx === -1) return
      var obj = this.measurements[idx]
      var remark = obj.QuestionType === 51 ? 'Liver' : obj.QuestionType === 52 ? 'Mediastinum' : ''
      obj.QuestionType === 51 ? this.liverIsInsideVolume = false : obj.QuestionType === 52 ? this.lungIsInsideVolume = false : ''
      measurement.data.data.remark = remark
      this.measurements[idx].OtherMeasureData = measurement.data
      this.measurements[idx].OtherMarkTool = measurement.data.metadata.toolName

      //  添加标记
      var data = {
        OtherMeasureData: measurement.data,
        QuestionId: obj.QuestionId,
        VisitTaskId: this.visitTaskId,
        OrderMarkName: remark
      }
      if (measurement.type === 'CircleROI') {
        this.$set(this.questionForm, obj.QuestionId, null)
      }
      // if (measurement.type === 'CircleROI') {
      //   this.setPet5PSCommentDisplay()
      //   this.$set(this.questionForm, obj.QuestionId, null)
      //   var pet5PS = this.setpet5PS()
      //   this.questionForm[this.pet5PSId] = pet5PS
      //   this.calculatePet5PS = pet5PS
      //   this.setUptakeFormBaseline()
      // }
      FusionEvent.$emit('addOrUpdateAnnotations', { data })
      this.questionFormChangeState = true
      this.setQuestionStatus(this.questions, this.measurements[idx].QuestionType)
    },
    clearMeasuredData(remark) {
      var idx = this.measurements.findIndex(i => i.OrderMarkName === remark)
      if (idx === -1) return
      this.$set(this.questionForm, this.measurements[idx].QuestionId, '')
      // var pet5PS = this.setpet5PS()
      // this.questionForm[this.pet5PSId] = pet5PS
      // this.calculatePet5PS = pet5PS
      // this.setPet5PSCommentDisplay()
      // this.setUptakeFormBaseline()
      this.measurements[idx].OtherMeasureData = ''
      this.currentQsId = this.measurements[idx].QuestionId
      // const { QuestionId, QuestionType } = this.measurements[idx]
      this.questionFormChangeState = true
      remark === 'Liver' ? this.liverIsInsideVolume = true : remark === 'Mediastinum' ? this.lungIsInsideVolume = true : ''
    },
    resetFormItemData(v) {
      this.questionForm[v] = null
    },
    setFormItemData(obj) {
      this.questionForm[obj.key] = obj.val
      if (obj.key === this.pet5PSId) {
        this.setPet5PSCommentDisplay()
        this.setUptakeFormBaseline()
        this.setfocalFDG()
      }
    },
    setPet5PSCommentDisplay() {
      if (this.pet5PSCommentsId && this.pet5PSId) {
        for (let i = 0; i < this.questions[0].Childrens[0].Childrens.length; i++) {
          if (this.questions[0].Childrens[0].Childrens[i].QuestionType === 59) {
            if (this.calculatePet5PS && this.calculatePet5PS !== this.questionForm[this.pet5PSId]) {
              this.questions[0].Childrens[0].Childrens[i].ShowQuestion = 0
              this.questions[0].Childrens[0].Childrens[i].IsRequired = 0
            } else {
              this.questions[0].Childrens[0].Childrens[i].ShowQuestion = 2
              this.questions[0].Childrens[0].Childrens[i].IsRequired = 3
              this.questionForm[this.pet5PSCommentsId] = ''
            }
            break
          }
        }
      }
    },
    setUptakeFormBaseline() {
      // 自动计算与基线相比摄取值变化
      if (!this.isBaseLineTask) {
        console.log('setUptakeFormBaseline: ', this.questionForm[this.pet5PSId], this.baseLinePET5PS)
        if (this.questionForm[this.pet5PSId] > 0) {
          // 当前访视的PET 5ps评分大于基线的PET 5ps评分   增大
          // 当前访视的PET 5ps评分小于基线的PET 5ps评分   减小
          if (this.questionForm[this.pet5PSId] > this.baseLinePET5PS) {
            this.questionForm[this.uptakeFromBaselineId] = '1'
          } else if (this.questionForm[this.pet5PSId] < this.baseLinePET5PS) {
            this.questionForm[this.uptakeFromBaselineId] = '2'
          }
        } else if (this.questionForm[this.pet5PSId] !== '-1' && this.questionForm[this.uptakeFromBaselineId] === '4') {
          this.questionForm[this.uptakeFromBaselineId] = ''
        } else if (this.questionForm[this.pet5PSId] === '' || this.questionForm[this.pet5PSId] === null) {
          this.questionForm[this.uptakeFromBaselineId] = ''
        }
      }
    },
    setfocalFDG() {
      console.log('setfocalFDG')
      if (this.questionForm[this.pet5PSId] !== '-1' && this.questionForm[this.focalFDGId] === '1') {
        this.questionForm[this.focalFDGId] = ''
      }
    },
    setpet5PS() {
      console.log('setpet5PS')
      // 无需标记，自主选择   1分
      // 无需标记，自主选择   x分
      const maxSUVmax = !isNaN(parseFloat(this.questionForm[this.suvmaxId])) ? parseFloat(this.questionForm[this.suvmaxId]) : null
      // 肝脏血池SUVmax
      const liverSUVmax = !isNaN(parseFloat(this.questionForm[this.liverSuvmaxId])) ? parseFloat(this.questionForm[this.liverSuvmaxId]) : null
      // 纵膈血池SUVmax
      const lungSUVmax = !isNaN(parseFloat(this.questionForm[this.lungSuvmaxId])) ? parseFloat(this.questionForm[this.lungSuvmaxId]) : null
      if (maxSUVmax !== null && liverSUVmax !== null && maxSUVmax > liverSUVmax * 2) {
        // 本访视病灶的 max SUVmax（所有病灶中最大的）>2*肝脏血池SUVmax   5分
        // this.questionForm[this.pet5PSId] = '5'
        return '5'
      } else if (maxSUVmax !== null && liverSUVmax !== null && maxSUVmax > liverSUVmax) {
        // 本访视病灶的SUVmax（所有病灶中最大的）>肝脏血池SUVmax          4分
        // this.questionForm[this.pet5PSId] = '4'
        return '4'
      } else if (maxSUVmax !== null && liverSUVmax !== null && lungSUVmax !== null && maxSUVmax > lungSUVmax && maxSUVmax <= liverSUVmax) {
        // 纵隔血池SUVmax<本访视点病灶的max SUVmax（所有病灶中最大的）≤1*肝脏血池SUVmax    3分
        // this.questionForm[this.pet5PSId] = '3'
        return '3'
      } else if (maxSUVmax !== null && lungSUVmax !== null && maxSUVmax <= lungSUVmax) {
        // 本访视点病灶的SUVmax（所有病灶中最大的）<=纵隔血池SUVmax     2分
        // this.questionForm[this.pet5PSId] = '2'
        return '2'
      } else {
        // this.questionForm[this.pet5PSId] = ''
        return ''
      }
    },
    async resetSuvQuestions(type = 0) {
      this.loading = true
      try {
        const params = {
          trialId: this.trialId,
          visitTaskId: this.visitTaskId,
          questionClassify: 0
        }
        const res = await getDicomReadingQuestionAnswer(params)
        if (res.IsSuccess) {
          const questions = res.Result
          questions.map((v) => {
            if (v.Type === 'group' && v.Childrens.length === 0) return
            if (v.Childrens.length > 0) {
              this.setSuvChild(v.Childrens, type)
            }
          })
          for (let i = 0; i < this.questions[0].Childrens[0].Childrens.length; i++) {
            if (this.questions[0].Childrens[0].Childrens[i].QuestionType === 59) {
              this.questions[0].Childrens[0].Childrens[i].ShowQuestion = 2
              this.questions[0].Childrens[0].Childrens[i].IsRequired = 3
              this.questionForm[this.pet5PSCommentsId] = ''
              break
            }
          }
          this.questionFormChangeState = true
        }
        this.loading = false
      } catch (e) {
        console.log(e)
        this.loading = false
      }
    },
    setSuvChild(obj, type) {
      obj.forEach(i => {
        if (i.QuestionType === 53 && !type) {
          // SUVmax;
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
        }
        if (i.QuestionType === 54 && !type) {
          // SUVmax所在病灶;
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
        }
        if (i.QuestionType === 55) {
          // PET 5PS评分;
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
          this.calculatePet5PS = i.Answer
        }
        if (i.QuestionType === 56) {
          // 与基线相比摄取值变化;
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
        }

        if (i.Childrens && i.Childrens.length > 0) {
          this.setSuvChild(i.Childrens, type)
        }
      })
    },
    async uploadScreenshots(fileName, file) {
      try {
        file = this.convertBase64ToBlob(file)
        var trialId = this.$route.query.trialId
        var subjectId = this.$route.query.trialId
        const result = await this.OSSclient.put(`/${trialId}/Read/${subjectId}/${this.visitTaskId}/${fileName}.png`, file)
        return { isSuccess: true, result: result }
      } catch (e) {
        console.log(e)
        return { isSuccess: false, result: e }
      }
    },
    convertBase64ToBlob(imageEditorBase64) {
      var base64Arr = imageEditorBase64.split(',')
      var imgtype = ''
      var base64String = ''
      if (base64Arr.length > 1) {
        // 如果是图片base64，去掉头信息
        base64String = base64Arr[1]
        imgtype = base64Arr[0].substring(
          base64Arr[0].indexOf(':') + 1,
          base64Arr[0].indexOf(';')
        )
      }
      // 将base64解码
      var bytes = atob(base64String)
      // var bytes = base64;
      var bytesCode = new ArrayBuffer(bytes.length)
      // 转换为类型化数组
      var byteArray = new Uint8Array(bytesCode)

      // 将base64转换为ascii码
      for (var i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i)
      }

      // 生成Blob对象（文件对象）
      return new Blob([bytesCode], { type: imgtype })
    }
  }
}
</script>
<style lang="scss" scoped>
.ecrf-wrapper {

  ::v-deep .el-form-item__label {
    color: #c3c3c3;
    text-align: left;
  }

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

  ::v-deep .el-textarea__inner {
    background-color: transparent;
    color: #ddd;
    border: 1px solid #5e5e5e;
  }

  ::v-deep .el-form-item {
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  ::v-deep .el-form-item__content {
    flex: 1;
  }

  ::v-deep .el-button--mini,
  .el-button--mini.is-round {
    padding: 7px 10px;
  }

  .el-form-item__content .el-select {
    width: 100%;
  }
}
</style>
