<template>
  <div v-loading="loading" class="ecrf-wrapper">
    <el-form v-if="questions.length > 0" ref="questions" size="small" :model="questionForm">
      <QuestionItem v-for="question of questions" :key="question.Id" :question="question" :question-form="questionForm"
        :reading-task-state="readingTaskState" :is-first-change-task="isFirstChangeTask" :visit-task-id="visitTaskId"
        @setFormItemData="setFormItemData" @resetFormItemData="resetFormItemData"
        @handleReadingChart="handleReadingChart" />

      <el-form-item v-if="readingTaskState < 2 && !isFirstChangeTask">
        <div class="ecrf-footer">
          <i v-if="groupClassify === null || groupClassify === 1" class="el-icon-warning feedback-icon"
            @click="openFeedBackTable" :style="{ color: isExistUnprocessedFeedback ? '#ffeb3b' : '#fff' }" />
          <el-button size="mini" :loading="saveLoading"
            :disabled="saveLoading || !questionFormChangeState || (!formChanged && groupClassify > 0)"
            :type="questionFormChangeState || (!formChanged && groupClassify > 0) ? 'primary' : null"
            @click="handleSave">{{ $t('common:button:save') }}</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>

</template>

<script>
// import { uploadPrintscreen } from '@/api/reading'
import { saveTaskQuestion, getSplenicState, getSplenicStateNoPet, getSplenicVerify, getSplenicVerifyNoPet, getCanChooseNotMerge, getCanChooseNotMergeNoPet, getDicomReadingQuestionAnswer } from '@/api/trials'
import { setSkipReadingCache } from '@/api/reading'
import QuestionItem from './QuestionItem'
import DicomEvent from './DicomEvent'
import { mapGetters } from 'vuex'
import store from '@/store'
export default {
  name: 'ECRF',
  components: {
    QuestionItem
  },
  props: {
    questionFormChangeState: {
      type: Boolean,
      default: false
    },
    questionFormChangeNum: {
      type: Number,
      default: 0
    },
    isFirstChangeTask: {
      type: Boolean,
      default: false
    },
    groupClassify: {
      type: Number,
      default: null
    },
    isQulityIssues: {
      type: Boolean,
      default: true
    },
    questionType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      loading: false,
      questions: [],
      questionForm: {},
      readingTaskState: 2,
      visitTaskId: '',
      imageQualityId: '',
      imageQualityIssuesId: '',
      measurements: [],
      spleenStatusId: '',
      spleenLengthId: '',
      spleenCommentsId: '',
      spleenTopId: '',
      spleenBottomId: '',
      isBaseLineTask: false,
      criterionType: null,
      spleenInfo: null,
      calculateSpleenStatus: '',
      formChanged: false,
      digitPlaces: 2,
      isExistUnprocessedFeedback: false,
      saveLoading: false
    }
  },
  computed: {
    ...mapGetters(['visitTaskList', 'currentReadingTaskState'])
  },
  watch: {
    questionForm: {
      deep: true,
      immediate: false,
      handler(v) {
        if (this.isQulityIssues) {
          DicomEvent.$emit('questionFormChange', true)
        }
      }
    },
    currentReadingTaskState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.readingTaskState = val
        }
      }
    }
  },
  mounted() {
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.criterionType = parseInt(localStorage.getItem('CriterionType'))
    this.isExistUnprocessedFeedback = localStorage.getItem('IsExistUnprocessedFeedback') !== 'false'
    DicomEvent.$on('setReadingState', readingTaskState => {
      this.readingTaskState = readingTaskState
    })
    if (this.groupClassify === 3) {
      DicomEvent.$on('addAnnotation', obj => {
        // this.$set(obj, 'SaveEnum', 1)
        this.addAnnotation(obj)
      })
      DicomEvent.$on('removeAnnotation', obj => {
        this.$set(obj, 'SaveEnum', 0)
        this.removeAnnotation(obj)
      })
      DicomEvent.$on('saveAnnotation', obj => {
        this.saveAnnotation(obj)
      })

      DicomEvent.$on('locateAnnotation', obj => {
        this.locateAnnotation(obj)
      })
    }
  },
  beforeDestroy() {
    DicomEvent.$off('setReadingState')
    if (this.groupClassify === 3) {
      DicomEvent.$off('addAnnotation')
      DicomEvent.$off('removeAnnotation')
      DicomEvent.$off('saveAnnotation')
      DicomEvent.$off('locateAnnotation')
    }
  },
  methods: {
    handleReadingChart(e) {
      this.$emit('handleReadingChart', e)
    },
    async getQuestions(visitTaskId, isRefresh = false) {
      var isChangeVisitTask = this.visitTaskId !== visitTaskId
      this.visitTaskId = visitTaskId
      // const loading = this.$loading({ fullscreen: true })
      var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === visitTaskId)
      var qs = []
      if (idx > -1) {
        this.isBaseLineTask = this.visitTaskList[idx].IsBaseLineTask
        this.readingTaskState = this.visitTaskList[idx].ReadingTaskState
        var questions = this.visitTaskList[idx].Questions
        if (this.groupClassify === 3) {
          this.measurements = []
          this.visitTaskList[idx].QuestionMarkInfoList.forEach(i => {
            if (this.isJSONString(i.MeasureData)) {
              i.MeasureData = JSON.parse(i.MeasureData)
            }
            this.measurements.push(i)
          })
          if (isChangeVisitTask || isRefresh) {
            if (this.criterionType === 18) {
              const { Result } = await getSplenicVerifyNoPet(visitTaskId)
              this.spleenInfo = Result
            } else {
              const { Result } = await getSplenicVerify(visitTaskId)
              this.spleenInfo = Result
            }

          }
        }

        for (var i = 0; i < questions.length; i++) {
          var v = questions[i]
          v.IsBaseLineTask = this.isBaseLineTask
          if (v.Type === 'group' && v.GroupClassify !== this.groupClassify) continue
          if (!v.IsPage && v.Type !== 'group' && v.Type !== 'summary' && i.Id) {
            const answer = v.Type === 'select' && v.OptionTypeEnum === 1 && v.Answer ? JSON.parse(v.Answer) : v.Answer
          this.$set(this.questionForm, v.Id, answer ? answer : null)
            // this.$set(this.questionForm, v.Id, v.Answer ? v.Answer : null)
            if (v.QuestionType === 44) {
              // 影像质量评估
              this.imageQualityId = v.Id
              // store.dispatch('reading/setImageQuality', v.Answer ? v.Answer : null)
            }
            if (v.QuestionType === 67) {
              // 影像质量问题
              this.imageQualityIssuesId = v.Id
            }

            if (v.QuestionType === 49) {
              // 脾脏状态
              this.spleenStatusId = v.Id
            }
            if (v.QuestionType === 48) {
              // 脾脏垂直径
              this.spleenLengthId = v.Id
            }
            if (v.QuestionType === 58) {
              // 修改脾脏状态备注
              this.spleenCommentsId = v.Id
            }
            if (v.QuestionType === 60) {
              // 脾尖位置
              this.spleenTopId = v.Id
            }
            if (v.QuestionType === 61) {
              // 脾底位置
              this.spleenBottomId = v.Id
            }
            
          }
          if (v.Childrens.length > 0) {
            this.setChild(v.Childrens)
          }
          qs.push(v)
        }
        this.questions = Object.assign([], qs)
      }
      if (this.imageQualityIssuesId) {
        store.dispatch('reading/setImageQualityIssues', this.questionForm[this.imageQualityIssuesId])
      }
      if (this.spleenLengthId && this.spleenInfo && this.readingTaskState < 2) {
        this.calculateSpleenStatus = this.spleenInfo.SplenicStatus
        this.setSpleenCommentDisplay()
      }
      // loading.close()
    },
    setChild(obj) {
      obj.forEach(i => {
        i.IsBaseLineTask = this.isBaseLineTask
        if (i.Type !== 'group' && i.Type !== 'summary' && i.Id) {
          let answer = i.Type === 'select' && i.OptionTypeEnum === 1 && i.Answer ? JSON.parse(i.Answer) : i.Answer
          if (i.DictionaryCode && i.Type === 'calculation') {
            answer = this.$fd(i.DictionaryCode, parseInt(i.Answer))
          }
          this.$set(this.questionForm, i.Id, answer ? answer : null)
          if (i.QuestionType === 44) {
            // 影响质量评估
            this.imageQualityId = i.Id
            // store.dispatch('reading/setImageQuality', i.Answer ? i.Answer : null)
          }
          if (i.QuestionType === 67) {
            // 影像质量问题
            this.imageQualityIssuesId = i.Id
          }
          if (i.QuestionType === 49) {
            // 脾脏状态
            this.spleenStatusId = i.Id
          }
          if (i.QuestionType === 48) {
            // 脾脏长度
            this.spleenLengthId = i.Id
          }
          if (i.QuestionType === 58) {
            // 修改脾脏状态备注
            this.spleenCommentsId = i.Id
          }
          if (i.QuestionType === 60) {
            // 脾尖位置
            this.spleenTopId = i.Id
            this.$set(i, 'SaveEnum', 0)
          }
          if (i.QuestionType === 61) {
            // 脾底位置
            this.spleenBottomId = i.Id
            this.$set(i, 'SaveEnum', 0)
          }
        }
        if (i.Childrens && i.Childrens.length > 0) {
          this.setChild(i.Childrens)
        }
      })
    },

    async handleSave(options = {}) {
      if (this.saveLoading) return false
      this.saveLoading = true
      const valid = await new Promise(resolve => {
        this.$refs['questions'].validate(v => resolve(v))
      })
      if (!valid) {
        this.saveLoading = false
        return false
      }
      // lugano标准校验脾脏状态是否符合要求
      if ((this.criterionType === 2 || this.criterionType === 18) && this.groupClassify === 3) {
        // 是否有标记未保存
        var existUnSave = this.checkAnnotationStatus(this.questions)
        if (existUnSave) {
          await this.$alert(this.$t('trials:lugano:message:saveWarning'), this.$t('trials:lugano:fusionDialog:warning'))
          this.saveLoading = false
          return false
        }

        var currentSpleenStatus = this.questionForm[this.spleenStatusId]
        var currentSpleenLength = this.questionForm[this.spleenLengthId]
        currentSpleenStatus = isNaN(parseInt(currentSpleenStatus)) ? null : parseInt(currentSpleenStatus)
        var stIdx = this.measurements.findIndex(i => i.QuestionType === 60)
        var slIdx = this.measurements.findIndex(i => i.QuestionType === 61)

        if (currentSpleenLength && currentSpleenStatus === 5) {
          // '脾脏状态为不可评估，不需要添加标记!'
          await this.$alert(this.$t('trials:lugano:message:validSpleen1'), this.$t('trials:lugano:fusionDialog:warning'), {
            callback: _ => { }
          })
          this.saveLoading = false
          return false
        } else if (currentSpleenStatus === 5 && ((stIdx > -1 && this.measurements[stIdx].MeasureData) || (slIdx > -1 && this.measurements[slIdx].MeasureData))) {
          // 若有标记，状态不可为“无法评估”
          await this.$alert(this.$t('trials:lugano:message:validSpleen1'), this.$t('trials:lugano:fusionDialog:warning'), {
            callback: _ => { }
          })
          this.saveLoading = false
          return false
        } else if (((stIdx > -1 && this.measurements[stIdx].MeasureData) || (slIdx > -1 && this.measurements[slIdx].MeasureData)) && !currentSpleenLength) {
          await this.$alert(this.$t('trials:lugano:message:validSpleen2'), this.$t('trials:lugano:fusionDialog:warning'), {
            callback: _ => { }
          })
          this.saveLoading = false
          return false
        }
        return await this.saveQuestionsList(options)
      } else if ((this.criterionType === 2 || this.criterionType === 18) && this.groupClassify === 1 && this.questionForm[this.imageQualityIssuesId] && parseInt(this.questionForm[this.imageQualityIssuesId]) === 6) {
        // 保存影响质量问题分组，如果质量问题为PET-CT影像无法融合则验证是否可以保存
        let res = null
        if (this.criterionType === 18) {
          res = await getCanChooseNotMergeNoPet({ visitTaskId: this.visitTaskId })
        } else {
          res = await getCanChooseNotMerge({ visitTaskId: this.visitTaskId })
        }

        if (res.IsSuccess && !res.Result.IsCanChooseNotMerge) {
          await this.$alert(this.$t('trials:lugano:saveQuestions:warning1'), this.$t('trials:lugano:fusionDialog:warning'), {
            showCancelButton: false,
            callback: action => { }
          })
          this.saveLoading = false
          return false
        }
        // 如果设置为PET-CT影像无法融合，则FDG-PET评估会被设置为NE。
        const confirm = await this.$confirm(this.$t('trials:lugano:saveQuestions:warning2'), {
          type: 'warning',
          distinguishCancelAndClose: true
        }).then(() => true).catch(() => false)
        if (!confirm) {
          this.saveLoading = false
          return false
        }
        return await this.saveQuestionsList(options)
      } else {
        return await this.saveQuestionsList(options)
      }
    },
    async saveQuestionsList(options = {}) {
      this.loading = true
      var answers = []
      var imageQuality = null
      for (const k in this.questionForm) {
        answers.push({ id: k, answer: Array.isArray(this.questionForm[k]) ? JSON.stringify(this.questionForm[k]) : this.questionForm[k] })
        if (k === this.imageQualityId) {
          imageQuality = this.questionForm[k]
        }
      }
      var params = {
        visitTaskId: this.visitTaskId,
        answers: answers

      }
      // if (this.groupClassify === 3) {
      //   var questionMarkInfoList = []
      //   this.measurements.forEach(item => {
      //     var i = Object.assign({}, item)
      //     if (i.MeasureData) {
      //       i.MeasureData = JSON.stringify(i.MeasureData)
      //     }
      //     questionMarkInfoList.push(i)
      //   })
      //   params.questionMarkInfoList = questionMarkInfoList
      // }
      try {
        const res = await saveTaskQuestion(this.questionType, params)
        if (this.imageQualityIssuesId) {
          store.dispatch('reading/setImageQualityIssues', this.questionForm[this.imageQualityIssuesId])
          if (this.questionForm[this.imageQualityIssuesId] && parseInt(this.questionForm[this.imageQualityIssuesId]) === 6) {
            DicomEvent.$emit('closePetct')
          }
        }
        if (!options.silentSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        }
        if (!options.skipRefresh) {
          var trialId = this.$route.query.trialId
          await store.dispatch('reading/refreshDicomReadingQuestionAnswer', { trialId: trialId, visitTaskId: this.visitTaskId })
          this.getQuestions(this.visitTaskId, true)
        }
        this.loading = false
        if (this.isQulityIssues) {
          DicomEvent.$emit('questionFormChange', false)
        }
        DicomEvent.$emit('getReportInfo', true)
        // DicomEvent.$emit('readingPageUpdate', {})
        var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
        const criterionType = parseInt(localStorage.getItem('CriterionType'))
        if (idx > -1 && !this.visitTaskList[idx].IsBaseLineTask && (criterionType === 1 || criterionType === 2 || criterionType === 18 || criterionType === 3 || criterionType === 17)) {
          if (parseInt(imageQuality) === 2) {
            this.$confirm(this.$t('trials:reading:warnning:unableEvaluate'), '', {
              type: 'warning'
            }).then(() => {
              store.dispatch('reading/setImageQuality', imageQuality)
              DicomEvent.$emit('handleImageQualityAbnormal')
              DicomEvent.$emit('readingPageUpdate', {})
            }).catch(() => {

            })
          }
        }
        this.formChanged = false
        this.saveLoading = false
        return res
      } catch (e) {
        this.loading = false
        this.saveLoading = false
        throw e
      }
    },
    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
          }
        }
      }
    },
    checkAnnotationValid(stIdx, slIdx) {
      var isValid = true
      if (stIdx > -1 && slIdx > -1 && this.measurements[stIdx].MeasureData && this.measurements[slIdx].MeasureData) {
        var stSeriesId = this.measurements[stIdx].SeriesId
        var stInstanceId = this.measurements[stIdx].InstanceId
        var slSeriesId = this.measurements[slIdx].SeriesId
        var slInstanceId = this.measurements[slIdx].InstanceId
        if (!(stSeriesId && stInstanceId && slSeriesId && slInstanceId && stSeriesId === slSeriesId && stInstanceId !== slInstanceId)) {
          isValid = false
        }
      }
      return isValid
    },
    setSpleenCommentDisplay() {
      if (this.spleenCommentsId && this.spleenStatusId) {
        for (let i = 0; i < this.questions[0].Childrens.length; i++) {
          if (this.questions[0].Childrens[i].QuestionType === 58) {
            if (this.calculateSpleenStatus && this.calculateSpleenStatus !== this.questionForm[this.spleenStatusId]) {
              this.questions[0].Childrens[i].ShowQuestion = 0
              this.questions[0].Childrens[i].IsRequired = 0
            } else {
              this.questions[0].Childrens[i].ShowQuestion = 2
              this.questions[0].Childrens[i].IsRequired = 3
              this.questionForm[this.spleenCommentsId] = ''
            }
            break
          }
        }
      }
    },
    async getSplenicState() {
      try {
        var spleenLength = this.questionForm[this.spleenLengthId]
        spleenLength = isNaN(parseFloat(spleenLength)) ? -1 : parseFloat(spleenLength)
        let result = null
        if (this.criterionType === 18) {
          result = await getSplenicStateNoPet(this.visitTaskId, spleenLength)
        } else {
          result = await getSplenicState(this.visitTaskId, spleenLength)
        }
        return { isSuccess: true, result: result.Result }
      } catch (e) {
        return { isSuccess: false, result: e }
      }
    },
    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 })
    },
    addAnnotation(obj) {
      const { Id, QuestionType } = obj
      this.currentQsId = Id
      var idx = this.measurements.findIndex(i => i.QuestionId === Id)
      var orderMarkName = QuestionType === 60 ? 'Spleen Top' : QuestionType === 61 ? 'Spleen Bottom' : ''
      if (idx === -1) {
        this.measurements.push({ QuestionId: Id, QuestionType: QuestionType, StudyId: '', SeriesId: '', InstanceId: '', MarkTool: '', PicturePath: '', NumberOfFrames: '', MeasureData: '', OrderMarkName: orderMarkName })
      }

      // 脾脏长度  直径测量
      this.$emit('setNonTargetMeasurementStatus', { status: true })
      DicomEvent.$emit('imageLocation', { questionId: Id, visitTaskId: this.visitTaskId, lesionName: orderMarkName, markTool: 'ArrowAnnotate', readingTaskState: this.readingTaskState, isMarked: false })
    },
    async 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.spleenTopId] && !this.questionForm[this.spleenBottomId]) {
        this.clearSpleenStatus()
      }
      // if (obj.QuestionType === 60 || obj.QuestionType === 61) {
      //   this.$set(this.questionForm, this.spleenStatusId, '')
      //   this.$set(this.questionForm, this.spleenLengthId, '')
      // }
      await store.dispatch('reading/removeNonTargetMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.measurements[idx].MeasureData, questionId: Id })
      this.setQuestionStatus(this.questions, this.measurements[idx].QuestionType)
      this.measurements.splice(idx, 1)
      DicomEvent.$emit('getMeasureData')
      // this.calculateSpleenStatus = ''
      // this.setSpleenCommentDisplay()
      this.formChanged = true
    },
    clearSpleenStatus() {
      this.$set(this.questionForm, this.spleenStatusId, '')
      this.$set(this.questionForm, this.spleenLengthId, '')
      for (let i = 0; i < this.questions[0].Childrens.length; i++) {
        if (this.questions[0].Childrens[i].QuestionType === 58) {
          this.questions[0].Childrens[i].ShowQuestion = 2
          this.questions[0].Childrens[i].IsRequired = 3
          this.questionForm[this.spleenCommentsId] = ''
          break
        }
      }
    },
    saveAnnotation(question) {
      var stIdx = this.measurements.findIndex(i => i.QuestionType === 60)
      var slIdx = this.measurements.findIndex(i => i.QuestionType === 61)
      var chenckVaild = this.checkAnnotationValid(stIdx, slIdx)
      if (!chenckVaild) {
        // 校验标记是否在同一序列的不同图像上
        this.$alert(this.$t('trials:lugano:message:validSpleen3'), this.$t('trials:lugano:fusionDialog:warning'), {
          callback: _ => { }
        })
        return
      }
      this.loading = true
      // 获取截图
      var annotationObj = this.measurements.find(i => i.QuestionType === question.QuestionType)
      if (!annotationObj) {
        this.saveQuestions(question)
      } else {
        var obj = Object.assign({}, annotationObj)
        DicomEvent.$emit('getScreenshots', { questionId: obj.Id, visitTaskId: this.visitTaskId, lesionName: obj.OrderMarkName, markTool: obj.MarkTool, readingTaskState: this.readingTaskState, isMarked: !!obj.MeasureData }, async val => {
          try {
            var pictureObj = await this.uploadScreenshots(`${new Date().getTime()}`, val)
            var picturePath = pictureObj.isSuccess ? this.$getObjectName(pictureObj.result.url) : ''
            this.saveQuestions(question, obj, picturePath)
          } catch (e) {
            console.log(e)
            this.loading = false
          }
        })
      }
    },
    async saveQuestions(question, obj, picturePath) {
      try {
        this.loading = true
        var answers = []
        var questionMarkInfoList = []
        if (obj && obj.MeasureData) {
          var annotation = Object.assign({}, obj.MeasureData)
          obj.MeasureData = JSON.stringify(annotation)
          obj.PicturePath = picturePath
          questionMarkInfoList.push(obj)
        }
        for (const k in this.questionForm) {
          if (k === question.Id) {
            answers.push({ id: k, answer: this.questionForm[k] })
            break
          }
        }
        var params = {
          visitTaskId: this.visitTaskId,
          answers,
          questionMarkInfoList
        }
        const qsType = question.QuestionType === 60 ? 4 : question.QuestionType === 61 ? 5 : null
        await saveTaskQuestion(qsType, params)
        this.$message.success(this.$t('common:message:savedSuccessfully'))
        await this.setQuestions()
        for (let i = 0; i < this.questions[0].Childrens.length; i++) {
          if (this.questions[0].Childrens[i].QuestionType === 58) {
            this.questions[0].Childrens[i].ShowQuestion = 2
            this.questions[0].Childrens[i].IsRequired = 3
            this.questionForm[this.spleenCommentsId] = ''
            break
          }
        }
        this.loading = false
        this.$set(question, 'SaveEnum', 0)
        DicomEvent.$emit('getReportInfo', true)
      } catch (e) {
        console.log(e)
        this.loading = false
      }
    },
    locateAnnotation(obj) {
      const { Id } = obj
      var idx = this.measurements.findIndex(i => i.QuestionId === Id)
      if (idx === -1) return
      const measureObj = this.measurements[idx]
      DicomEvent.$emit('imageLocation', { questionId: Id, visitTaskId: this.visitTaskId, lesionName: measureObj.OrderMarkName, markTool: measureObj.MarkTool, readingTaskState: this.readingTaskState, isMarked: !!measureObj.MeasureData })
    },
    setMeasuredData(measurement) {
      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.remark)
      }
      if (idx === -1) return
      var remark = this.measurements[idx].QuestionType === 60 ? 'Spleen Top' : this.measurements[idx].QuestionType === 61 ? 'Spleen Bottom' : ''
      measurement.data.remark = remark
      this.measurements[idx].StudyId = measurement.studyId
      this.measurements[idx].SeriesId = measurement.seriesId
      this.measurements[idx].InstanceId = measurement.instanceId
      this.measurements[idx].MarkTool = measurement.type
      this.measurements[idx].NumberOfFrames = isNaN(parseInt(measurement.frame)) ? 0 : measurement.frame
      this.measurements[idx].MeasureData = measurement
      this.measurements[idx].pictureBaseStr = measurement.pictureBaseStr
      measurement.pictureBaseStr = ''
      // 添加标记
      var data = {
        Id: '',
        IsDicomReading: true,
        StudyId: measurement.studyId,
        InstanceId: measurement.instanceId,
        SeriesId: measurement.seriesId,
        MeasureData: measurement,
        QuestionId: this.measurements[idx].QuestionId,
        RowIndex: null,
        RowId: null,
        VisitTaskId: this.visitTaskId,
        OrderMarkName: measurement.data.remark,
        frame: isNaN(parseInt(measurement.frame)) ? 0 : measurement.frame
      }
      if (measurement.type === 'ArrowAnnotate') {
        const location = measurement.location ? Number(measurement.location).toFixed(this.digitPlaces) : null
        this.$set(this.questionForm, this.measurements[idx].QuestionId, location || null)
        // if (this.measurements[idx].QuestionType === 60 || this.measurements[idx].QuestionType === 61) {
        //   var length = this.getSpleenL()
        //   this.$set(this.questionForm, this.spleenLengthId, length)
        //   var status = this.setSpleenStatus(length)
        //   this.$set(this.questionForm, this.spleenStatusId, status)
        //   this.calculateSpleenStatus = status
        // }

        // if (this.measurements[idx].QuestionType === 48 && length <= 130 && this.isBaseLineTask) {
        //   // 脾脏状态设置默认值为正常
        //   this.$set(this.questionForm, this.spleenStatusId, '1')
        // }
        // if (this.measurements[idx].QuestionType === 48 && length > 130 && this.isBaseLineTask) {
        //   // 脾脏状态设置默认值为肿大
        //   this.$set(this.questionForm, this.spleenStatusId, '6')
        // }
      }
      store.dispatch('reading/addOrUpdateNonTargetMeasuredData', { visitTaskId: this.visitTaskId, data: data })
      if (this.isQulityIssues) {
        DicomEvent.$emit('questionFormChange', true)
      }
      this.formChanged = true
      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
          }
        }
      }
    },
    getSpleenL() {
      var length = null
      // 脾尖位置
      var st = this.questionForm[this.spleenTopId]
      st = isNaN(parseFloat(st)) ? null : parseFloat(st)
      // 脾底位置
      var sb = this.questionForm[this.spleenBottomId]
      sb = isNaN(parseFloat(sb)) ? null : parseFloat(sb)
      if (st && sb) {
        length = Math.abs(st - sb).toFixed(this.digitPlaces)
      }
      return length
    },
    setSpleenStatus(length) {
      console.log('setSpleenStatus')
      var status = ''
      if (length) {
        if (this.isBaseLineTask) {
          // 直径≤130mm时，系统默认脾脏状态为“正常”
          if (length <= 130) {
            status = '1'
          }
          // 直径>130mm时，系统默认脾脏状态为“肿大”
          if (length > 130) {
            status = '6'
          }
        } else {
          // 与基线相比脾垂直径变化值
          var diffFromBaseline = length - this.spleenInfo.BaseLineSpleenLength
          var percentFormBaseline = 0
          if (this.spleenInfo.BaseLineSpleenLength) {
            percentFormBaseline = diffFromBaseline * 100 / (this.spleenInfo.BaseLineSpleenLength - 130)
          }
          if (length <= 130) {
            // 当前访视的垂直径≤130mm
            // 系统默认脾脏状态为“正常”
            status = '1'
          } else if (this.spleenInfo.BaseLineSpleenLength > 130 && diffFromBaseline >= 10 && percentFormBaseline > 50 && length > 130) {
            // 1、基线 垂直径>130 mm
            // 2、与基线相比脾垂直径变化值≥10 mm
            // 3、与基线相比脾肿大增加的百分比>50％
            // 4、当前垂直径>130 mm
            // 系统默认脾脏状态为“显著增大”
            status = '4'
          } else if (this.spleenInfo.BaseLineSpleenLength <= 130 && diffFromBaseline >= 20 && length > 130) {
            // 1、基线垂直径≤130mm
            // 2、与基线相比脾垂直径变化值≥20 mm
            // 3、当前垂直径>130 mm
            // 系统默认脾脏状态为“显著增大”
            status = '4'
          } else if (this.spleenInfo.BaseLineSpleenLength > 130 && this.spleenInfo.LowSpleenLength <= 130 && length - this.spleenInfo.LowSpleenLength >= 20 && length > 130) {
            // 1、基线 垂直径>130 mm
            // 2、当前访视的前面访视中 存在垂直径≤130mm
            // 3、与最低点相比脾脏垂直径的增加值≥20 mm
            // 4、当前垂直径>130 mm
            // 系统默认脾脏状态为“显著增大”
            status = '4'
          } else if (this.spleenInfo.BaseLineState === '6' && percentFormBaseline < -50 && length > 130) {
            // 1、基线期 状态为“肿大”
            // 2、与基线相比脾肿大增加的百分比小于-50％
            // 3、当前垂直径>130 mm
            // 系统默认脾脏状态为“部分缓解”
            status = '2'
          } else {
            // 系统默认脾脏状态为“稳定”
            status = '3'
          }
        }
      }
      return status
    },
    resetFormItemData(v) {
      this.questionForm[v] = null
      // if (v === this.spleenLengthId) {
      //   var spleenStatus = this.questionForm[this.spleenStatusId]
      //   spleenStatus = isNaN(parseInt(spleenStatus)) ? null : parseInt(spleenStatus)
      //   if (spleenStatus === 5) {
      //     this.removeAnnotation({ Id: this.spleenLengthId })
      //   }
      // }
      this.formChanged = true
    },
    setFormItemData(obj) {
      this.questionForm[obj.key] = obj.val
      if (obj.key === this.spleenStatusId) {
        this.setSpleenCommentDisplay()
      }
      
      this.formChanged = true
    },
    setQuestions() {
      return new Promise(resolve => {
        var params = {
          trialId: this.$route.query.trialId,
          visitTaskId: this.visitTaskId
        }
        getDicomReadingQuestionAnswer(params).then(res => {
          var questions = []
          for (var i = 0; i < res.Result.length; i++) {
            var v = res.Result[i]
            if (v.Type === 'group' && v.GroupClassify !== this.groupClassify) continue
            questions.push(v)
          }
          questions.map((v) => {
            if (v.Type === 'group' && v.Childrens.length === 0) return
            if (v.Childrens.length > 0) {
              this.setQSChild(v.Childrens)
            }
          })
          resolve()
        })
      })
    },
    setQSChild(obj) {
      obj.forEach(i => {
        if (i.QuestionType === 49) {
          // 脾脏状态;
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
          this.calculateSpleenStatus = i.Answer
        }
        if (i.QuestionType === 48) {
          // 脾脏长度;
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
        }
        if (i.Childrens && i.Childrens.length > 0) {
          this.setQSChild(i.Childrens)
        }
      })
    },
    openFeedBackTable() {
      this.$FB({
        type: 'imgfail',
        trialId: this.$route.query.trialId,
        visitTaskId: this.visitTaskId,
        callBack: async () => {
          console.log('callBack')
          const confirm = await this.$confirm(
            this.$t('trials:reading:confirm:feedbackmsg'),
            {
              type: 'warning',
              distinguishCancelAndClose: true
            }
          )
          if (confirm !== 'confirm') return
          this.loading = true
          try {
            const res = await setSkipReadingCache({ visitTaskId: this.visitTaskId })
            this.loading = false
            if (res.IsSuccess) {
              window.location.reload()
            }
          } catch (e) {
            this.loading = false
            console.log(e)
          }
        }
      })
    },
    isJSONString(str) {
      try {
        JSON.stringify(JSON.parse(str))
        return true
      } catch (e) {
        return false
      }
    }
  }
}
</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;
  }

  ::v-deep .el-form-item__content .el-select {
    width: 100%;
  }

  .ecrf-footer {
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    align-items: center;

    .feedback-icon {
      padding: 0 10px;
      color: #fff;
      font-weight: 400;
      font-size: 22px;
      cursor: pointer;

      &:hover {
        color: #68a2d5;
      }
    }
  }
}
</style>
