<template>
  <div class="measurement-wrapper">

    <div class="container">
      <!-- 测量问题 -->
      <template v-for="(qs,index) in questions">
        <div v-if="qs.QuestionClassify === 0" :key="index" v-loading="loading" class="lesions lesions_wrapper">
          <h4 v-if="qs.Type === 'group'" style="color: #ddd;padding: 5px 0px;margin: 0;">
            {{ language==='en'?qs.GroupEnName:qs.GroupName }}
          </h4>
          <div class="lesion_list">
            <template v-for="item in qs.Childrens">
              <div v-if="item.QuestionClassify === 0 && !(isBaseLineTask && item.LesionType === 2)" :key="item.Id">
                <div v-if="item.Type === 'table'" class="flex-row" style="margin:3px 0;">
                  <div class="title">{{ item.QuestionName }}</div>
                  <div v-if="readingTaskState<2 && (isBaseLineTask || item.LesionType === 2)" class="add-icon" @click.prevent="handleAdd(item)">
                    <i class="el-icon-plus" />
                  </div>
                </div>
                <!-- @change="handleCollapseChange(qs.Childrens,item)" -->
                <el-collapse
                  v-if="item.Type === 'table' && item.TableQuestions"
                  v-model="activeName"
                  accordion
                  @change="handleCollapseChange"
                >
                  <el-collapse-item
                    v-for="(q,i) in item.TableQuestions.Answers"
                    :key="`${item.Id}_${q.RowIndex}`"
                    :name="`${item.Id}_${q.RowIndex}`"
                    @contextmenu.prevent.native="collapseRightClick($event,q,item.Id,q.RowIndex)"
                  >
                    <template slot="title">
                      <div style="width:300px;position: relative;" :style="{color:(activeName===item.Id+q.RowIndex?'#ffeb3b':'#fff')}">

                        {{ getLesionName(item.OrderMark,q.RowIndex) }}
                        <!-- 未保存 -->
                        <el-tooltip v-if="readingTaskState<2 && parseInt(item.TableQuestions.Answers[i].saveTypeEnum) === 0" class="item" effect="dark" :content="$t('trials:reading:button:unsaved')" placement="bottom">
                          <i class="el-icon-warning" style="color:red" />
                        </el-tooltip>
                        <!-- 信息不完整 -->
                        <el-tooltip v-if="readingTaskState<2 && parseInt(item.TableQuestions.Answers[i].saveTypeEnum) ===1" class="item" effect="dark" :content="$t('trials:reading:button:incompleteInfor')" placement="bottom">
                          <i class="el-icon-warning" style="color:#ff9800" />
                        </el-tooltip>
                        <div style="position: absolute;left: 50px;top: 2px;">
                          <!-- white-space: nowrap;overflow: hidden;text-overflow: ellipsis; -->
                          <div style="font-size: 11px;width:220px;height: 30px;">
                            <div
                              v-if="item.TableQuestions.Answers[i].lesionPart"
                              style="margin-left:10px;display: inline-block; white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width:90px"
                            >
                              <el-tooltip v-if="!!item.TableQuestions.Answers[i].lesionPart" class="item" effect="dark" :content="item.TableQuestions.Answers[i].lesionPart" placement="bottom">
                                <span>{{ item.TableQuestions.Answers[i].lesionPart }}</span>
                              </el-tooltip>
                            </div>
                            <div style="display: inline-block;margin-left:5px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width:50px">
                              <span v-if="item.LesionType === 0">
                                {{ $fd('TargetState',parseInt(item.TableQuestions.Answers[i].lesionState)) }}
                              </span>
                              <span v-else-if="item.LesionType === 1">
                                {{ $fd('NoTargetState',parseInt(item.TableQuestions.Answers[i].lesionState)) }}
                              </span>
                              <span v-else>
                                {{ $fd('NewLesionState',parseInt(item.TableQuestions.Answers[i].lesionState)) }}
                              </span>
                            </div>
                            <div style="display: inline-block;margin-left:5px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width:60px;color:red;">
                              <template v-if="item.TableQuestions.Answers[i].suvMax && !isNaN(parseFloat(item.TableQuestions.Answers[i].suvMax))">
                                {{ item.TableQuestions.Answers[i].suvMax }} SUV
                              </template>
                            </div>
                          </div>
                        </div>
                        <div v-if="((item.LesionType === 0 && parseInt(item.TableQuestions.Answers[i].lesionState) === 0) || (item.LesionType === 1 && [0,1].includes(parseInt(item.TableQuestions.Answers[i].lesionState))) || (item.LesionType === 2 && parseInt(item.TableQuestions.Answers[i].lesionState) === 0)) && item.TableQuestions.Answers[i].IsCurrentTaskAdd === 'False'" style="position: absolute;right: 5px;top: 2px;transform: rotateY(180deg);">
                          <!-- 分裂 -->
                          <!-- <el-tooltip v-show="readingTaskState<2 && !!item.TableQuestions.Answers[i].RowId && !isBaseLineTask" class="item" :content="$t('trials:reading:button:split')" placement="left">
                            <i class="iconfont icon-24gl-split" style="color:#fff;font-size: 16px;" @click.stop="handleSplit(item.TableQuestions.Answers[i].RowId,item.Id)" />
                          </el-tooltip> -->
                        </div>

                      </div>

                    </template>
                    <QuestionForm
                      :ref="`${item.Id}_${q.RowIndex}`"
                      :questions="item.TableQuestions.Questions"
                      :answers="item.TableQuestions.Answers[i]"
                      :lesion-type="item.LesionType"
                      :order-mark="item.OrderMark"
                      :table-questions="tableQuestions"
                      :row-index="String(q.RowIndex)"
                      :question-name="item.QuestionName"
                      :parent-qs-id="item.Id"
                      :visit-task-id="visitTaskId"
                      :is-current-task="isCurrentTask"
                      :reading-task-state="readingTaskState"
                      :is-base-line-task="isBaseLineTask"
                      @changeLesionType="changeLesionType"
                      @resetQuestions="resetQuestions"
                      @determineExistsUnsavedLession="determineExistsUnsavedLession"
                      @close="close"
                    />
                  </el-collapse-item>

                </el-collapse>
              </div>
            </template>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import { getReadingQuestionAndAnswer, splitLesion } from '@/api/trials'
