<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"
          @setFormItemData="setFormItemData"
          @resetFormItemData="resetFormItemData"
          @addAnnotation="addAnnotation"
          @removeAnnotation="removeAnnotation"
          @locateAnnotation="locateAnnotation"
        />
      </template>
      <el-form-item v-if="readingTaskState < 2">
        <div style="text-align:right">
          <el-button :disabled="!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 { saveImageQuality, getDicomReadingQuestionAnswer } from '@/api/trials'
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,
      isInsideVolume: true
    }
  },
  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.initList()
    FusionEvent.$on('refreshQuestions', () => {
      this.initList()
    })
    FusionEvent.$on('resetSuvQuestions', () => {
      console.log('resetSuvQuestions')
      this.resetSuvQuestions()
    })
  },
  beforeDestroy() {
    FusionEvent.$off('refreshQuestions')
    FusionEvent.$off('resetSuvQuestions')
  },
  methods: {
    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
      }
    },
    initList() {
      this.loading = true
      var params = {
        trialId: this.trialId,
        visitTaskId: this.visitTaskId,
        questionClassify: 0
      }
      getDicomReadingQuestionAnswer(params).then(res => {
        var 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)
          }
        })
        this.questions = questions
        this.calculatePet5PS = this.setpet5PS()
        this.setPet5PSCommentDisplay()
        this.measurements = []
        res.OtherInfo.QuestionMarkInfoList.forEach(i => {
          if (i.OtherMeasureData) {
            i.OtherMeasureData = JSON.parse(i.OtherMeasureData)
          }
          this.measurements.push(i)
        })
        this.loading = false
      }).catch(() => { 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
          }
          if (i.QuestionType === 52) {
            // 纵膈血池SUVmax(52);
            this.lungSuvmaxId = i.Id
          }
          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.Childrens && i.Childrens.length > 0) {
            this.setChild(i.Childrens)
          }
        }
      })
    },
    handleSave() {
      this.$refs['questions'].validate((valid) => {
        if (!valid) return
        if (!this.isInsideVolume) {
          this.$alert('当前标记在图像外，不允许保存！', '提示', {
            callback: action => {
              this.$message({
                type: 'info',
                message: `action: ${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.saveQuestionsForm()
          }).catch(() => {

          })
        } else {
          this.saveQuestionsForm()
        }
        // else if (pet5PS > 1 && (!liverSUVmax || !lungSUVmax)) {
        //   this.$alert('pet 5ps评分不为1，X或者NE，需要进行标记！', '提示', {
        //     // confirmButtonText: '确定',
        //     callback: action => {

        //     }
        //   })
        // }
      })
    },
    saveQuestionsForm() {
      this.loading = true
      var answers = []
      for (const k in this.questionForm) {
        answers.push({ id: k, answer: this.questionForm[k] })
      }
      var questionMarkInfoList = []
      this.measurements.forEach(item => {
        var i = Object.assign({}, item)
        if (i.OtherMeasureData) {
          for (const k in i.OtherMeasureData.data.cachedStats) {
            i.OtherMeasureData.data.cachedStats[k].pointsInShape = []
          }
          i.OtherMeasureData = JSON.stringify(i.OtherMeasureData)
        }

        questionMarkInfoList.push(i)
      })
      var params = {
        visitTaskId: this.visitTaskId,
        answers: answers,
        questionMarkInfoList
      }
      saveImageQuality(params).then(async res => {
        this.$message.success(this.$t('common:message:savedSuccessfully'))
        window.opener.postMessage({ type: 'petctLesionUpdate' }, window.location)
        this.loading = false
        this.questionFormChangeState = false
      }).catch(() => {
        this.loading = false
      })
    },
    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) {
      console.log('question_removeAnnotation')
      const { Id } = obj
      var idx = this.measurements.findIndex(i => i.QuestionId === Id)
      if (idx === -1) return
      this.$set(this.questionForm, Id, '')
      var pet5PS = this.setpet5PS()
      this.questionForm[this.pet5PSId] = pet5PS
      this.calculatePet5PS = pet5PS
      this.setPet5PSCommentDisplay()
      FusionEvent.$emit('removeAnnotation', { otherMeasureData: this.measurements[idx].OtherMeasureData, type: 'clear' })
      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 })
    },
    setMeasuredData(measurement) {
      this.isInsideVolume = true
      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' : ''
      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') {
        const suvMax = measurement.suvMax
        this.$set(this.questionForm, obj.QuestionId, suvMax || null)
        var pet5PS = this.setpet5PS()
        this.questionForm[this.pet5PSId] = pet5PS
        this.calculatePet5PS = pet5PS
        this.setPet5PSCommentDisplay()
      }
      FusionEvent.$emit('addOrUpdateAnnotations', { data })
      this.questionFormChangeState = true
    },
    setOutsideMeasuredData(measurement) {
      this.isInsideVolume = false
      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 obj = this.measurements[idx]
      var remark = obj.QuestionType === 51 ? 'Liver' : obj.QuestionType === 52 ? 'Mediastinum' : ''
      measurement.data.remark = remark
      this.measurements[idx].OtherMeasureData = measurement
      this.measurements[idx].OtherMarkTool = measurement.metadata.toolName

      //  添加标记
      var data = {
        OtherMeasureData: measurement,
        QuestionId: obj.QuestionId,
        VisitTaskId: this.visitTaskId,
        OrderMarkName: remark
      }
      if (measurement.metadata.toolName === 'CircleROI') {
        // const suvMax = measurement.suvMax
        this.$set(this.questionForm, obj.QuestionId, null)
        var pet5PS = this.setpet5PS()
        this.questionForm[this.pet5PSId] = pet5PS
        this.calculatePet5PS = pet5PS
        this.setPet5PSCommentDisplay()
      }
      FusionEvent.$emit('addOrUpdateAnnotations', { data })
      this.questionFormChangeState = true
    },
    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.measurements[idx].OtherMeasureData = ''
      this.currentQsId = this.measurements[idx].QuestionId
      // const { QuestionId, QuestionType } = this.measurements[idx]
      this.questionFormChangeState = true
    },
    resetFormItemData(v) {
      this.questionForm[v] = null
    },
    setFormItemData(obj) {
      this.questionForm[obj.key] = obj.val
      if (obj.key === this.pet5PSId) {
        this.setPet5PSCommentDisplay()
      }
    },
    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
          }
        }
      }
    },
    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 ''
      }
    },
    resetSuvQuestions() {
      this.loading = true
      var params = {
        trialId: this.trialId,
        visitTaskId: this.visitTaskId,
        questionClassify: 0
      }
      getDicomReadingQuestionAnswer(params).then(res => {
        var questions = res.Result
        questions.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.Childrens.length > 0) {
            this.setSuvChild(v.Childrens)
          }
          var pet5PS = this.setpet5PS()
          this.questionForm[this.pet5PSId] = pet5PS
          this.calculatePet5PS = pet5PS
          this.setPet5PSCommentDisplay()
          this.questionFormChangeState = true
        })

        this.loading = false
      }).catch(() => { this.loading = false })
    },
    setSuvChild(obj) {
      obj.forEach(i => {
        if (i.QuestionType === 53) {
          // SUVmax;
          this.$set(this.questionForm, i.Id, i.Answer ? i.Answer : null)
        }
        if (i.QuestionType === 54) {
          // 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)
        }

        if (i.Childrens && i.Childrens.length > 0) {
          this.setSuvChild(i.Childrens)
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .ecrf-wrapper{

    /deep/ .el-form-item__label{
      color: #c3c3c3;
      text-align: left;
    }
    /deep/ .el-input__inner{
      background-color: transparent;
      color: #ddd;
      border: 1px solid #5e5e5e;
    }
    /deep/ .el-textarea__inner{
      background-color: transparent;
      color: #ddd;
      border: 1px solid #5e5e5e;
    }
    /deep/ .el-form-item{
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      flex-wrap: wrap;
    }
    /deep/ .el-form-item__content{
      flex: 1;
    }
    /deep/ .el-button--mini, .el-button--mini.is-round {
    padding: 7px 10px;
  }
    .el-form-item__content
    .el-select{
      width: 100%;
    }
  }

  </style>

