<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 size="mini" type="primary" @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,
      visitTaskId: '',
      measurements: [],
      currentQsId: ''
    }
  },
  computed: {
    ...mapGetters(['currentReadingTaskState'])
  },
  watch: {
    questionForm: {
      deep: true,
      immediate: false,
      handler(v) {
      }
    },
    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.initList()
    FusionEvent.$on('refreshQuestions', () => {
      this.initList()
    })
  },
  beforeDestroy() {
    FusionEvent.$off('refreshQuestions')
  },
  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) => {
          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.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 => {
        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.Childrens && i.Childrens.length > 0) {
            this.setChild(i.Childrens)
          }
        }
      })
    },
    handleSave() {
      this.$refs['questions'].validate((valid) => {
        if (!valid) return
        this.loading = true
        var answers = []
        for (const k in this.questionForm) {
          answers.push({ id: k, answer: this.questionForm[k] })
        }
        var questionMarkInfoList = []
        this.measurements.forEach(i => {
          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
        }).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 ? 'Lung' : ''
      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, '')
      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) {
      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 ? 'Lung' : ''
      measurement.data.data.remark = remark
      this.measurements[idx].OtherMeasureData = measurement.data
      this.measurements[idx].OtherMarkTool = measurement.data.metadata.toolName
      // this.measurements[idx].pictureBaseStr = measurement.pictureBaseStr
      // measurement.pictureBaseStr = ''
      // // 添加标记
      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)
      }
      FusionEvent.$emit('addOrUpdateAnnotations', { data })
    },
    resetFormItemData(v) {
      this.questionForm[v] = null
    },
    setFormItemData(obj) {
      this.questionForm[obj.key] = obj.val
    }
  }
}
</script>
<style lang="scss" scoped>
  .ecrf-wrapper{

    /deep/ .el-form-item__label{
      color: #c3c3c3;
    }
    /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>