// import store from '@/store'
import { mapGetters } from 'vuex'
import QuestionForm from './TableQuestionItem'
import FusionEvent from './FusionEvent'
export default {
  name: 'TableQuestionList',
  components: {
    QuestionForm
  },
  data() {
    return {
      height: window.innerHeight - 140,
      questions: [],
      readingQuestions: [],
      activeName: '',
      activeItem: {
        activeRowIndex: null,
        activeCollapseId: null
      },
      visitTaskId: '',
      isCurrentTask: false,
      loading: false,
      unSaveTargets: [],
      temporaryLesions: [],
      readingTaskState: 2,
      isBaseLineTask: false,
      taskBlindName: '',
      tableQuestions: [],
      isFirstRender: false,
      currentModifyUid: null
    }
  },
  computed: {
    ...mapGetters(['currentReadingTaskState', 'language'])
  },
  watch: {
    currentReadingTaskState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.readingTaskState = val
        }
      }
    }
  },
  mounted() {
    this.visitTaskId = this.$route.query.visitTaskId
    this.taskBlindName = this.$route.query.taskBlindName
    this.readingTaskState = parseInt(this.$route.query.readingTaskState)
    this.isBaseLineTask = this.$route.query.isBaseLineTask === 'true'
    this.isCurrentTask = this.$route.query.isCurrentTask === 'true'
    // window.addEventListener('resize', this.setHeight)
    this.initList()
  },
  beforeDestroy() {
  },
  methods: {
    initList() {
      this.loading = true
      this.activeName = ''
      this.activeItem.activeRowIndex = null
      this.activeItem.activeCollapseId = null
      var params = {
        trialId: this.$route.query.trialId,
        visitTaskId: this.visitTaskId
      }
      getReadingQuestionAndAnswer(params).then(res => {
        this.questions = this.getQuestions(res.Result.SinglePage)
        this.getTableQuestions()
        this.$nextTick(() => {
          this.tableQuestions.forEach(item => {
            item.TableQuestions.Answers.forEach(i => {
              var refName = `${item.Id}_${i.RowIndex}`
              this.$refs[refName] && this.$refs[refName][0].initForm()
            })
          })
        })
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    async initList1() {
      var i = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
      if (i > -1) {
        this.visitTaskId = this.visitTaskList[i].VisitTaskId
        this.taskBlindName = this.visitTaskList[i].TaskBlindName
        this.readingTaskState = this.visitTaskList[i].ReadingTaskState
        this.isBaseLineTask = this.visitTaskList[i].IsBaseLineTask
        this.isCurrentTask = this.visitTaskList[i].IsCurrentTask
        this.activeName = ''
        this.activeItem.activeRowIndex = null
        this.activeItem.activeCollapseId = null
        this.questions = this.visitTaskList[i].ReadingQuestions
        this.$nextTick(() => {
          this.getTableQuestions()
          this.tableQuestions.forEach(item => {
            item.TableQuestions.Answers.forEach(i => {
              var refName = `${item.Id}_${i.RowIndex}`
              this.$refs[refName] && this.$refs[refName][0].initForm()
            })
          })
        })
      }
    },

    getQuestions(questions) {
      questions.forEach(item => {
        if (item.Type === 'table' && item.TableQuestions && item.TableQuestions.Answers.length > 0) {
          item.TableQuestions.Answers.forEach(answerObj => {
            this.$set(answerObj, 'lesionPart', this.getQuestionAnswer(item.TableQuestions.Questions, 8, answerObj))
            this.$set(answerObj, 'suvMax', this.getQuestionAnswer(item.TableQuestions.Questions, 20, answerObj))
            var isLymphLesion = this.getQuestionAnswer(item.TableQuestions.Questions, 2, answerObj)
            isLymphLesion = isLymphLesion ? parseInt(isLymphLesion) : null
            this.$set(answerObj, 'isLymphLesion', isLymphLesion)

            var lesionState = this.getQuestionAnswer(item.TableQuestions.Questions, 7, answerObj)
            lesionState = !isNaN(parseInt(lesionState)) ? parseInt(lesionState) : ''
            this.$set(answerObj, 'lesionState', lesionState)
            if (answerObj.RowId) {
              this.$set(answerObj, 'saveTypeEnum', 2)
            } else {
              this.$set(answerObj, 'saveTypeEnum', 0)
            }
          })
        }
        if (item.Childrens.length > 0) {
          this.getQuestions(item.Childrens)
        }
      })
      return questions
    },
    getTableQuestions() {
      this.tableQuestions = []
      this.questions.map(item => {
        if (item.Type === 'table') {
          this.tableQuestions.push(item)
        }
        if (item.Childrens.length > 0) {
          this.getTableQuestionsChild(item.Childrens)
        }
      })
    },
    getTableQuestionsChild(obj) {
      obj.map(item => {
        if (item.Type === 'table') {
          this.tableQuestions.push(item)
        }
        if (item.Childrens.length > 0) {
          this.getTableQuestionsChild(item.Childrens)
        }
      })
    },
    refreshReadingQuestionAndAnswer(type) {
      if (type === 0) {
        // 删除
        this.activeName = ''
        this.activeItem.activeRowIndex = null
        this.activeItem.activeCollapseId = null
      }

      this.getReadingQuestionAndAnswer(this.visitTaskId)
    },
    getReadingQuestionAndAnswer() {
      return new Promise(resolve => {
        const loading = this.$loading({ fullscreen: true })
        var params = {
          trialId: this.$route.query.trialId,
          visitTaskId: this.visitTaskId
        }
        getReadingQuestionAndAnswer(params).then(res => {
          this.questions = this.getQuestions(res.Result.SinglePage)
          this.getTableQuestions()
          this.$nextTick(() => {
            this.tableQuestions.forEach(item => {
              item.TableQuestions.Answers.forEach(i => {
                var refName = `${item.Id}_${i.RowIndex}`
                this.$refs[refName] && this.$refs[refName][0].initForm()
              })
            })
          })
          loading.close()
          resolve()
        })
      })
    },
    setHeight() {
      this.height = window.innerHeight - 140
    },
    getQuestionAnswer(questions, questionMark, answers) {
      var idx = questions.findIndex(i => i.QuestionMark === questionMark)
      if (idx > -1) {
        var questionId = questions[idx].Id
        return answers[questionId]
      } else {
        return ''
      }
    },
    async resetQuestions(obj) {
      this.setQuestions(this.questions, obj)
      // await store.dispatch('reading/setReadingQuestionAndAnswer', { questions: this.questions, visitTaskId: this.visitTaskId })

      this.getTableQuestions()
    },
    setQuestions(questions, obj) {
      questions.forEach(item => {
        if (item.Type === 'table' && item.Id === obj.questionId) {
          var idx = item.TableQuestions.Answers.findIndex(i => i.RowIndex === obj.rowIndex)
          item.TableQuestions.Answers[idx].isLymphLesion = obj.isLymphLesion
          item.TableQuestions.Answers[idx].loctation = obj.lesionOrgan
          item.TableQuestions.Answers[idx].lesionPart = obj.lesionPart
          item.TableQuestions.Answers[idx].saveTypeEnum = obj.saveTypeEnum
          item.TableQuestions.Answers[idx].suvMax = obj.suvMax
          for (const i in obj.anwsers) {
            if (i === 'OtherMeasureData' && obj.anwsers[i]) {
              item.TableQuestions.Answers[idx][i] = JSON.stringify(obj.anwsers[i])
            } else {
              item.TableQuestions.Answers[idx][i] = String(obj.anwsers[i])
            }
          }
        }
        if (item.Childrens.length > 0) {
          this.setQuestions(item.Childrens, obj)
        }
      })
    },
    // 分裂
    handleSplit(rowId, questionId) {
      // 消失，无法评估，疑似，太小等状态病灶不支持分裂
      // 获取病灶状态
      var idx = this.tableQuestions.findIndex(i => i.Id === questionId)
      if (idx > -1) {
        var i = this.tableQuestions[idx].TableQuestions.Answers.findIndex(i => i.RowId === rowId)
        if (i > -1) {
          var arr = []
          this.getUnSaveTarget()
          if (this.unSaveTargets.length > 0) {
            this.unSaveTargets.forEach(item => {
              arr.push(item.lessionName)
            })
          }
          var unSavedList = this.getAllUnSaveLesions()
          unSavedList.forEach(item => {
            arr.push(item.lessionName)
          })
          if (arr.length > 0) {
            // 病灶${message}，未保存。如果分裂，信息将被还原，是否继续？
            var msg = this.$t('trials:reading:warnning:msg3')
            msg = msg.replaceAll('xxx', arr.join('、'))
            this.$confirm(msg, {
              type: 'warning',
              distinguishCancelAndClose: true
            })
              .then(() => {
                this.split(rowId, questionId)
              })
              .catch(() => {})
          } else {
            // 是否确认分裂
            this.$confirm(this.$t('trials:reading:warnning:msg4'), {
              type: 'warning',
              distinguishCancelAndClose: true
            })
              .then(() => {
                this.split(rowId, questionId)
              })
              .catch(() => {})
          }
        }
      }
    },
    split(rowId, questionId) {
      const loading = this.$loading({ fullscreen: true })
      var params = {
        visitTaskId: this.visitTaskId,
        questionId: questionId,
        rowId: rowId
      }
      splitLesion(params).then(async res => {
        loading.close()
        await this.getReadingQuestionAndAnswer()
        this.$nextTick(() => {
          this.tableQuestions.forEach(item => {
            item.TableQuestions.Answers.forEach(i => {
              var refName = `${item.Id}_${i.RowIndex}`
              this.$refs[refName] && this.$refs[refName][0].initForm()
            })
          })
        })
      })
    },
    isCanActiveTool(toolName) {
      this.getUnSaveTarget()
      if (this.unSaveTargets.length > 0) {
        var rowIndex = String(this.unSaveTargets[0].rowIndex)
        var questionId = this.unSaveTargets[0].questionId
        const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        if (rowIndex === this.activeItem.activeRowIndex && questionId === this.activeItem.activeCollapseId && !this.$refs[refName][0].questionForm.OtherMeasureData) {
          if (toolName === 'CircleROI') {
            return { isCanActiveTool: true, reason: '' }
          } else {
            return { isCanActiveTool: false, reason: '' }
          }
        } else {
          var msg = this.$t('trials:reading:warnning:msg5')
          msg = msg.replace('xxx', this.unSaveTargets[0].lessionName)
          // `病灶${this.unSaveTargets[0].lessionName}信息未保存，不允许继续添加！`
          return { isCanActiveTool: false, reason: msg }
        }
      } else {
        if (this.activeName && this.activeItem.activeCollapseId && this.activeItem.activeRowIndex) {
          // const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
          if (toolName === 'CircleROI') {
            return { isCanActiveTool: true, reason: '' }
          } else {
            //  '请使用圆形测量工具！'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools7') }
          }
        } else {
          if (toolName === 'CircleROI') {
            return { isCanActiveTool: true, reason: '' }
          } else {
            // '请使用圆形测量工具！'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools7') }
          }
        }
      }
    },

    async handleAdd(qs) {
      // 判断是否有未保存的病灶
      this.getUnSaveTarget()
      if (this.unSaveTargets.length > 0) {
        // 病灶${this.unSaveTargets[0].lessionName}信息未保存，不允许继续添加！
        let msg = this.$t('trials:reading:warnning:msg5')
        msg = msg.replace('xxx', this.unSaveTargets[0].lessionName)

        this.$confirm(msg, {
          type: 'warning',
          showCancelButton: false,
          callback: action => {}
        })
        return
      }
      if (!!qs.MaxQuestionCount && qs.MaxQuestionCount <= qs.TableQuestions.Answers.length) {
        let msg = this.$t('trials:reading:warnning:msg14')
        msg = msg.replace('xxx', qs.MaxQuestionCount)
        this.$confirm(msg, {
          type: 'warning',
          showCancelButton: false,
          callback: action => {}
        })
      } else {
        // saveTypeEnum: 0
        var obj = { saveTypeEnum: 0 }
        var maxIndex = this.getMaxRowIndex(qs.TableQuestions.Answers)
        obj.RowIndex = `${maxIndex + 1}.00`
        // await store.dispatch('reading/addReadingQuestionAndAnswer', { lesionType: qs.LesionType, visitTaskId: this.visitTaskId, lesionObj: obj })
        this.findQuestionAndAddLesion(this.questions, { lesionType: qs.LesionType, lesionObj: obj })

        this.activeItem.activeRowIndex = String(obj.RowIndex)
        this.activeItem.activeCollapseId = qs.Id
        this.activeName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        FusionEvent.$emit('imageLocation', { otherMeasureData: '', markTool: 'CircleROI', isMarked: false })
      }
    },

    getMaxRowIndex(answerList) {
      if (answerList.length > 0) {
        var arr = []
        answerList.forEach(item => {
          var rowIndex = item.RowIndex
          arr.push(parseInt(rowIndex))
        })
        var max = Math.max.apply(null, arr)
        return max
      } else {
        return 0
      }
    },
    determineExistsUnsavedLession(callback) {
      // const loading = this.$loading({ fullscreen: true })
      this.getUnSaveTarget()
      if (this.unSaveTargets.length > 0) {
        var rowIndex = String(this.unSaveTargets[0].rowIndex)
        var questionId = this.unSaveTargets[0].questionId
        if (rowIndex === String(this.activeItem.activeRowIndex) && questionId === this.activeItem.activeCollapseId) {
          callback(true)
          // loading.close()
          return
        } else {
          // 病灶${this.unSaveTargets[0].lessionName}信息未保存，不允许执行此操作！
          let msg = this.$t('trials:reading:warnning:msg17')
          msg = msg.replace('xxx', this.unSaveTargets[0].lessionName)
          this.$confirm(msg, {
            type: 'warning',
            showCancelButton: false,
            callback: action => { }
          })
          callback(false)
          // loading.close()
          return
        }
      }
      callback(true)
      // loading.close()
      return
    },
    getUnSaveTarget() {
      console.log('getUnSaveTarget')
      this.unSaveTargets = []
      this.tableQuestions.map(item => {
        if (item.TableQuestions && item.TableQuestions.Answers) {
          item.TableQuestions.Answers.map(t => {
            if (!t.RowId) {
              var lessionName = this.getLesionName(item.OrderMark, t.RowIndex)
              this.unSaveTargets.push({ lessionName: lessionName, rowIndex: t.RowIndex, questionId: item.Id })
            }
          })
        }
      })
      // console.log(this.unSaveTargets)
      return this.unSaveTargets
    },
    getAllUnSaveLesions() {
      var arr = []
      this.tableQuestions.map(item => {
        if (item.TableQuestions && item.TableQuestions.Answers) {
          item.TableQuestions.Answers.map(t => {
            const refName = `${item.Id}_${t.RowIndex}`
            if (this.$refs[refName] && this.$refs[refName][0] && this.$refs[refName][0].questionForm.saveTypeEnum !== 2) {
              var lessionName = this.getLesionName(item.OrderMark, t.RowIndex)
              arr.push({ lessionName: lessionName, rowIndex: t.RowIndex, questionId: item.Id })
            }
          })
        }
      })
      return arr
    },
    getLesionName(orderMark, rowIndex) {
      var lessionName = ''
      var rowIndexArr = rowIndex.split('.')
      var x = parseInt(rowIndexArr[0])
      var y = parseInt(rowIndexArr[1])
      if (y > 0) {
        y = String.fromCharCode(parseInt(rowIndexArr[1]) - 1 + 65 + 32)
        lessionName = `${orderMark}${String(x).padStart(2, '0')}${y}`
      } else {
        lessionName = `${orderMark}${String(x).padStart(2, '0')}`
      }

      return lessionName
    },
    handleCollapseChange(val) {
      if (this.activeName) {
        var arr = this.activeName.split('_')
        this.activeItem.activeRowIndex = arr[1]
        this.activeItem.activeCollapseId = arr[0]
        this.$nextTick(() => {
          const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
          if (this.$refs[refName][0].questionForm.IsDicomReading !== false) {
            var markTool = 'CircleROI'
            var isMarked = !!this.$refs[refName][0].questionForm.OtherMeasureData || this.$refs[refName][0].questionForm.saveTypeEnum === 2
          }
          FusionEvent.$emit('imageLocation', { otherMeasureData: this.$refs[refName][0].questionForm.OtherMeasureData, markTool, isMarked })
        })
      } else {
        this.activeItem.activeRowIndex = null
        this.activeItem.activeCollapseId = null
      }
    },
    setActiveCollapse(obj) {
      if (obj.OrderMarkName === 'Liver' || obj.OrderMarkName === 'Mediastinum') {
        this.activeItem.activeCollapseId = null
        this.activeItem.activeRowIndex = null
        this.activeName = ''
      } else {
        this.activeItem.activeCollapseId = obj.QuestionId
        this.activeItem.activeRowIndex = obj.RowIndex
        this.activeName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
      }
    },
    collapseRightClick(e, obj, activeCollapseId, activeRowIndex) {
      const refName = `${activeCollapseId}_${activeRowIndex}`
      FusionEvent.$emit('imageLocation', { otherMeasureData: this.$refs[refName][0].questionForm.OtherMeasureData })

      e.stopImmediatePropagation()
      e.stopPropagation()
      e.preventDefault()
    },
    // 更改病灶类型
    async changeLesionType(questionsObj) {
      // await store.dispatch('reading/removeReadingQuestionAndAnswer', { lesionType: questionsObj.oldLesionType, rowIndex: questionsObj.rowIndex, visitTaskId: this.visitTaskId })
      this.questions = this.findQuestionAndRemoveLesion(this.questions, { lesionType: questionsObj.oldLesionType, rowIndex: questionsObj.rowIndex })
      // saveTypeEnum: 0
      var lesionObj = { }
      var questionObj = questionsObj.questionForm
      // 切换到新的病灶集合
      var targetObj = this.tableQuestions.find(item => item.LesionType === questionsObj.newLesionType)
      var lesionMark = ''
      var maxIndex = this.getMaxRowIndex(targetObj.TableQuestions.Answers)
      lesionObj.RowIndex = `${maxIndex + 1}.00`
      lesionMark = `${targetObj.OrderMark}${String(maxIndex + 1).padStart(2, '0')}`
      targetObj.TableQuestions.Questions.forEach(i => {
        var obj = questionObj.find(v => v.QuestionMark === i.QuestionMark)
        if (obj) {
          lesionObj[i.Id] = obj.Answer
        }
      })

      if (questionsObj.otherMeasureData) {
        FusionEvent.$emit('removeAnnotation', { otherMeasureData: questionsObj.otherMeasureData })
        questionsObj.otherMeasureData.data.remark = lesionMark
        lesionObj.OtherMeasureData = JSON.stringify(questionsObj.otherMeasureData)
      }

      var deleteInfo = null
      if (questionsObj.rowId) {
        deleteInfo = { rowId: questionsObj.rowId, questionId: questionsObj.questionId }
        lesionObj.RowId = questionsObj.rowId
      }
      // await store.dispatch('reading/addReadingQuestionAndAnswer', { lesionType: questionsObj.newLesionType, visitTaskId: this.visitTaskId, lesionObj: lesionObj })
      this.findQuestionAndAddLesion(this.questions, { lesionType: questionsObj.newLesionType, lesionObj: lesionObj })

      this.activeItem.activeRowIndex = String(lesionObj.RowIndex)
      this.activeItem.activeCollapseId = targetObj.Id
      this.activeName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
      const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
      this.$nextTick(() => {
        if (deleteInfo) {
          this.$refs[refName][0].setDeleteInfo(deleteInfo)
        }
        if (questionsObj.otherMeasureData) {
          const measureData = {}
          measureData.frame = 0
          measureData.data = questionsObj.otherMeasureData
          measureData.type = questionsObj.otherMeasureData.metadata.toolName
          measureData.suvMax = questionsObj.suvMax

          this.$refs[refName][0].setMeasureData(measureData)
        }
      })
    },
    findQuestionAndAddLesion(questions, obj) {
      for (var i = 0; i < questions.length; i++) {
        if (questions[i].Type === 'table' && questions[i].TableQuestions && (questions[i].LesionType === obj.lesionType)) {
          var sourceObj = {}
          questions[i].TableQuestions.Questions.forEach(item => {
            sourceObj[item.Id] = ''
          })
          var targetObj = Object.assign(sourceObj, obj.lesionObj)
          targetObj.IsCurrentTaskAdd = 'True'
          questions[i].TableQuestions.Answers.push(targetObj)
          break
        }
        if (questions[i].Childrens.length > 0) {
          this.findQuestionAndAddLesion(questions[i].Childrens, obj)
        }
      }
      return questions
    },
    findQuestionAndRemoveLesion(questions, obj) {
      for (var i = 0; i < questions.length; i++) {
        if (questions[i].Type === 'table' && questions[i].TableQuestions && (questions[i].LesionType === obj.lesionType) && questions[i].TableQuestions.Answers.length > 0) {
          var idx = questions[i].TableQuestions.Answers.findIndex(i => String(i.RowIndex) === String(obj.rowIndex))
          if (idx > -1) {
            questions[i].TableQuestions.Answers.splice(idx, 1)
            break
          }
        }
        if (questions[i].Childrens.length > 0) {
          this.findQuestionAndRemoveLesion(questions[i].Childrens, obj)
        }
      }
      return questions
    },
    // 创建新病灶
    createNLTarget(measureData) {
      var idx = this.tableQuestions.findIndex(item => item.LesionType === 2)
      if (idx > -1) {
        this.addTarget(this.tableQuestions[idx], measureData)
      }
    },
    // 创建靶病灶
    createTTarget(measureData) {
      var idx = this.tableQuestions.findIndex(item => item.LesionType === 0)
      if (idx > -1) {
        this.addTarget(this.tableQuestions[idx], measureData)
      }
    },

    async addTarget(target, measureData) {
      // saveTypeEnum: 0
      var obj = {}
      var maxIndex = this.getMaxRowIndex(target.TableQuestions.Answers)
      obj.RowIndex = `${maxIndex + 1}.00`
      obj.measureObj = measureData
      // await store.dispatch('reading/addReadingQuestionAndAnswer', { lesionType: target.LesionType, visitTaskId: this.visitTaskId, lesionObj: obj })
      this.findQuestionAndAddLesion(this.questions, { lesionType: target.LesionType, visitTaskId: this.visitTaskId, lesionObj: obj })

      this.activeItem.activeRowIndex = String(obj.RowIndex)
      this.activeItem.activeCollapseId = target.Id
      this.activeName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
    },
    createNTTarget(measureData) {
      var idx = this.tableQuestions.findIndex(item => item.LesionType === 1)
      if (idx > -1) {
        this.addTarget(this.tableQuestions[idx], measureData)
      }
    },
    setCollapseActive(measureData) {
      if (measureData) {
        if (this.activeItem.activeRowIndex === measureData.RowIndex && this.activeItem.activeCollapseId === measureData.QuestionId) {
          return
        } else {
          this.activeItem.activeCollapseId = measureData.QuestionId
          this.activeItem.activeRowIndex = measureData.RowIndex
          this.activeName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        }
      }
    },
    modifyMeasuredData(measureObj) {
      if (measureObj.questionInfo) {
        this.activeItem.activeCollapseId = measureObj.questionInfo.QuestionId
        this.activeItem.activeRowIndex = String(measureObj.questionInfo.RowIndex)
        this.activeName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        if (this.$refs[refName]) {
          this.$refs[refName][0].setMeasureData(measureObj.measureData)
        }
      }
    },
    clearMeasuredData() {
      if (this.activeItem.activeCollapseId && this.activeItem.activeRowIndex && this.activeName) {
        const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        this.$refs[refName][0].clearMeasurement()
      }
    },
    setOutsideMeasuredData(annotation) {
      if (this.activeItem.activeCollapseId && this.activeItem.activeRowIndex && this.activeName) {
        const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        this.$refs[refName][0].setOutsideMeasuredData(annotation)
      }
    },
    // 设置测量数据
    setMeasuredData(measureData) {
      // this.$nextTick(() => {
      //   var uid = measureData.data.annotationUID
      //   if (this.activeItem.activeCollapseId) {
      //   // 有病灶激活
      //     const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
      //     if (!this.$refs[refName][0].questionForm.OtherMeasureData || this.currentModifyUid === uid) {
      //     // 激活病灶不存在标记，给病灶绑定标记信息
      //       this.$refs[refName][0].setMeasureData(measureData)
      //       this.currentModifyUid = measureData.data.annotationUID
      //       return
      //     }
      //   } else {
      //     if (measureData.data.questionId && measureData.data.rowIndex) {
      //       this.activeItem.activeCollapseId = measureData.data.questionId
      //       this.activeItem.activeRowIndex = String(measureData.data.rowIndex)
      //       this.activeName = `${measureData.data.questionId}_${measureData.data.rowIndex}`
      //       const refName = `${measureData.data.questionId}_${measureData.data.rowIndex}`
      //       this.$refs[refName][0].setMeasureData(measureData)
      //       this.currentModifyUid = measureData.data.annotationUID
      //       return
      //     }
      //   }
      //   // 激活病灶存在标记/无病灶激活，则创建病灶，并激活改标记
      //   if (this.isBaseLineTask) {
      //     var idx = this.tableQuestions.findIndex(item => item.LesionType === 0)
      //     if (this.tableQuestions[idx].TableQuestions.Answers.length < this.tableQuestions[idx].MaxQuestionCount && (measureData.type === 'CircleROI')) {
      //       this.createTTarget(measureData)
      //     } else {
      //       this.createNTTarget(measureData)
      //     }
      //   } else {
      //     this.createNLTarget(measureData)
      //   }
      // })
      if (measureData.data && measureData.data.data.remark) {
        return
      }
      if (this.activeName && this.activeItem.activeCollapseId && this.activeItem.activeRowIndex) {
        // 判断是否存在测量数据
        this.$nextTick(() => {
          const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
          if (!this.$refs[refName][0].questionForm.OtherMeasureData) {
            this.$refs[refName][0].setMeasureData(measureData)
          } else {
            if (this.isBaseLineTask) {
              var idx = this.tableQuestions.findIndex(item => item.LesionType === 0)
              if (this.tableQuestions[idx].TableQuestions.Answers.length < this.tableQuestions[idx].MaxQuestionCount && (measureData.type === 'CircleROI')) {
                this.createTTarget(measureData)
              } else {
                this.createNTTarget(measureData)
              }
            } else {
              this.createNLTarget(measureData)
            }
          }
        })
      } else {
        if (this.isBaseLineTask) {
          var idx = this.tableQuestions.findIndex(item => item.LesionType === 0)
          if (this.tableQuestions[idx].TableQuestions.Answers.length < this.tableQuestions[idx].MaxQuestionCount && (measureData.type === 'CircleROI')) {
            this.createTTarget(measureData)
          } else {
            this.createNTTarget(measureData)
          }
        } else {
          this.createNLTarget(measureData)
        }
      }
    },
    async close(questionsObj) {
      if (questionsObj) {
        this.getReadingQuestionAndAnswer(questionsObj.visitTaskId)
        FusionEvent.$emit('getAnnotations')
        FusionEvent.$emit('refreshQuestions')
      }
      this.activeItem.activeRowIndex = null
      this.activeItem.activeCollapseId = null
      this.activeName = ''
    }

  }
}
</script>
<style lang="scss" scoped>
.measurement-wrapper{

  // .container{
  //   padding: 10px;
  // }
  .title{
    padding: 5px;
    font-weight: bold;
    color: #ddd;
    font-size: 15px;

  }
  .add-icon{
    padding: 5px;
    font-weight: bold;
    color: #ddd;
    font-size: 15px;
    border: 1px solid #938b8b;
    margin-bottom: 2px;
    cursor: pointer;
  }
  .add-icon:hover{
    background-color: #607d8b;
  }

  .flex-row{
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    background-color: #424242;

  }
  .lesion_list{
    position: relative;
  }
  .el-collapse{
    border-bottom:none;
    border-top:none;
    /deep/ .el-collapse-item{
      background-color: #000!important;
      color: #ddd;

    }
    /deep/ .el-collapse-item__header{
      background-color: #000!important;
      color: #ddd;
      border-bottom-color:#5a5a5a;
      padding-left: 5px;
      height: 35px;
      line-height: 35px;
    }
    /deep/ .el-collapse-item__wrap{
      background-color: #000!important;
      color: #ddd;
    }
    /deep/ .el-collapse-item__content{
      width:260px;
      position: absolute;
      top: 0px;
      right: 0px;
      // border: 1px solid #ffeb3b;
      border: 1px solid #fff;
      z-index: 1;
      color: #ddd;
      padding: 5px;
      background-color:#1e1e1e;
    }

  }
}
</style>
