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

    <div class="container">
      <div class="basic-info">
        <h3 v-if="isReadingShowSubjectInfo">
          <span v-if="subjectCode">{{ subjectCode }} </span>
          <span style="margin-left:5px;">{{ taskBlindName }}</span>
        </h3>
        <div v-if="readingTaskState < 2">
          <el-tooltip class="item" effect="dark" :content="$t('trials:dicomReading:message:confirmReset')" placement="bottom">
            <i
              class="el-icon-refresh-left"
              @click="resetMeasuredData"
            />
          </el-tooltip>
        </div>
      </div>
      <!-- 非测量问题 -->
      <div class="lesions">
        <!-- 影像质量问题 -->
        <!-- <Questions
          ref="ecrf"
          :question-form-change-state="questionFormChangeState"
          :question-form-change-num="questionFormChangeNum"
          :group-classify="1"
        /> -->
        <Questions
          ref="ecrf"
          :question-form-change-state="true"
          :question-form-change-num="0"
          :is-qulity-issues="false"
          :group-classify="1"
        />
      </div>
      <!-- 测量问题 -->
      <template v-if="questions.length > 0 && CriterionType !== 10">
        <div v-for="(qs,index) in questions" :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">
            <div v-for="item in qs.Childrens" v-show="!(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: item.LesionType === 1 && readingTaskState < 2?'58px':'50px',top: '2px'}">
                        <!-- white-space: nowrap;overflow: hidden;text-overflow: ellipsis; -->

                        <div style="font-size: 11px;width:210px;height: 30px;display: flex;justify-content: flex-start;flex-wrap: nowrap;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
                          <el-tooltip v-if="item.TableQuestions.Answers[i].SplitOrMergeType === '1' || item.TableQuestions.Answers[i].SplitOrMergeType === '3'" class="item" effect="dark" :content="`${$t('trials:reading:message:fused')}${item.TableQuestions.Answers[i].SplitOrMergeLesionName}`" placement="bottom">
                            <div v-if="item.TableQuestions.Answers[i].SplitOrMergeType === '1' || item.TableQuestions.Answers[i].SplitOrMergeType === '3'">
                              <span class="login-cycle" />
                            </div>
                          </el-tooltip>
                          <div v-if="item.TableQuestions.Answers[i].SplitOrMergeType === '4'">
                            <span class="login-cycle" />
                          </div>
                          <el-tooltip v-if="!!item.TableQuestions.Answers[i].lesionPart" class="item" effect="dark" :content="item.TableQuestions.Answers[i].lesionPart" placement="bottom">
                            <div v-if="item.TableQuestions.Answers[i].lesionPart" style="max-width: 100px;overflow: hidden;">
                              {{ item.TableQuestions.Answers[i].lesionPart }}
                            </div>
                          </el-tooltip>
                          <div v-if="item.LesionType === 0" style="margin:0 5px;">
                            {{ $fd('TargetState',parseInt(item.TableQuestions.Answers[i].lesionState)) }}
                          </div>
                          <div v-else-if="item.LesionType === 1" style="margin:0 5px;">
                            {{ $fd('NoTargetState',parseInt(item.TableQuestions.Answers[i].lesionState)) }}
                          </div>
                          <div v-else style="margin:0 5px;">
                            {{ $fd('NewLesionState',parseInt(item.TableQuestions.Answers[i].lesionState)) }}
                          </div>
                          <div v-if="!isNaN(parseInt(item.TableQuestions.Answers[i].lesionLength))">
                            <el-tooltip class="item" effect="dark" :content="`${item.TableQuestions.Answers[i].lesionLength}*${item.TableQuestions.Answers[i].lesionShort}m㎡`" placement="bottom">
                              <span>{{ item.TableQuestions.Answers[i].lesionLength }}*{{ item.TableQuestions.Answers[i].lesionShort }}m㎡</span>
                            </el-tooltip>
                          </div>

                        </div>
                      </div>
                      <div v-if="item.TableQuestions.Answers[i].IsCurrentTaskAdd === 'False' && readingTaskState < 2" style="position: absolute;right: 5px;top: 2px;">
                        <!-- 分裂 -->
                        <el-tooltip v-show="!!item.TableQuestions.Answers[i].RowId && item.TableQuestions.Answers[i].SplitOrMergeType !== '4' && ((item.LesionType === 0 && [0,4].includes(parseInt(item.TableQuestions.Answers[i].lesionState))) || (item.LesionType === 1 && [0,1].includes(parseInt(item.TableQuestions.Answers[i].lesionState))) || (item.LesionType === 2 && parseInt(item.TableQuestions.Answers[i].lesionState) === 0))" class="item" :content="$t('trials:reading:button:split')" placement="bottom">
                          <i class="iconfont icon-24gl-split" style="color:#fff;font-size: 16px;" @click.stop="handleSplit(item.TableQuestions.Answers[i].RowId,item.Id)" />
                        </el-tooltip>

                        <!-- 融合 -->
                        <el-tooltip v-show="!!item.TableQuestions.Answers[i].RowId && item.TableQuestions.Answers[i].SplitOrMergeType !== '2' && ((item.LesionType === 0 && [0,1,4].includes(parseInt(item.TableQuestions.Answers[i].lesionState))))" class="item" :content="$t('trials:reading:button:merge')" placement="bottom">
                          <i class="iconfont icon-24gl-merge" style="color:#fff;font-size: 16px;" @click.stop="handleMerge(item.TableQuestions.Answers[i],item.Id,item.OrderMark)" />
                        </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"
                    @getReadingQuestionAndAnswer="getReadingQuestionAndAnswer"
                    @determineExistsUnsavedLession="determineExistsUnsavedLession"
                    @resetQuestions="resetQuestions"
                    @close="close"
                  />
                </el-collapse-item>

              </el-collapse>
            </div>
          </div>
        </div>
      </template>
      <!-- <el-divider /> -->
      <!-- 肝脏评估 -->
      <Questions
        ref="ecrf2"
        :question-form-change-state="true"
        :question-form-change-num="0"
        :group-classify="2"
        :is-qulity-issues="false"
        style="margin-top:20px"
        :question-type="6"
        @setNonTargetMeasurementStatus="setNonTargetMeasurementStatus"
      />
      <!-- 脾脏评估 -->
      <Questions
        ref="ecrf3"
        :question-form-change-state="true"
        :question-form-change-num="0"
        :group-classify="3"
        :is-qulity-issues="false"
        :question-type="7"
        @setNonTargetMeasurementStatus="setNonTargetMeasurementStatus"
      />
    </div>
    <el-dialog
      v-if="merge.visible"
      v-loading="merge.loading"
      :visible.sync="merge.visible"
      :close-on-click-modal="false"
      :title="$t('trials:reading:lugano:message:merge')"
      width="500px"
    >
      <div class="merge-table">
        <div class="merge-label">
          <label>{{ $t('trials:reading:lugano:label:currentLesion') }}</label>
          <span>{{ mergeInfo.lesionName }}</span>
          <span style="margin-left:10px">{{ mergeInfo.lesionPart }}</span>
        </div>
        <div class="merge-label"><label>{{ $t('trials:reading:lugano:label:selectLesion') }}</label></div>
        <el-table
          :data="lesionData"
          style="width: 450px"
          size="small"
          height="200"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="45"
          />
          <el-table-column
            prop="OrderMarkName"
            :label="$t('trials:reading:lugano:label:lesionNumber')"
            width="100"
          />
          <el-table-column
            prop="Part"
            :label="$t('trials:reading:lugano:label:lesionLocation')"
            min-width="120"
            show-overflow-tooltip
          />
        </el-table>
      </div>
      <div slot="footer" style="text-align:right;">
        <!-- 取消 -->
        <el-button size="mini" @click="merge.visible = false">{{ $t('common:button:cancel') }}</el-button>
        <!-- 确认 -->
        <el-button
          type="primary"
          size="mini"
          :disabled="mergeList.length === 0"
          @click="confirmMerge"
        >
          {{ $t('common:button:confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { splitLesion, getSplitPPdSum, getCanMergeLesion, mergeLesion } from '@/api/trials'
import { resetReadingTask } from '@/api/reading'
import DicomEvent from './../DicomEvent'
import store from '@/store'
import { mapGetters } from 'vuex'
import Questions from './../Questions'
import QuestionForm from './QuestionForm'
export default {
  name: 'MeasurementList',
  components: {
    Questions,
    QuestionForm
  },
  props: {
    isShow: {
      type: Boolean,
      required: true
    },
    isReadingShowSubjectInfo: {
      type: Boolean,
      required: true
    },
    questionFormChangeState: {
      type: Boolean,
      default() {
        return false
      }
    },
    questionFormChangeNum: {
      type: Number,
      default() {
        return 0
      }
    }
  },
  data() {
    return {
      questions: [],
      activeName: '',
      activeItem: {
        activeRowIndex: null,
        activeCollapseId: null
      },
      visitTaskId: '',
      isCurrentTask: false,
      loading: false,
      unSaveTargets: [],
      temporaryLesions: [],
      readingTaskState: 2,
      isBaseLineTask: false,
      taskBlindName: '',
      tableQuestions: [],
      isFirstRender: false,
      CriterionType: null,
      subjectCode: '',
      isNonTargetMeasurement: false,
      splitTargetLesions: [],
      lesionTypeQuestionId: '',
      merge: { visible: false, loading: false },
      lesionData: [],
      mergeInfo: {},
      mergeList: []
    }
  },
  computed: {
    ...mapGetters(['visitTaskList', 'language', 'lastCanvasTaskId', 'currentReadingTaskState'])
  },
  watch: {
    lastCanvasTaskId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initList()
        }
        console.log('lastCanvasTaskId', val)
      }
    },
    currentReadingTaskState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.readingTaskState = val
        }
      }
    }
  },
  mounted() {
    // this.subjectCode = this.$router.currentRoute.query.subjectCode
    this.subjectCode = localStorage.getItem('subjectCode')
    window.addEventListener('message', this.receiveMsg)
    this.CriterionType = parseInt(localStorage.getItem('CriterionType'))
    DicomEvent.$on('setCollapseActive', measureData => {
      this.setCollapseActive(measureData)
      console.log('setCollapseActive')
    })
    DicomEvent.$on('changeLesionType', (questionsObj) => {
      this.changeLesionType(questionsObj)
      console.log('changeLesionType')
    })
    DicomEvent.$on('getAllUnSaveLesions', (callback) => {
      var list = this.getAllUnSaveLesions()
      callback(list)
      console.log('getAllUnSaveLesions')
    })

    DicomEvent.$on('split', measureData => {
      this.handleSplit(measureData.RowId, measureData.QuestionId)
    })
    DicomEvent.$on('refreshQuestions', async(obj) => {
      var triald = this.$router.currentRoute.query.trialId
      await store.dispatch('reading/refreshDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskId })
      this.$nextTick(() => {
        this.$refs['ecrf'].getQuestions(this.visitTaskId)
        this.$refs['ecrf2'].getQuestions(this.visitTaskId)
        this.$refs['ecrf3'].getQuestions(this.visitTaskId)
      })
    })
    DicomEvent.$on('refreshSplitTargetLesionPDD', async(callback) => {
      const res = await getSplitPPdSum({ visitTaskId: this.visitTaskId })
      this.splitTargetLesions = res.Result
      if (this.splitTargetLesions && this.splitTargetLesions.length > 0) {
        this.splitTargetLesions.map(i => {
          var refName = `${this.lesionTypeQuestionId}_${i.RowIndex}`
          console.log(refName)
          var params = {}
          params.splitLesionTargetPPD = i.AllPPD
          params.splitLesionTargetLDi = i.AllLDi
          params.splitLesionTargetSDi = i.AllSDi
          this.$refs[refName] && this.$refs[refName][0].initForm(params)
        })
      }
      callback(true)
    })
  },
  beforeDestroy() {
    DicomEvent.$off('setCollapseActive')
    DicomEvent.$off('changeLesionType')
    DicomEvent.$off('getUnSaveTarget')
    DicomEvent.$off('refreshQuestions')
  },
  methods: {
    async initList() {
      var i = this.visitTaskList.findIndex(i => i.VisitTaskId === this.lastCanvasTaskId)
      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
        if (!this.visitTaskList[i].IsInit) {
          var loading = this.$loading({ fullscreen: true })
          var triald = this.$router.currentRoute.query.trialId
          if (!this.visitTaskList[i].measureDataInit) {
            await store.dispatch('reading/getMeasuredData', this.visitTaskList[i].VisitTaskId)
          }
          if (!this.visitTaskList[i].studyListInit) {
            await store.dispatch('reading/getStudyInfo', { trialId: triald, subjectVisitId: this.visitTaskList[i].VisitId, visitTaskId: this.visitTaskList[i].VisitTaskId, taskBlindName: this.visitTaskList[i].TaskBlindName })
          }
          if (!this.visitTaskList[i].readingQuestionsInit) {
            await store.dispatch('reading/getReadingQuestionAndAnswer', { trialId: triald, visitTaskId: this.visitTaskList[i].VisitTaskId })
          }
          if (!this.visitTaskList[i].questionsInit) {
            await store.dispatch('reading/getDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskList[i].VisitTaskId })
          }

          await store.dispatch('reading/setStatus', { visitTaskId: this.visitTaskList[i].VisitTaskId })
          loading.close()
        }
        if (!this.isBaseLineTask) {
          const res = await getSplitPPdSum({ visitTaskId: this.visitTaskId })
          this.splitTargetLesions = res.Result
        }
        this.questions = this.visitTaskList[i].ReadingQuestions
        this.$nextTick(() => {
          this.$refs['ecrf'].getQuestions(this.visitTaskId)
          this.$refs['ecrf2'].getQuestions(this.visitTaskId)
          this.$refs['ecrf3'].getQuestions(this.visitTaskId)
          this.getTableQuestions()
          this.tableQuestions.forEach(item => {
            item.TableQuestions.Answers.forEach(i => {
              var refName = `${item.Id}_${i.RowIndex}`
              var params = {}
              if (parseInt(i.LesionType) === 0) {
                this.lesionTypeQuestionId = item.Id
                var idx = this.splitTargetLesions.findIndex(v => v.RowId === i.RowId)
                if (idx > -1) {
                  params.splitLesionTargetPPD = this.splitTargetLesions[idx].AllPPD
                  params.splitLesionTargetLDi = this.splitTargetLesions[idx].AllLDi
                  params.splitLesionTargetSDi = this.splitTargetLesions[idx].AllSDi
                }
              }
              this.$refs[refName] && this.$refs[refName][0].initForm(params)
            })
          })
        })
      }
    },
    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].lesionLength = obj.lesionLength
          item.TableQuestions.Answers[idx].lesionShort = obj.lesionShort
          item.TableQuestions.Answers[idx].lesionState = obj.lesionState
          item.TableQuestions.Answers[idx].saveTypeEnum = obj.saveTypeEnum

          for (const i in obj.anwsers) {
            if (i === 'MeasureData' && obj.anwsers[i]) {
              item.TableQuestions.Answers[idx].InstanceId = obj.anwsers[i].instanceId
              item.TableQuestions.Answers[idx].SeriesId = obj.anwsers[i].seriesId
              item.TableQuestions.Answers[idx][i] = JSON.stringify(obj.anwsers[i])
              item.TableQuestions.Answers[idx].isDicomReading = !(obj.anwsers[i].IsDicomReading === false || obj.anwsers[i].IsDicomReading === 'False')
            } else {
              item.TableQuestions.Answers[idx][i] = String(obj.anwsers[i])
            }
          }
        }
        if (item.Childrens.length > 0) {
          this.setQuestions(item.Childrens, obj)
        }
      })
    },
    getQuestions(questions) {
      questions.forEach(item => {
        if (item.Type === 'table' && item.TableQuestions && item.TableQuestions.Answers.length > 0) {
          item.TableQuestions.Answers.forEach(answerObj => {
            this.$set(answerObj, 'loctation', this.getQuestionAnswer(item.TableQuestions.Questions, 6, answerObj))
            this.$set(answerObj, 'lesionLength', this.getQuestionAnswer(item.TableQuestions.Questions, 0, answerObj))
            this.$set(answerObj, 'lesionShort', this.getQuestionAnswer(item.TableQuestions.Questions, 1, 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) {
              var idx = item.TableQuestions.Questions.findIndex(i => i.QuestionMark === 11)
              if (idx > -1) {
                var lesionNum = this.getQuestionAnswer(item.TableQuestions.Questions, 11, answerObj)
                lesionNum = !isNaN(parseInt(lesionNum)) ? parseInt(lesionNum) : ''
                this.$set(answerObj, 'saveTypeEnum', isNaN(parseInt(lesionNum)) ? 1 : 2)
              } else {
                this.$set(answerObj, 'saveTypeEnum', isNaN(parseInt(lesionState)) ? 1 : 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(async resolve => {
        try {
          const loading = this.$loading({ fullscreen: true })

          await store.dispatch('reading/refreshReadingQuestionAndAnswer', { trialId: this.$router.currentRoute.query.trialId, visitTaskId: this.visitTaskId }).then(async() => {
            var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
            if (idx > -1) {
              if (this.visitTaskList[idx].ReadingQuestions.length > 0) {
                this.questions = this.visitTaskList[idx].ReadingQuestions
              }
              this.readingTaskState = this.visitTaskList[idx].ReadingTaskState
              this.isBaseLineTask = this.visitTaskList[idx].IsBaseLineTask
              this.isCurrentTask = this.visitTaskList[idx].IsCurrentTask
            }
            if (!this.isBaseLineTask) {
              const res = await getSplitPPdSum({ visitTaskId: this.visitTaskId })
              this.splitTargetLesions = res.Result
            }
            this.getTableQuestions()
            this.$nextTick(() => {
              this.tableQuestions.forEach(item => {
                item.TableQuestions.Answers.forEach(i => {
                  var refName = `${item.Id}_${i.RowIndex}`
                  var params = {}
                  if (parseInt(i.LesionType) === 0) {
                    var idx = this.splitTargetLesions.findIndex(v => v.RowId === i.RowId)
                    if (idx > -1) {
                      params.splitLesionTargetPPD = this.splitTargetLesions[idx].AllPPD
                      params.splitLesionTargetLDi = this.splitTargetLesions[idx].AllLDi
                      params.splitLesionTargetSDi = this.splitTargetLesions[idx].AllSDi
                    }
                  }
                  this.$refs[refName] && this.$refs[refName][0].initForm(params)
                })
              })
            })
          }) 
          await store.dispatch('reading/refreshMeasuredData', this.visitTaskId)
          DicomEvent.$emit('getMeasureData')
          await store.dispatch('reading/refreshDicomReadingQuestionAnswer', { trialId: this.$route.query.trialId, visitTaskId: this.visitTaskId })
          this.$refs['ecrf'].getQuestions(this.visitTaskId, true)
          this.$refs['ecrf2'].getQuestions(this.visitTaskId, true)
          this.$refs['ecrf3'].getQuestions(this.visitTaskId, true)
          loading.close()
          resolve()
        } catch (e) { console.log(e) }
      })
    },
    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 ''
      }
    },
    // 分裂
    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 refName = `${questionId}_${this.tableQuestions[idx].TableQuestions.Answers[i].RowIndex}`
          // var lesionState = this.$refs[refName][0].getQuestionVal(7)
          // var lesionType = this.$refs[refName][0].lesionType
          // var isCurrentTaskAdd = this.tableQuestions[idx].TableQuestions.Answers[i].IsCurrentTaskAdd
          // if (isNaN(parseInt(lesionState))) {
          //   this.$confirm(`请先为病灶设置状态`, {
          //     type: 'warning',
          //     distinguishCancelAndClose: true
          //   })
          //     .then(() => {})
          //     .catch(() => {})
          // } else if (lesionType === 0 && lesionState !== 0) {
          //   // 靶病灶
          //   this.$confirm(`病灶状态为消失或无法评估或太小，不支持分裂`, {
          //     type: 'warning',
          //     distinguishCancelAndClose: true
          //   })
          //     .then(() => {})
          //     .catch(() => {})
          // } else if (lesionType === 1 && lesionState === 2 || lesionState === 3) {
          //   // 非靶病灶
          //   this.$confirm(`病灶状态为消失或无法评估，不支持分裂`, {
          //     type: 'warning',
          //     distinguishCancelAndClose: true
          //   })
          //     .then(() => {})
          //     .catch(() => {})
          // } else if (lesionType === 2 && (lesionState === 1 || lesionState === 2 || lesionState === 3)) {
          //   // 新病灶
          //   this.$confirm(`病灶状态为疑似或消失或无法评估，不支持分裂`, {
          //     type: 'warning',
          //     distinguishCancelAndClose: true
          //   })
          //     .then(() => {})
          //     .catch(() => {})
          // } else if (isCurrentTaskAdd !== 'False') {
          //   this.$confirm(`首次添加的病灶不支持分裂`, {
          //     type: 'warning',
          //     distinguishCancelAndClose: true
          //   })
          //     .then(() => {})
          //     .catch(() => {})
          // } else {}
          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(() => {})
          }
        }
      }
    },
    async split(rowId, questionId) {
      const loading = this.$loading({ fullscreen: true })
      try {
        var params = {
          visitTaskId: this.visitTaskId,
          questionId: questionId,
          rowId: rowId
        }
        await splitLesion(params)
        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()
            })
          })
        })
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    },
    // 融合
    async handleMerge(answers, questionId, orderMark) {
      this.lesionData = []
      this.mergeList = []
      this.merge.visible = true
      this.mergeInfo.questionId = questionId
      this.mergeInfo.mergeRowId = answers.RowId
      this.mergeInfo.lesionName = this.getLesionName(orderMark, answers.RowIndex)
      this.mergeInfo.lesionPart = answers.lesionPart
      this.merge.loading = true
      try {
        const res = await getCanMergeLesion({ rowId: answers.RowId })
        if (res.IsSuccess) {
          this.lesionData = res.Result
        }
        this.merge.loading = false
      } catch (e) {
        console.log(e)
        this.merge.loading = false
      }
    },
    handleSelectionChange(val) {
      this.mergeList = []
      val.map(i => {
        this.mergeList.push(i.RowId)
      })
    },
    confirmMerge() {
    // '融合后将无法撤销, 是否继续?'
      this.$confirm(this.$t('trials:reading:lugano:warnning:fuse'), {
        type: 'warning'
      }).then(() => {
        this.lesionMerge()
      }).catch(() => {

      })
    },
    async lesionMerge() {
      this.merge.loading = true
      try {
        var params = {
          visitTaskId: this.visitTaskId,
          questionId: this.mergeInfo.questionId,
          mergeMainRowId: this.mergeInfo.mergeRowId,
          mergeRowIdList: this.mergeList
        }
        const res = await mergeLesion(params)
        if (res.IsSuccess) {
          this.merge.visible = false
          DicomEvent.$emit('readingPageUpdate', {})
          DicomEvent.$emit('getReportInfo', true)
          DicomEvent.$emit('setMeasuredToolsPassive')
          this.getReadingQuestionAndAnswer()
        }
        this.merge.loading = false
      } catch (e) {
        this.merge.loading = false
        console.log(e)
      }
    },
    isCanActiveTool(toolName) {
      this.isNonTargetMeasurement = false
      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.MeasureData) {
          return this.checkToolCanActive(toolName)
        } 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.activeItem.activeCollapseId) {
          return this.checkToolCanActive(toolName)
        } else {
          if (this.isBaseLineTask && (toolName === 'Bidirectional' || toolName === 'RectangleRoi' || toolName === 'CircleROI')) {
            return { isCanActiveTool: true, reason: '' }
          } else if (!this.isBaseLineTask && (toolName === 'ArrowAnnotate' || toolName === 'Bidirectional' || toolName === 'RectangleRoi' || toolName === 'CircleROI')) {
            return { isCanActiveTool: true, reason: '' }
          } else if (this.isBaseLineTask && toolName === 'ArrowAnnotate') {
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg54') }
          } else {
            return { isCanActiveTool: false, reason: '' }
          }
        }
      }
    },

    checkToolCanActive(toolName) {
      console.log('checkToolCanActive')
      const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
      var isLymphNodes = this.$refs[refName][0].getQuestionVal(2)
      isLymphNodes = !isNaN(parseInt(isLymphNodes)) ? parseInt(isLymphNodes) : null
      if (!this.$refs[refName][0].questionForm.MeasureData) {
        if (this.isBaseLineTask) {
          if (this.$refs[refName][0].lesionType === 0 && isLymphNodes === 1 && toolName !== 'Bidirectional') {
            // '淋巴结靶病灶需使用长短径测量工具'
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg6') }
          } else if (this.$refs[refName][0].lesionType === 0 && isLymphNodes === 0 && toolName !== 'Bidirectional') {
            // ' 请使用长短径测量工具'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools9') }
          } else if (this.$refs[refName][0].lesionType === 0 && toolName !== 'Bidirectional') {
            // '请使用长短径测量工具'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools9') }
          } else if (this.$refs[refName][0].lesionType === 1 && isLymphNodes === 1 && toolName !== 'Bidirectional' && toolName !== 'RectangleRoi') {
            // '淋巴结非靶病灶需使用长短径测量工具或矩形工具'
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg8') }
          } else if (this.$refs[refName][0].lesionType === 1 && isLymphNodes === 0 && toolName !== 'Bidirectional' && toolName !== 'RectangleRoi') {
            // '请使用长短径测量工具或矩形工具'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools8') }
          } else if (this.$refs[refName][0].lesionType === 1 && toolName !== 'Bidirectional' && toolName !== 'RectangleRoi') {
            // '请使用长短径测量工具或矩形工具'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools8') }
          } else if (toolName === 'ArrowAnnotate') {
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg54') }
          } else if (toolName === 'Length' && !isNaN(parseInt(this.$refs[refName][0].lesionType))) {
            // '请使用长短径测量工具或矩形工具'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools8') }
          } else {
            return { isCanActiveTool: true, reason: '' }
          }
        } else {
          if (this.$refs[refName][0].lesionType === 0 && isLymphNodes === 1 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate') {
            // 请使用长短径测量工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools1') }
          } else if (this.$refs[refName][0].lesionType === 0 && isLymphNodes === 0 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate') {
            // 请使用长短径测量工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools1') }
          } else if (this.$refs[refName][0].lesionType === 0 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate') {
            // 请使用长短径测量工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools1') }
          } else if (this.$refs[refName][0].lesionType === 1 && isLymphNodes === 1 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate' && toolName !== 'RectangleRoi') {
            // 淋巴结非靶病灶需使用长短径测量工具或矩形工具或矩形工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg52') }
          } else if (this.$refs[refName][0].lesionType === 1 && isLymphNodes === 0 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate' && toolName !== 'RectangleRoi') {
            // '请使用长短径测量工具或矩形工具或箭头工具进行淋巴结非靶病灶的标记。'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools2') }
          } else if (this.$refs[refName][0].lesionType === 1 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate' && toolName !== 'RectangleRoi') {
            // 请使用长短径测量工具或矩形工具或箭头工具进行非靶病灶的标记。
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools3') }
          } else if (this.$refs[refName][0].lesionType === 2 && isLymphNodes === 1 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate') {
            // 淋巴结新病灶需使用长短径测量工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg12') }
          } else if (this.$refs[refName][0].lesionType === 2 && isLymphNodes === 0 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate') {
            // '请使用长短径测量工具或箭头工具进行淋巴结非靶病灶的标记。'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools4') }
          } else if (this.$refs[refName][0].lesionType === 2 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate') {
            // '请使用长短径测量工具或箭头工具进行新病灶的标记。'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools5') }
          } else if (toolName === 'Length' && !isNaN(parseInt(this.$refs[refName][0].lesionType))) {
            // '请使用长短径测量工具或矩形工具或箭头工具。'
            return { isCanActiveTool: false, reason: this.$t('trials:lugano:message:validTools6') }
          } else {
            return { isCanActiveTool: true, reason: '' }
          }
        }
      } else {
        if (toolName === 'Bidirectional' || toolName === 'RectangleRoi' || toolName === 'ArrowAnnotate') {
          return { isCanActiveTool: true, reason: '' }
        } else {
          return { isCanActiveTool: false, reason: '' }
        }
      }
    },

    async handleAdd(qs) {
      this.$emit('setToolPassive')
      // 判断是否有未保存的病灶
      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.QuestionName)
        msg = msg.replace('xxx', qs.MaxQuestionCount)
        this.$confirm(msg, {
          type: 'warning',
          showCancelButton: false,
          callback: action => {}
        })
      } else {
        // saveTypeEnum: 0
        var obj = { saveTypeEnum: 0 }
        // var questions = qs.TableQuestions.Questions.find(item => item.QuestionMark === 3)
        // if (questions) {
        //   console.log(questions)
        //   var maxIndex = this.getMaxRowIndex(qs.TableQuestions.Answers)
        //   obj.RowIndex = `${maxIndex + 1}.00`
        //   obj[questions.Id] = `${qs.OrderMark}${String(maxIndex + 1).padStart(2, '0')}`
        // }
        var maxIndex = this.getMaxRowIndex(qs.TableQuestions.Answers)
        obj.RowIndex = `${maxIndex + 1}.00`
        obj.IsDicomReading = true
        await store.dispatch('reading/addReadingQuestionAndAnswer', { lesionType: qs.LesionType, visitTaskId: this.visitTaskId, lesionObj: obj })

        this.activeItem.activeRowIndex = String(obj.RowIndex)
        this.activeItem.activeCollapseId = qs.Id
        this.activeName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
      }
    },
    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() {
      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 splitOrMergeType = this.$refs[refName][0].answers.SplitOrMergeType
            var markTool = splitOrMergeType !== '3' ? this.$refs[refName][0].currentMarkTool : ''
            var readingTaskState = this.readingTaskState
            var isMarked = !!this.$refs[refName][0].questionForm.MeasureData
            DicomEvent.$emit('imageLocation', { questionId: this.activeItem.activeCollapseId, rowIndex: this.activeItem.activeRowIndex, visitTaskId: this.visitTaskId, lesionName: this.$refs[refName][0].lesionMark, lesionType: this.$refs[refName][0].lesionType, markTool, readingTaskState, isMarked })
          }
        })
      } else {
        this.activeItem.activeRowIndex = null
        this.activeItem.activeCollapseId = null
      }
    },
    collapseRightClick(e, obj, activeCollapseId, activeRowIndex) {
      if (obj.IsDicomReading !== false) {
        const refName = `${activeCollapseId}_${activeRowIndex}`
        DicomEvent.$emit('imageLocation', { questionId: activeCollapseId, rowIndex: activeRowIndex, visitTaskId: this.visitTaskId, lesionName: this.$refs[refName][0].lesionMark, lesionType: this.$refs[refName][0].lesionType })
      }
      e.stopImmediatePropagation()
      e.stopPropagation()
      e.preventDefault()
    },
    // 更改病灶类型
    async changeLesionType(questionsObj) {
      await store.dispatch('reading/removeReadingQuestionAndAnswer', { lesionType: questionsObj.oldLesionType, rowIndex: questionsObj.rowIndex, visitTaskId: this.visitTaskId })
      // 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 => {
        // if (i.QuestionMark === 3) {
        //   var maxIndex = this.getMaxRowIndex(targetObj.TableQuestions.Answers)
        //   lesionObj.RowIndex = `${maxIndex + 1}.00`
        //   lesionObj[i.Id] = `${targetObj.OrderMark}${String(maxIndex + 1).padStart(2, '0')}`
        //   lesionMark = lesionObj[i.Id]
        // } else {
        //   var obj = questionObj.find(v => v.QuestionMark === i.QuestionMark)
        //   if (obj) {
        //     lesionObj[i.Id] = obj.Answer
        //   }
        // }
        var obj = questionObj.find(v => v.QuestionMark === i.QuestionMark)
        if (obj) {
          lesionObj[i.Id] = obj.Answer
        }
      })

      // 需要处理2D 和 3D的标记
      if (questionsObj.measureData) {
        await store.dispatch('reading/removeMeasuredData', { visitTaskId: this.visitTaskId, measureData: questionsObj.measureData, questionId: questionsObj.questionId, rowIndex: questionsObj.rowIndex })

        questionsObj.measureData.data.remark = lesionMark
        lesionObj.MeasureData = JSON.stringify(questionsObj.measureData)
      }

      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.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)
        }
        this.$refs[refName][0].setMeasureData(questionsObj.measureData, deleteInfo)
      })
    },
    removeQuestionAnswer(questionsObj) {
      // 移除当前病灶
      var currentObj = this.tableQuestions.find(item => item.LesionType === questionsObj.oldLesionType)
      if (currentObj) {
        var i = currentObj.TableQuestions.Answers.findIndex(i => String(i.RowIndex) === String(questionsObj.rowIndex))
        if (i === -1) return
        currentObj.TableQuestions.Answers.splice(i, 1)
      }
    },
    // 创建新病灶
    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.RowIndex = target.TableQuestions.Answers.length + 1
      // var questions = target.TableQuestions.Questions.find(item => item.QuestionMark === 3)
      // if (questions) {
      //   var maxIndex = this.getMaxRowIndex(target.TableQuestions.Answers)
      //   obj.RowIndex = `${maxIndex + 1}.00`
      //   obj[questions.Id] = `${target.OrderMark}${String(maxIndex + 1).padStart(2, '0')}`
      //   // obj[questions.Id] = `${target.OrderMark}${String(obj.RowIndex).padStart(2, '0')}`
      // }
      // target.TableQuestions.Answers.push(obj)
      obj.IsDicomReading = !(measureData.isDicomReading === false || measureData.isDicomReading === 'False')
      obj.measureObj = measureData
      await store.dispatch('reading/addReadingQuestionAndAnswer', { 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}`
      // const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
      // this.$nextTick(() => {
      //   this.$refs[refName][0].setMeasureData(measureData)
      // })
    },
    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.measureData.data.remark === 'Spleen Top' || measureObj.measureData.data.remark === 'Spleen Bottom') {
        this.$refs['ecrf3'].setMeasuredData(measureObj.measureData)
        this.isNonTargetMeasurement = false
      } else {
        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}`
          this.$refs[refName][0].setMeasureData(measureObj.measureData)
        }
      }
    },
    // 设置测量数据
    setMeasuredData(measureData) {
      if (this.isNonTargetMeasurement || measureData.data.remark === 'Spleen Top' || measureData.data.remark === 'Spleen Bottom') {
        this.$refs['ecrf3'].setMeasuredData(measureData)
        this.isNonTargetMeasurement = false
        return
      }
      if (this.activeItem.activeCollapseId) {
        // 判断是否存在测量数据
        this.$nextTick(() => {
          const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
          if (!this.$refs[refName][0].questionForm.MeasureData || (this.$refs[refName][0].questionForm && this.$refs[refName][0].questionForm.MeasureData && measureData.data.uuid === this.$refs[refName][0].questionForm.MeasureData.data.uuid)) {
            if (!this.$refs[refName][0].questionForm.MeasureData && this.$refs[refName][0].answers.SplitOrMergeType === '3') {
              this.createNLTarget(measureData)
            } else {
              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 === 'Bidirectional')) {
                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 === 'Bidirectional')) {
            this.createTTarget(measureData)
          } else {
            this.createNTTarget(measureData)
          }
        } else {
          this.createNLTarget(measureData)
        }
      }
    },
    setNonTargetMeasurementStatus(obj) {
      this.isNonTargetMeasurement = obj.status
    },
    async close(questionsObj) {
      if (questionsObj) {
        this.getReadingQuestionAndAnswer(questionsObj.visitTaskId)
      }
      this.activeItem.activeRowIndex = null
      this.activeItem.activeCollapseId = null
      this.activeName = ''
    },
    getECRFQuestions(obj) {
      this.$nextTick(() => {
        this.$refs['ecrf'].getQuestions(obj.visitTaskId)
        this.$refs['ecrf2'].getQuestions(obj.visitTaskId)
        this.$refs['ecrf3'].getQuestions(obj.visitTaskId)
      })
    },
    receiveMsg(event) {
      if (event.data.type === 'isCanActiveNoneDicomTool') {
        this.getUnSaveTarget()
        var obj = {}
        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.MeasureData) {
            // 判断是否是靶病灶
            //  questions.findIndex(i => i.QuestionMark === questionMark)
            var lesionType = this.$refs[refName][0].questionForm.LesionType
            if (lesionType === 0) {
              // '当前病灶为靶病灶，不允许添加标记！'
              obj = { isCanActiveTool: false, lesionName: '', reason: this.$t('trials:reading:warnning:msg18') }
            } else {
              obj = { isCanActiveTool: true, lesionName: this.$refs[refName][0].lesionMark, reason: '', toolName: event.data.toolName }
            }
          } else {
            let msg = this.$t('trials:reading:warnning:msg5')
            msg = msg.replace('xxx', this.unSaveTargets[0].lessionName)
            obj = { isCanActiveTool: false, lesionName: '', reason: msg }
          }
        } else {
          if (this.activeItem.activeCollapseId) {
            // 判断是否是靶病灶
            const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
            // obj = { isCanActiveTool: true, lesionName: this.$refs[refName][0].lesionMark, reason: '' }
            const lesionType = this.$refs[refName][0].questionForm.LesionType
            if (lesionType === 0) {
              // 当前病灶为靶病灶，不允许添加标记！
              obj = { isCanActiveTool: false, lesionName: '', reason: this.$t('trials:reading:warnning:msg18') }
            } else {
              obj = { isCanActiveTool: true, lesionName: this.$refs[refName][0].lesionMark, reason: '', toolName: event.data.toolName }
            }
          } else {
            // 获取非靶病灶/新病灶的长度及标识
            var qsObj = null
            var lesionName = ''
            if (this.isBaseLineTask) {
              const idx = this.tableQuestions.findIndex(item => item.LesionType === 1)
              if (idx > -1) {
                qsObj = this.tableQuestions[idx]
              }
            } else {
              const idx = this.tableQuestions.findIndex(item => item.LesionType === 2)
              if (idx > -1) {
                qsObj = this.tableQuestions[idx]
              }
            }

            // var questions = qsObj.TableQuestions.Questions.find(item => item.QuestionMark === 3)
            // if (questions) {
            //   var maxIndex = this.getMaxRowIndex(qsObj.TableQuestions.Answers)
            //   lesionName = `${qsObj.OrderMark}${String(maxIndex + 1).padStart(2, '0')}`
            // }
            var maxIndex = this.getMaxRowIndex(qsObj.TableQuestions.Answers)
            lesionName = `${qsObj.OrderMark}${String(maxIndex + 1).padStart(2, '0')}`
            obj = { isCanActiveTool: true, lesionName: lesionName, reason: '', toolName: event.data.toolName }
          }
        }

        DicomEvent.$emit('isCanActiveNoneDicomTool', obj)
      } else if (event.data.type === 'setMeasurement') {
        this.setMeasuredData(event.data.data)
      } else if (event.data.type === 'petctLesionUpdate') {
        this.refreshQuestions()
      }
    },
    async refreshQuestions() {
      const loading = this.$loading({ fullscreen: true })
      await store.dispatch('reading/refreshMeasuredData', this.visitTaskId)
      await this.getReadingQuestionAndAnswer()
      var triald = this.$router.currentRoute.query.trialId
      await store.dispatch('reading/refreshDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskId })
      this.$nextTick(() => {
        this.$refs['ecrf'].getQuestions(this.visitTaskId)
        this.$refs['ecrf2'].getQuestions(this.visitTaskId)
        this.$refs['ecrf3'].getQuestions(this.visitTaskId)
      })
      DicomEvent.$emit('getReportInfo', true)
      loading.close()
    },
    async resetMeasuredData() {
      const confirm = await this.$confirm(
        this.$t('trials:dicomReading:message:confirmReset1'),
        this.$t('trials:dicomReading:message:confirmReset2'),
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      const loading = this.$loading({ fullscreen: true })
      try {
        const res = await resetReadingTask({ visitTaskId: this.visitTaskId })
        if (res.IsSuccess) {
          // 刷新标注、表单、报告页信息、融合页表单及标注
          this.activeName = ''
          this.activeItem.activeRowIndex = null
          this.activeItem.activeCollapseId = null
          await this.getReadingQuestionAndAnswer(this.visitTaskId)
          const triald = this.$router.currentRoute.query.trialId
          await store.dispatch('reading/refreshDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskId })
          this.$refs['ecrf'].getQuestions(this.visitTaskId, true)
          this.$refs['ecrf2'].getQuestions(this.visitTaskId, true)
          this.$refs['ecrf3'].getQuestions(this.visitTaskId, true)
          DicomEvent.$emit('getMeasureData')
          DicomEvent.$emit('getReportInfo', true)
          DicomEvent.$emit('refreshStudyListMeasureData')
          DicomEvent.$emit('resetPage', {})
        }
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.measurement-wrapper{
  height: 100%;
  overflow-y: auto;
  .container{
    padding: 10px;
    .basic-info{
      display: flex;
      justify-content: space-between;
      align-items: center;
      h3{
        color: #ddd;
        padding: 5px 0px;
        margin: 0;
      }
      i{
        color: #fff;
        font-size: 22px;
        font-weight: bold;
        cursor: pointer;
      }
    }
  }
  .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;
  }
  .login-cycle{
    width: 5px;
    height: 5px;
    display: inline-block;
    background-color: #428bca;
    border-radius: 50%;
    margin-right: 2px;
    margin-bottom: 2px;
  }
  .el-collapse{
    border-bottom:none;
    border-top:none;
    ::v-deep .el-collapse-item{
      background-color: #000!important;
      color: #ddd;

    }
    ::v-deep .el-collapse-item__header{
      background-color: #000!important;
      color: #ddd;
      border-bottom-color:#5a5a5a;
      padding-left: 5px;
      height: 35px;
      line-height: 35px;
    }
    ::v-deep .el-collapse-item__wrap{
      background-color: #000!important;
      color: #ddd;
    }
    ::v-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;
    }

  }
  .merge-table{
    padding:0 10px;
    ::v-deep.el-table{
      background-color:  #1e1e1e !important;
      color: #383838;
    }
    ::v-deep.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf{
      border-bottom: 1px solid #383838;
    }
    .el-table--border::after, .el-table--group::after, .el-table::before{
      background-color: #1e1e1e;
    }
    ::v-deep.el-table__header-wrapper{
        th{
          background-color:  #1e1e1e !important;
          color: #dfdfdf;
          border-bottom: 1px solid #383838;
        }
      }
    ::v-deep.el-table__body-wrapper{
      tr{
        background-color:  #1e1e1e !important;
        color: #dfdfdf;
      }
      tr:hover > td{
        background-color:  #1e1e1e !important;
      }
    }
    ::v-deep.el-table__empty-block{
      background-color:  #1e1e1e !important;
    }
    .merge-label{
      color:#ddd;
      font-size: 13px;
      margin-bottom: 10px;
      span{
        font-size: 15px;
        color: red;
      }
    }
  }
}
</style>
