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

    <div class="container">
      <div class="basic-info">
        <h3 v-if="taskInfo && taskInfo.IsReadingShowSubjectInfo">
          <span v-if="visitInfo.SubjectCode">{{ visitInfo.SubjectCode }} </span>
          <span style="margin-left:5px;">{{ visitInfo.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="resetForm" />
          </el-tooltip>
        </div>
      </div>

      <!-- 影像质量评估 -->
      <div v-if="outerQuestions.length > 0" class="outer_form_wrapper">
        <el-form ref="outerForm" size="small" :model="outerForm">
          <question-form-item v-for="outerQs in outerQuestions" :key="outerQs.Id" :question="outerQs"
            :question-form="outerForm" :reading-task-state="readingTaskState" :visit-task-id="visitTaskId"
            @resetFormItemData="resetOuterFormItemData" @setFormItemData="setOuterFormItemData"
            @handleReadingChart="handleReadingChart" />
          <el-form-item v-if="readingTaskState < 2">
            <div class="outer_form-footer">
              <i class="el-icon-warning feedback-icon"
                :style="{ color: taskInfo && taskInfo.IsExistUnprocessedFeedback ? '#ffeb3b' : '#fff' }"
                @click="openFeedBackTable" />
              <el-button size="mini" :loading="outerSaveLoading" :disabled="outerSaveLoading" @click="saveOuterForm">{{ $t('common:button:save') }}</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- 病灶评估 -->
      <template v-if="tableQuestions.length > 0 && criterionType !== 10">
        <div v-for="(qs, index) in tableQuestions" :key="index" 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="table in qs.Childrens" v-show="!(isBaseLineTask && table.LesionType === 2)" :key="table.Id">
              <div v-if="table.Type === 'table'" class="flex-row" style="margin:3px 0;">
                <div class="title">{{ table.QuestionName }}
                  <svg-icon v-if="table.LesionType === 0" icon-class="readingChart"
                    class="svg-icon svg-readingChart-mini" @click.stop="(e) => handleReadingChart({
                      e,
                      data: {
                        ReportChartTypeEnum: 0,
                        QuestionName: table.QuestionName
                      },
                    })" />
                </div>
                <div v-if="readingTaskState < 2 && (isBaseLineTask || table.LesionType === 2)" class="add-icon"
                  @click.prevent="addTarget(table)">
                  <i class="el-icon-plus" />
                </div>
              </div>
              <el-collapse v-if="table.Type === 'table' && table.TableQuestions" v-model="activeName" accordion
                @change="handleCollapseChange">
                <el-collapse-item v-for="(answer, i) in table.TableQuestions.Answers"
                  :key="`${table.Id}_${answer.RowIndex}`" :name="`${table.Id}_${answer.RowIndex}`"
                  @contextmenu.prevent.native="collapseRightClick($event, table.Id, answer.RowIndex)">
                  <template slot="title">
                    <div style="width:340px;position: relative;"
                      :style="{ color: (activeName === table.Id + answer.RowIndex ? '#ffeb3b' : '#fff') }">
                      {{ getLesionName(table.OrderMark, answer.RowIndex) }}
                      <!-- 未保存 -->
                      <el-tooltip
                        v-if="readingTaskState < 2 && parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].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(innerFormData[`${table.Id}_${answer.RowIndex}`].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: table.LesionType === 1 && readingTaskState < 2 ? '58px' : '50px', top: '2px' }">
                        <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="innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeType === '1' || innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeType === '3'"
                            class="item" effect="dark"
                            :content="`${$t('trials:reading:message:fused')}${innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeLesionName}`"
                            placement="bottom">
                            <div
                              v-if="innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeType === '1' || innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeType === '3'">
                              <span class="login-cycle"
                                :style="`background-color:${$GuidToColor(innerFormData[`${table.Id}_${answer.RowIndex}`].MergeRowId)}`" />
                            </div>
                          </el-tooltip>
                          <div v-if="innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeType === '4'">
                            <span class="login-cycle"
                              :style="`background-color:${$GuidToColor(innerFormData[`${table.Id}_${answer.RowIndex}`].RowId)}`" />
                          </div>
                          <div style="font-size: 11px;width:220px;height: 30px;">
                            <div v-if="innerFormData[`${table.Id}_${answer.RowIndex}`].LesionPart"
                              style="margin-left:10px;display: inline-block; white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width:90px"
                              :title="innerFormData[`${table.Id}_${answer.RowIndex}`].LesionPart">
                              {{ innerFormData[`${table.Id}_${answer.RowIndex}`].LesionPart }}
                            </div>
                            <div
                              style="display: inline-block;margin-left:5px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width:50px">
                              <span v-if="table.LesionType === 0">
                                {{
                                  $fd('TargetState',
                                    parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].LesionState))
                                }}
                              </span>
                              <span v-else-if="table.LesionType === 1">
                                {{
                                  $fd('NoTargetState',
                                    parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].LesionState))
                                }}
                              </span>
                              <span v-else>
                                {{
                                  $fd('NewLesionState',
                                    parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].LesionState))
                                }}
                              </span>
                            </div>
                            <div
                              style="display: inline-block;margin-left:5px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;max-width:60px">
                              <template
                                v-if="innerFormData[`${table.Id}_${answer.RowIndex}`].IsLymphNodes && !isNaN(parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].LesionShort))">
                                {{ innerFormData[`${table.Id}_${answer.RowIndex}`].LesionShort }}mm
                              </template>
                              <template
                                v-else-if="!innerFormData[`${table.Id}_${answer.RowIndex}`].IsLymphNodes && !isNaN(parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].LesionLength))">
                                {{ innerFormData[`${table.Id}_${answer.RowIndex}`].LesionLength }}mm
                              </template>
                            </div>
                          </div>
                        </div>

                      </div>
                      <!-- 分裂 -->
                      <div
                        v-if="((table.LesionType === 0 && [0, 1, 4].includes(parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].LesionState))) || (table.LesionType === 0 && parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].LesionState) === 0) || (table.LesionType === 1 && [0, 1].includes(parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].LesionState))) || (table.LesionType === 2 && parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].LesionState) === 0)) && innerFormData[`${table.Id}_${answer.RowIndex}`].IsCurrentTaskAdd === 'False'"
                        style="position: absolute;right: 5px;top: 2px;">
                        <el-tooltip
                          v-show="readingTaskState < 2 && innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeType !== '4' && !!innerFormData[`${table.Id}_${answer.RowIndex}`].RowId && !isBaseLineTask && innerFormData[`${table.Id}_${answer.RowIndex}`].IsDicomReading !== false"
                          class="table" :content="$t('trials:reading:button:split')" placement="left">
                          <i class="iconfont icon-24gl-split" style="color:#fff;font-size: 16px;"
                            @click.stop="lesionSplit(table.Id, innerFormData[`${table.Id}_${answer.RowIndex}`].RowId)" />
                        </el-tooltip>
                        <!-- 融合 -->
                        <el-tooltip
                          v-show="readingTaskState < 2 && !isBaseLineTask && !!innerFormData[`${table.Id}_${answer.RowIndex}`].RowId && innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeType !== '2' && table.LesionType === 0 && [0, 1, 4].includes(parseInt(innerFormData[`${table.Id}_${answer.RowIndex}`].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(innerFormData[`${table.Id}_${answer.RowIndex}`], table.Id, table.OrderMark)" />
                        </el-tooltip>
                      </div>

                    </div>

                  </template>
                  <el-form :ref="`${table.Id}_${answer.RowIndex}`" size="small"
                    :model="innerFormData[`${table.Id}_${answer.RowIndex}`]">
                    <table-question-form-item :ref="`form_${table.Id}_${answer.RowIndex}`" :table-info="table"
                      :answer="answer" :question-form="innerFormData[`${table.Id}_${answer.RowIndex}`]"
                      :reading-task-state="readingTaskState" :organs="organs" :is-base-line-task="isBaseLineTask"
                      :is-current-task="isCurrentTask" @update="innerFormDataUpdate" @close="closeInnerForm"
                      @lesionTypeChange="lesionTypeChange" @handleReadingChart="handleReadingChart" />
                    <div
                      v-if="readingTaskState < 2 && innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeType !== '1' && innerFormData[`${table.Id}_${answer.RowIndex}`].SplitOrMergeType !== '3'"
                      style="text-align:right;margin-top:10px;">
                      <!-- 清除标记 -->
                      <el-button v-if="innerFormData[`${table.Id}_${answer.RowIndex}`].MeasureData" size="mini"
                        @click="clearMeasureData(table, answer.RowIndex)">
                        {{ $t('trials:reading:button:removeMark') }}
                      </el-button>
                      <!-- 删除 -->
                      <el-button v-if="table.TableQuestions.Answers[i].IsCurrentTaskAdd !== 'False'" size="mini"
                        @click="deleteLesion(table, answer.RowIndex)">
                        {{ $t('common:button:delete') }}
                      </el-button>
                      <!-- 保存 -->
                      <el-button size="mini" :loading="!!rowSaveLoadingMap[`${table.Id}_${answer.RowIndex}`]"
                        :disabled="!!rowSaveLoadingMap[`${table.Id}_${answer.RowIndex}`]" @click="saveLesion(table, answer.RowIndex)">
                        {{ $t('common:button:save') }}
                      </el-button>
                    </div>
                  </el-form>
                </el-collapse-item>

              </el-collapse>
            </div>
          </div>
        </div>
      </template>
    </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 {
  getDicomReadingQuestionAnswer,
  getReadingQuestionAndAnswer,
  getReadingOrganList,
  saveTaskQuestion,
  submitTableQuestion,
  deleteReadingRowAnswer,
  splitLesion,
  getCanMergeLesion,
  mergeLesion
} from '@/api/trials'
import { resetReadingTask, setSkipReadingCache } from '@/api/reading'
import { mapGetters } from 'vuex'
import QuestionFormItem from './QuestionFormItem'
import TableQuestionFormItem from './TableQuestionFormItem'
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
export default {
  name: 'QuestionList',
  components: {
    QuestionFormItem,
    TableQuestionFormItem
  },
  props: {
    readingTaskState: {
      type: Number,
      required: true
    },
    lastViewportTaskId: {
      type: String,
      required: true
    },
    visitInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      isBaseLineTask: false,
      isCurrentTask: false,
      criterionType: null,
      taskInfo: null,
      outerQuestions: [],
      outerForm: {},
      tableQuestions: [],
      trialId: '',
      visitTaskId: '',
      loading: false,
      activeName: '',
      innerFormData: {},
      organs: [],
      deleteTargetInfo: null,
      digitPlaces: 2,
      imageQualityId: '',
      imageQualityIssuesId: '',
      outerSaveLoading: false,
      rowSaveLoadingMap: {},
      validationDialogVisible: false,


      merge: { visible: false, loading: false },
      lesionData: [],
      mergeInfo: {},
      mergeList: []
    }
  },
  computed: {
    ...mapGetters(['language'])
  },
  watch: {
    // lastViewportTaskId: {
    //   immediate: true,
    //   handler(id) {
    //     if (!id) return
    //     this.visitTaskId = id
    //     this.$nextTick(() => {
    //       this.activeName = ''
    //       this.getOuterQuestions()
    //       this.getTableQuestions()
    //     })
    //   }
    // }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.visitTaskId = this.visitInfo.VisitTaskId
    this.taskInfo = JSON.parse(sessionStorage.getItem('taskInfo'))
    this.isBaseLineTask = this.taskInfo.IsBaseLine
    this.criterionType = this.taskInfo.CriterionType
    const digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.getOrganList()
    this.getOuterQuestions()
    this.getTableQuestions()
    window.addEventListener('message', this.receiveMsg)
  },
  methods: {
    handleReadingChart(e) {
      this.$emit('handleReadingChart', e)
    },
    async showValidationDialog(msg) {
      if (this.validationDialogVisible) {
        return false
      }
      this.validationDialogVisible = true
      try {
        await this.$confirm(msg, {
          type: 'warning',
          showCancelButton: false,
          closeOnClickModal: false,
          closeOnPressEscape: false
        })
      } catch (e) {
      } finally {
        this.validationDialogVisible = false
      }
      return false
    },
    // 融合
    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('setReadingToolPassive')
          this.getTableQuestions()
        }
        this.merge.loading = false
      } catch (e) {
        this.merge.loading = false
        console.log(e)
      }
    },
    // 获取器官信息
    async getOrganList() {
      try {
        const params = {
          visitTaskId: this.visitTaskId
        }
        const res = await getReadingOrganList(params)
        if (res.IsSuccess) {
          this.organs = res.Result
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取外层问题
    async getOuterQuestions() {
      const loading = this.$loading({ fullscreen: true })
      try {
        const params = {
          trialId: this.$route.query.trialId,
          visitTaskId: this.visitTaskId
        }
        const res = await getDicomReadingQuestionAnswer(params)
        if (res.IsSuccess) {
          this.outerQuestions = res.Result
          this.outerForm = this.getOuterFormData(this.outerQuestions)
        }
        loading.close()
      } catch (e) {
        console.log(e)
        loading.close()
      }
    },
    // 初始化外层问题表单
    getOuterFormData(childrens, formData = {}) {
      childrens.forEach(item => {
        if (item.Type !== 'group' && item.Type !== 'summary') {
          formData[item.Id] = item.Answer ? item.OptionTypeEnum === 1 ? JSON.parse(item.Answer) : item.Answer : ''
          if (item.QuestionType === 44) {
            // 影像质量评估
            this.imageQualityId = item.Id
          }
          if (item.QuestionType === 67) {
            // 影像质量问题
            this.imageQualityIssuesId = item.Id
          }
          if (item.Childrens?.length) {
            this.getOuterFormData(item.Childrens, formData)
          }
        } else {
          this.getOuterFormData(item.Childrens, formData)
        }
      })
      return formData
    },
    resetOuterFormItemData(v) {
      this.$set(this.outerForm, v, null)
    },
    setOuterFormItemData(obj) {

    },
    // 获取表格问题
    async getTableQuestions() {
      this.isCurrentTask = this.taskInfo.VisitTaskId === this.visitTaskId
      const loading = this.$loading({ fullscreen: true })
      try {
        const params = {
          trialId: this.$route.query.trialId,
          visitTaskId: this.visitTaskId
        }
        const res = await getReadingQuestionAndAnswer(params)
        if (res.IsSuccess) {
          this.tableQuestions = res.Result.SinglePage
          this.innerFormData = {}
          res.Result.SinglePage.forEach(group => {
            group.Childrens.forEach(table => {
              const tableKey = table.Id
              this.$set(this.innerFormData, tableKey, {})
              table.TableQuestions.Questions.forEach(question => {
                if (question.Type !== 'summary') {
                  this.$set(this.innerFormData[tableKey], question.Id, null)
                }
              })
              this.$set(this.innerFormData[tableKey], 'RowId', '00000000-0000-0000-0000-000000000000')
              this.$set(this.innerFormData[tableKey], 'LesionLength', null)
              this.$set(this.innerFormData[tableKey], 'LesionShort', null)
              this.$set(this.innerFormData[tableKey], 'IsLymphNodes', null)
              this.$set(this.innerFormData[tableKey], 'LesionState', null)
              this.$set(this.innerFormData[tableKey], 'LesionPart', null)
              this.$set(this.innerFormData[tableKey], 'LesionOrgan', null)
              this.$set(this.innerFormData[tableKey], 'LesionName', null)
              this.$set(this.innerFormData[tableKey], 'MeasureData', null)
              this.$set(this.innerFormData[tableKey], 'TableId', tableKey)
              this.$set(this.innerFormData[tableKey], 'IsCurrentTaskAdd', 'True')

              // QuestionMark：0--长径；1--短径；2--是否淋巴结；5--所在器官；7--状态；8--所在部位；
              const lengthId = this.getQuestionId(0, table.TableQuestions.Questions)
              const shortId = this.getQuestionId(1, table.TableQuestions.Questions)
              const lymphNodesId = this.getQuestionId(2, table.TableQuestions.Questions)
              const organId = this.getQuestionId(5, table.TableQuestions.Questions)
              const stateId = this.getQuestionId(7, table.TableQuestions.Questions)
              const partId = this.getQuestionId(8, table.TableQuestions.Questions)
              table.TableQuestions.Answers.forEach((answer, index) => {
                this.$set(this.innerFormData, `${tableKey}_${answer.RowIndex}`, {})
                this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'LesionName', this.getLesionName(table.OrderMark, answer.RowIndex))
                for (const key in answer) {
                  let val = answer[key]
                  if (key === 'MeasureData' && val) {
                    val = JSON.parse(val)
                  } else if (key === 'LesionType' || key === lymphNodesId || key === stateId) {
                    val = isNaN(parseInt(val)) ? null : parseInt(val)
                  } else if (key === 'IsCanEditPosition') {
                    val = val === 'True'
                  }
                  this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], key, val)
                  if (key === lengthId) {
                    this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'LesionLength', val)
                  } else if (key === shortId) {
                    this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'LesionShort', val)
                  } else if (key === lymphNodesId) {
                    this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'IsLymphNodes', val)
                  } else if (key === stateId) {
                    this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'LesionState', val)
                    this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'SaveTypeEnum', isNaN(parseInt(val)) ? 1 : 2)
                  } else if (key === partId) {
                    this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'LesionPart', val)
                  } else if (key === organId) {
                    this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'LesionOrgan', val)
                  }
                }
                this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'TableId', tableKey)
                this.$set(this.innerFormData[`${tableKey}_${answer.RowIndex}`], 'RowIndex', answer.RowIndex)
              })
            })
          })
        }
        loading.close()
      } catch (e) {
        console.log(e)
        loading.close()
      }
    },
    // 保存外层问题表单
    async saveOuterForm() {
      if (this.outerSaveLoading) return
      this.outerSaveLoading = true
      let loading = null
      try {
        const valid = await this.$refs['outerForm'].validate()
        if (!valid) return
        loading = this.$loading({ fullscreen: true })
        const answers = []
        let imageQuality = null
        for (const k in this.outerForm) {
          answers.push({ id: k, answer: this.outerForm[k] })
          if (k === this.imageQualityId) {
            imageQuality = this.outerForm[k]
          }
        }
        const params = {
          visitTaskId: this.visitTaskId,
          answers: answers

        }
        const res = await saveTaskQuestion(0, params)
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          if (!this.isBaseLineTask) {
            if (parseInt(imageQuality) === 2) {
              this.$confirm(this.$t('trials:reading:warnning:unableEvaluate'), '', {
                type: 'warning'
              }).then(() => {
                this.changeLesionState()
              }).catch(() => {

              })
            }
          }
        }
        loading.close()
      } catch (e) {
        console.log(e)
      } finally {
        if (loading) loading.close()
        this.outerSaveLoading = false
      }
    },
    setAnnotation(obj) {
      const annotation = Object.assign({}, !Object.hasOwn(obj, 'isDicomReading') ? obj.annotation : obj)
      if (this.activeName) {
        // 判断当前激活的病灶是否有标注信息
        const tableId = this.activeName.split('_')[0]
        const rowIndex = this.activeName.split('_')[1]
        const innerForm = this.innerFormData[`${tableId}_${rowIndex}`]
        if (innerForm.MeasureData) {
          if (this.isBaseLineTask) {
            const targetTable = this.tableQuestions[0].Childrens.find(
              child => child.LesionType === 0
            )
            if (typeof targetTable !== 'object') return
            if (targetTable.MaxQuestionCount && targetTable.TableQuestions.Answers.length < targetTable.MaxQuestionCount && (obj.toolName === 'Length' || obj.toolName === 'Bidirectional')) {
              this.createTTarget(annotation)
            } else {
              this.createNTTarget(annotation)
            }
          } else {
            this.createNLTarget(annotation)
          }
        } else {
          const targetTable = this.tableQuestions[0].Childrens.find(
            child => child.Id === tableId
          )
          if (typeof targetTable !== 'object') return
          if (Object.hasOwn(annotation, 'isDicomReading') && !annotation.isDicomReading) {
            // 非dicom获取名称进行重绘
            annotation.data.remark = innerForm.LesionName
            annotation.markTool = annotation.data.toolName
            DicomEvent.$emit('addNoneDicomMeasureData', annotation)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'IsDicomReading', false)
          }
          this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'MeasureData', annotation)
          let length = null
          let short = null
          if (obj.toolName === 'Length') {
            const referencedImageId = annotation.metadata.referencedImageId
            length = annotation.data.cachedStats[`imageId:${referencedImageId}`].length
            length = length ? parseFloat(length).toFixed(this.digitPlaces) : length
            const lengthId = this.getQuestionId(0, targetTable.TableQuestions.Questions)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionLength', length)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], lengthId, length)
          } else if (obj.toolName === 'Bidirectional') {
            const referencedImageId = annotation.metadata.referencedImageId
            length = annotation.data.cachedStats[`imageId:${referencedImageId}`].length
            length = length ? parseFloat(length).toFixed(this.digitPlaces) : length
            const lengthId = this.getQuestionId(0, targetTable.TableQuestions.Questions)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionLength', length)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], lengthId, length)

            short = annotation.data.cachedStats[`imageId:${referencedImageId}`].width
            short = short ? parseFloat(short).toFixed(this.digitPlaces) : short
            const shortId = this.getQuestionId(1, targetTable.TableQuestions.Questions)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionShort', short)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], shortId, short)
          }
          const stateId = this.getQuestionId(7, targetTable.TableQuestions.Questions)
          const state = this.innerFormData[`${tableId}_${rowIndex}`][stateId]
          // 基线时，默认状态都为存在
          if (this.isBaseLineTask && !state) {
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionState', 0)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], stateId, 0)
          }
          if (!(innerForm.IsCurrentTaskAdd === 'True')) {
            // 非基线时，非淋巴结病灶长径>=10mm，自动给“存在”状态，如果淋巴结病灶短径>=10mm，自动给“存在”状态。
            if (!this.isBaseLineTask && ((obj.toolName === 'Length' && length >= 10) || (obj.toolName === 'Bidirectional' && short >= 10))) {
              this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionState', 0)
              this.$set(this.innerFormData[`${tableId}_${rowIndex}`], stateId, 0)
            }
            // 非基线时，非淋巴结病灶长径<10mm，自动给“存在”状态，如果淋巴结病灶短径<10mm，自动给“消失”状态。
            if (!this.isBaseLineTask && ((obj.toolName === 'Length' && length < 10) || (obj.toolName === 'Bidirectional' && short < 10))) {
              const stateId = this.getQuestionId(7, targetTable.TableQuestions.Questions)
              if (innerForm.IsLymphNodes) {
                this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionState', 3)
                this.$set(this.innerFormData[`${tableId}_${rowIndex}`], stateId, 3)
              } else if (innerForm.IsLymphNodes === 0) {
                this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionState', 0)
                this.$set(this.innerFormData[`${tableId}_${rowIndex}`], stateId, 0)
              }
            }
          }
          this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'SaveTypeEnum', innerForm.RowId ? 1 : 0)
          this.setMarkName(this.innerFormData[`${tableId}_${rowIndex}`].LesionType, this.innerFormData[`${tableId}_${rowIndex}`][stateId], this.innerFormData[`${tableId}_${rowIndex}`].LesionName, annotation)

        }
      } else {
        if (this.isBaseLineTask) {
          const targetTable = this.tableQuestions[0].Childrens.find(
            child => child.LesionType === 0
          )
          if (typeof targetTable !== 'object') return
          if (targetTable.MaxQuestionCount && targetTable.TableQuestions.Answers.length < targetTable.MaxQuestionCount && (obj.toolName === 'Length' || obj.toolName === 'Bidirectional')) {
            this.createTTarget(annotation)
          } else {
            this.createNTTarget(annotation)
          }
        } else {
          this.createNLTarget(annotation)
        }
      }
    },
    modifyAnnotation(obj) {
      const { annotation, toolName } = obj
      const formData = Object.values(this.innerFormData).find(
        i => i.LesionName === annotation.data.label
      )
      if (typeof formData !== 'object') return
      const tableId = formData.TableId
      const rowIndex = formData.RowIndex
      const targetTable = this.tableQuestions[0].Childrens.find(
        child => child.Id === formData.TableId
      )
      if (typeof targetTable !== 'object') return
      this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'MeasureData', annotation)
      let length = null
      let short = null
      if (toolName === 'Length') {
        const referencedImageId = annotation.metadata.referencedImageId
        length = annotation.data.cachedStats[`imageId:${referencedImageId}`].length
        length = length ? parseFloat(length).toFixed(this.digitPlaces) : length
        const lengthId = this.getQuestionId(0, targetTable.TableQuestions.Questions)
        this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionLength', length)
        this.$set(this.innerFormData[`${tableId}_${rowIndex}`], lengthId, length)
      } else if (toolName === 'Bidirectional') {
        const referencedImageId = annotation.metadata.referencedImageId
        length = annotation.data.cachedStats[`imageId:${referencedImageId}`].length
        length = length ? parseFloat(length).toFixed(this.digitPlaces) : length
        const lengthId = this.getQuestionId(0, targetTable.TableQuestions.Questions)
        this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionLength', length)
        this.$set(this.innerFormData[`${tableId}_${rowIndex}`], lengthId, length)

        short = annotation.data.cachedStats[`imageId:${referencedImageId}`].width
        short = short ? parseFloat(short).toFixed(this.digitPlaces) : short
        const shortId = this.getQuestionId(1, targetTable.TableQuestions.Questions)
        this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionShort', short)
        this.$set(this.innerFormData[`${tableId}_${rowIndex}`], shortId, short)
      }
      const stateId = this.getQuestionId(7, targetTable.TableQuestions.Questions)
      const state = this.innerFormData[`${tableId}_${rowIndex}`][stateId]
      // 基线时，默认状态都为存在
      if (this.isBaseLineTask && !state) {
        this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionState', 0)
        this.$set(this.innerFormData[`${tableId}_${rowIndex}`], stateId, 0)
      }
      const isCurrentTaskAdd = this.innerFormData[`${tableId}_${rowIndex}`].IsCurrentTaskAdd
      const isLymphNodes = this.innerFormData[`${tableId}_${rowIndex}`].IsLymphNodes
      if (!(isCurrentTaskAdd === 'True')) {
        // 非基线时，非淋巴结病灶长径>=10mm，自动给“存在”状态，如果淋巴结病灶短径>=10mm，自动给“存在”状态。
        if (!this.isBaseLineTask && ((toolName === 'Length' && length >= 10) || (toolName === 'Bidirectional' && short >= 10))) {
          this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionState', 0)
          this.$set(this.innerFormData[`${tableId}_${rowIndex}`], stateId, 0)
        }
        // 非基线时，非淋巴结病灶长径<10mm，自动给“存在”状态，如果淋巴结病灶短径<10mm，自动给“消失”状态。
        if (!this.isBaseLineTask && ((toolName === 'Length' && length < 10) || (toolName === 'Bidirectional' && short < 10))) {
          const stateId = this.getQuestionId(7, targetTable.TableQuestions.Questions)
          if (isLymphNodes) {
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionState', 3)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], stateId, 3)
          } else if (isLymphNodes === 0) {
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'LesionState', 0)
            this.$set(this.innerFormData[`${tableId}_${rowIndex}`], stateId, 0)
          }
        }
      }
      this.setMarkName(this.innerFormData[`${tableId}_${rowIndex}`].LesionType, this.innerFormData[`${tableId}_${rowIndex}`][stateId], this.innerFormData[`${tableId}_${rowIndex}`].LesionName, annotation)
      this.$set(this.innerFormData[`${tableId}_${rowIndex}`], 'SaveTypeEnum', formData.RowId ? 1 : 0)
      this.activeName = `${tableId}_${rowIndex}`
    },
    setMarkName(lesionType, lesionState, lesionName, annotation) {
      let status = ''
      if (lesionType === 0 && lesionState === 1) {
        status = 'T'
      }
      if ((lesionType === 0 && lesionState === 3) || (lesionType === 1 && lesionState === 3) || (lesionType === 2 && lesionState === 3)) {
        status = 'D'
      }
      this.$emit('setMarkName', {
        annotationUID: annotation.annotationUID,
        name: lesionName,
        status
      })
    },
    // 新增病灶
    addTarget(tableInfo, annotation) {
      // 判断是否存在未保存的病灶，否则不允许添加
      const obj = Object.values(this.innerFormData).find(
        obj => !obj.RowId
      )
      if (obj !== undefined && typeof obj === 'object') {
        let msg = this.$t('trials:reading:warnning:msg5')
        msg = msg.replace('xxx', obj.LesionName)

        this.$confirm(msg, {
          type: 'warning',
          showCancelButton: false,
          callback: action => { }
        })
        return
      }
      // 判断当前病灶类型下的病灶个数是否超过最大行数，否则不允许添加
      if (!!tableInfo.MaxQuestionCount && tableInfo.MaxQuestionCount <= tableInfo.TableQuestions.Answers.length) {
        let msg = this.$t('trials:reading:warnning:msg14')
        msg = msg.replace('xxx', tableInfo.MaxQuestionCount)
        this.$confirm(msg, {
          type: 'warning',
          showCancelButton: false,
          callback: action => { }
        })
        return
      }
      const answer = Object.assign({}, this.innerFormData[tableInfo.Id])
      answer.TableId = tableInfo.Id
      answer.RowId = ''
      const maxIndex = this.getMaxRowIndex(tableInfo.TableQuestions.Answers)
      answer.RowIndex = `${maxIndex + 1}.00`
      answer.IsDicomReading = annotation && Object.hasOwn(annotation, 'isDicomReading') ? annotation.isDicomReading : true
      answer.SaveTypeEnum = 0
      answer.LesionType = tableInfo.LesionType
      answer.LesionName = this.getLesionName(tableInfo.OrderMark, answer.RowIndex)
      if (!answer.IsDicomReading) {
        // 非dicom获取名称进行重绘
        annotation.data.remark = answer.LesionName
        annotation.markTool = annotation.data.toolName
        DicomEvent.$emit('addNoneDicomMeasureData', annotation)
      }
      let state = null
      if (this.isBaseLineTask && tableInfo.LesionType === 0) {
        state = 0
      }
      if (this.isBaseLineTask && tableInfo.LesionType === 1) {
        state = 0
      }
      const stateId = this.getQuestionId(7, tableInfo.TableQuestions.Questions)
      answer[stateId] = state
      answer.LesionState = state
      tableInfo.TableQuestions.Answers.push(answer)
      if (typeof annotation === 'object') {
        answer.MeasureData = annotation
        if (annotation.metadata?.toolName === 'Length') {
          const referencedImageId = annotation.metadata.referencedImageId
          let length = annotation.data.cachedStats[`imageId:${referencedImageId}`].length
          length = length ? parseFloat(length).toFixed(this.digitPlaces) : length
          const lengthId = this.getQuestionId(0, tableInfo.TableQuestions.Questions)
          answer.LesionLength = length
          answer[lengthId] = length
        } else if (annotation.metadata?.toolName === 'Bidirectional') {
          const referencedImageId = annotation.metadata.referencedImageId
          let length = annotation.data.cachedStats[`imageId:${referencedImageId}`].length
          length = length ? parseFloat(length).toFixed(this.digitPlaces) : length
          const lengthId = this.getQuestionId(0, tableInfo.TableQuestions.Questions)
          answer.LesionLength = length
          answer[lengthId] = length

          let short = annotation.data.cachedStats[`imageId:${referencedImageId}`].width
          short = short ? parseFloat(short).toFixed(this.digitPlaces) : short
          const shortId = this.getQuestionId(1, tableInfo.TableQuestions.Questions)
          answer.LesionShort = short
          answer[shortId] = short
        }
        this.$emit('setMarkName', {
          annotationUID: annotation.annotationUID,
          name: answer.LesionName
        }
        )
      }
      this.$set(this.innerFormData, `${tableInfo.Id}_${answer.RowIndex}`, {})
      for (const key in answer) {
        this.$set(this.innerFormData[`${tableInfo.Id}_${answer.RowIndex}`], key, answer[key])
      }
      // this.innerFormData[`${tableInfo.Id}_${answer.RowIndex}`] = answer
      this.activeName = `${tableInfo.Id}_${answer.RowIndex}`
    },
    // 创建靶病灶
    createTTarget(annotation) {
      // 靶病灶
      const targetTable = this.tableQuestions[0].Childrens.find(
        child => child.LesionType === 0
      )
      this.addTarget(targetTable, annotation)
    },
    // 创建非靶病灶
    createNTTarget(annotation) {
      // 非靶病灶
      const targetTable = this.tableQuestions[0].Childrens.find(
        child => child.LesionType === 1
      )
      this.addTarget(targetTable, annotation)
    },
    // 创建新病灶
    createNLTarget(annotation) {
      // 新病灶
      const targetTable = this.tableQuestions[0].Childrens.find(
        child => child.LesionType === 2
      )
      this.addTarget(targetTable, annotation)
    },
    // 清除标注
    async clearMeasureData(table, rowIndex) {
      //  是否确认清除标记？
      const confirm = await this.$confirm(
        this.$t('trials:reading:warnning:msg47'),
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      const innerForm = this.innerFormData[`${table.Id}_${rowIndex}`]
      // 重置长短径 和 状态
      const lengthId = this.getQuestionId(0, table.TableQuestions.Questions)
      this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], lengthId, null)
      this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'LesionLength', null)
      const shortId = this.getQuestionId(1, table.TableQuestions.Questions)
      this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], shortId, null)
      this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'LesionShort', null)
      const stateId = this.getQuestionId(7, table.TableQuestions.Questions)
      this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], stateId, null)
      this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'LesionState', null)
      const obj = Object.assign({}, innerForm.MeasureData)
      // 移除标注信息
      if (innerForm.IsDicomReading && innerForm.IsDicomReading !== 'False') {
        this.$emit('removeAnnotation', obj)
      } else {
        DicomEvent.$emit('removeNoneDicomMeasureData', obj)
      }
      // 重置标注信息
      this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'MeasureData', null)
      // 重置保存标志
      this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'SaveTypeEnum', innerForm.RowId ? 1 : 0)
      this.$refs[`form_${table.Id}_${rowIndex}`][0].getOrganList()
    },
    // 删除病灶
    async deleteLesion(table, rowIndex) {
      const loading = this.$loading({ fullscreen: true })
      try {
        const confirm = await this.$confirm(
          this.$t('trials:reading:warnning:msg48'),
          {
            type: 'warning',
            distinguishCancelAndClose: true
          }
        )
        if (confirm !== 'confirm') return
        const innerForm = this.innerFormData[`${table.Id}_${rowIndex}`]
        if (innerForm.RowId) {
          const param = {
            visitTaskId: this.visitTaskId,
            questionId: table.Id,
            rowId: innerForm.RowId
          }
          const res = await deleteReadingRowAnswer(param)
          if (res.IsSuccess) {
            if (innerForm.MeasureData) {
              // 移除标注信息
              const obj = Object.assign({}, innerForm.MeasureData)
              if (innerForm.IsDicomReading && innerForm.IsDicomReading !== 'False') {
                this.$emit('removeAnnotation', obj)
              } else {
                DicomEvent.$emit('removeNoneDicomMeasureData', obj)
              }
            }
            // 刷新表格问题
            await this.getTableQuestions()
            this.$emit('getAnnotations', this.visitTaskId)
            // '删除成功！'
            this.$message.success(this.$t('common:message:deletedSuccessfully'))
            this.activeName = ''
          }
        } else {
          if (innerForm.MeasureData) {
            // 移除标注信息
            const obj = Object.assign({}, innerForm.MeasureData)
            if (innerForm.IsDicomReading && innerForm.IsDicomReading !== 'False') {
              this.$emit('removeAnnotation', obj)
            } else {
              DicomEvent.$emit('removeNoneDicomMeasureData', obj)
            }
          }
          // 移除病灶
          this.removeAnswer(table.Id, rowIndex)
          delete this.innerFormData[`${table.Id}_${rowIndex}`]
          this.activeName = ''
        }
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    },
    // 保存病灶
    async saveLesion(table, rowIndex) {
      const rowKey = `${table.Id}_${rowIndex}`
      if (this.rowSaveLoadingMap[rowKey]) return
      this.$set(this.rowSaveLoadingMap, rowKey, true)
      await this.$nextTick()
      let loading = null
      try {
        const valid = await this.$refs[`${table.Id}_${rowIndex}`][0].validate()
        if (!valid) return
        loading = this.$loading({ fullscreen: true })
        const closeLoading = loading.close.bind(loading)
        loading.close = () => {
          closeLoading()
          loading = null
        }
        const innerForm = this.innerFormData[`${table.Id}_${rowIndex}`]
        const measureData = innerForm.MeasureData
        const lesionState = innerForm.LesionState
        let lesionLength = innerForm.LesionLength
        let lesionShort = innerForm.LesionShort
        const lymphNodes = innerForm.IsLymphNodes
        const lesionType = table.LesionType
        // const lesionPart = innerForm.LesionPart
        if (this.isBaseLineTask) {
          // 基线
          // 靶病灶且状态为存在（0）
          if (lesionType === 0 && lesionState === 0) {
            if (lymphNodes === 1) {
              //  淋巴结靶病灶 必须使用长短径测量工具,短径大于等于15mm
              if (!(measureData && measureData.markTool === 'Bidirectional' && lesionShort >= 15)) {
                // 评估状态为存在的淋巴结靶病灶需使用长短径测量工具添加标记，且短径须大于15mm！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg19'))
                return
              }
            } else {
              // 非淋巴结靶病灶 直径测量工具 长径须大于等于10mm且不小于2倍层厚
              if (!(measureData && measureData.markTool === 'Length' && lesionLength >= 10 && (measureData.sliceThickness && lesionLength >= 2 * measureData.sliceThickness || !measureData.sliceThickness))) {
                // 评估状态为存在的非淋巴结靶病灶需使用直径测量工具添加标记，长径须大于10mm且不小于2倍层厚！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg20'))
                return
              }
            }
          }

          // 非靶病灶且状态为存在（0）
          if (lesionType === 1 && lesionState === 0) {
            if (lymphNodes === 1) {
              // 淋巴结非靶病灶 必须使用长短径测量工具或箭头工具
              if (!(measureData && (measureData.markTool === 'Bidirectional' || measureData.markTool === 'RectangleROI' || measureData.markTool === "RectangleRoi"))) {
                // 评估状态为存在的淋巴结非靶病灶需使用长短径测量工具或矩形工具添加标记
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg21'))
                return
              }
            } else {
              // 非淋巴结非靶病灶 直径测量工具或箭头工具
              console.log(measureData, 'measureData')
              if (!(measureData && (measureData.markTool === 'Length' || measureData.markTool === 'RectangleROI' || measureData.markTool === "RectangleRoi"))) {
                // 评估状态为存在的非淋巴结非靶病灶需使用直径测量工具或矩形工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg22'))
                return
              }
            }
          }
        } else {
          // 非基线
          // 靶病灶且状态为存在（0）
          if (lesionType === 0 && lesionState === 0) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 必须使用长短径测量工具
              if (!(measureData && measureData.markTool === 'Bidirectional' && lesionShort >= 10)) {
                // 评估状态为存在的淋巴结靶病灶需使用长短径测量工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg23'))
                return
              }
            } else {
              // 非淋巴结靶病灶 直径测量工具
              if (!(measureData && measureData.markTool === 'Length')) {
                // `评估状态为存在的非淋巴结靶病灶需使用直径测量工具添加标记！`
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg24'))
                return
              }
            }
          }
          // 靶病灶且状态为太小（1）
          if (lesionType === 0 && lesionState === 1) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 必须使用箭头工具，短径记录为5mm
              if (!(measureData && (measureData.markTool === 'ArrowAnnotate'))) {
                // 评估状态为太小的淋巴结靶病灶需使用箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg25'))
                return
              } else if (measureData && measureData.markTool === 'ArrowAnnotate') {
                const shortId = this.getQuestionId(1, table.TableQuestions.Questions)
                this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], shortId, 5)
                this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'LesionShort', 5)
                lesionShort = 5
              }
            } else {
              // 非淋巴结靶病灶 箭头工具，长径记录为5mm
              if (!(measureData && (measureData.markTool === 'ArrowAnnotate'))) {
                // 评估状态为太小的非淋巴结靶病灶需使用箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg26'))
                return
              } else if (measureData && measureData.markTool === 'ArrowAnnotate') {
                const lengthId = this.getQuestionId(0, table.TableQuestions.Questions)
                this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], lengthId, 5)
                this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'LesionLength', 5)
                lesionLength = 5
              }
            }
          }

          // 靶病灶且状态为无法评估（2）
          if (lesionType === 0 && lesionState === 2) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 不需要添加标记
              if (measureData) {
                // 评估状态为无法评估的淋巴结靶病灶不需要添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg27'))
                return
              }
            } else {
              // 非淋巴结靶病灶 不需要添加标记
              if (measureData) {
                // 状态为无法评估的非淋巴结靶病灶不需要添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg28'))
                return
              }
            }
          }

          // 靶病灶且状态为消失（3）
          if (lesionType === 0 && lesionState === 3) {
            if (lymphNodes === 1) {
              if (!(measureData && (measureData.markTool === 'Bidirectional' && lesionShort < 10))) {
                // `评估状态为消失的淋巴结靶病灶需使用长短径工具添加标记,且短径需小于10mm！`
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg29'))
                return
              }
            } else {
              // 非淋巴结靶病灶 箭头工具
              if (!(measureData && measureData.markTool === 'ArrowAnnotate')) {
                // 评估状态为消失的非淋巴结靶病灶只能使用箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg30'))
                return
              } else if (measureData && measureData.markTool === 'ArrowAnnotate') {
                const lengthId = this.getQuestionId(0, table.TableQuestions.Questions)
                this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], lengthId, null)
                this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'LesionLength', null)
                lesionLength = null
              }
            }
          }

          // 非靶病灶且状态为存在（0）
          if (lesionType === 1 && lesionState === 0) {
            if (lymphNodes === 1) {
              // 淋巴结非靶病灶 必须使用长短径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'Bidirectional' || measureData.markTool === 'RectangleROI' || measureData.markTool === "RectangleRoi"))) {
                // 评估状态为存在的淋巴结非靶病灶需使用长短径测量工具或箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg31'))
                return
              }
            } else {
              // 非淋巴结非靶病灶 直径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'Length' || measureData.markTool === 'RectangleROI' || measureData.markTool === "RectangleRoi"))) {
                // 评估状态为存在的非淋巴结非靶病灶需使用直径测量工具或箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg32'))
                return
              }
            }
          }

          // 非靶病灶且状态为显著增大（1）
          if (lesionType === 1 && lesionState === 1) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 必须使用长短径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'Bidirectional' || measureData.markTool === 'RectangleROI' || measureData.markTool === "RectangleRoi"))) {
                // `评估状态为显著增大的淋巴结非靶病灶需使用长短径测量工具或矩形工具添加标记！`
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg33'))
                return
              }
            } else {
              // 非淋巴结非靶病灶 直径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'Length' || measureData.markTool === 'RectangleROI' || measureData.markTool === "RectangleRoi"))) {
                // 评估状态为显著增大的非淋巴结非靶病灶需使用直径测量工具或矩形工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg34'))
                return
              }
            }
          }

          // 非靶病灶且状态为无法评估（2）
          if (lesionType === 1 && lesionState === 2) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 无标记
              if (measureData) {
                // 评估状态为无法评估的淋巴结非靶病灶不需要添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg35'))
                return
              }
            } else {
              // 非淋巴结非靶病灶 无标记
              if (measureData) {
                // 评估状态为无法评估的非淋巴结非靶病灶不需要添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg36'))
                return
              }
            }
          }

          // 非靶病灶且状态为消失（3）
          if (lesionType === 1 && lesionState === 3) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 必须使用长短径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'ArrowAnnotate' || (measureData.markTool === 'Bidirectional' && lesionShort < 10)))) {
                // 评估状态为消失的淋巴结非靶病灶需使用箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg37'))
                return
              }
            } else {
              // 非淋巴结非靶病灶 箭头工具
              if (!(measureData && (measureData.markTool === 'ArrowAnnotate'))) {
                // 评估状态为消失的非淋巴结非靶病灶需使用箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg38'))
                return
              }
            }
          }

          // 新病灶且状态为存在（0）
          if (lesionType === 2 && lesionState === 0) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 必须使用长短径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'Bidirectional' || measureData.markTool === 'ArrowAnnotate'))) {
                // 评估状态为存在的淋巴结新病灶需使用长短径测量工具或箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg39'))
                return
              }
            } else {
              // 非淋巴结非靶病灶 直径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'Length' || measureData.markTool === 'ArrowAnnotate'))) {
                // 评估状态为存在的非淋巴结新病灶需使用直径测量工具或箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg40'))
                return
              }
            }
          }

          // 新病灶且状态为疑似（1）
          if (lesionType === 2 && lesionState === 1) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 必须使用长短径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'Bidirectional' || measureData.markTool === 'ArrowAnnotate'))) {
                // 评估状态为疑似的淋巴结新病灶需使用长短径测量工具或箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg41'))
                return
              }
            } else {
              // 非淋巴结非靶病灶 直径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'Length' || measureData.markTool === 'ArrowAnnotate'))) {
                // `评估状态为疑似的非淋巴结新病灶需使用直径测量工具或箭头工具添加标记！`
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg42'))
                return
              }
            }
          }

          // 新病灶且状态为无法评估（2）
          if (lesionType === 2 && lesionState === 2) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 必须使用长短径测量工具、箭头工具
              if (measureData) {
                // `评估状态为无法评估的淋巴结新病灶不需要添加标记！`
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg43'))
                return
              }
            } else {
              // 非淋巴结非靶病灶 直径测量工具、箭头工具
              if (measureData) {
                // 评估状态为无法评估的非淋巴结新病灶不需要添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg44'))
                return
              }
            }
          }

          // 新病灶且状态为消失（3）
          if (lesionType === 2 && lesionState === 3) {
            if (lymphNodes === 1) {
              // 淋巴结靶病灶 必须使用长短径测量工具、箭头工具
              if (!(measureData && (measureData.markTool === 'ArrowAnnotate' || (measureData.markTool === 'Bidirectional' && lesionShort < 10)))) {
                // 评估状态为消失的淋巴结新病灶需使用箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg45'))
                return
              }
            } else {
              // 箭头工具
              if (!(measureData && (measureData.markTool === 'ArrowAnnotate'))) {
                // 评估状态为消失的非淋巴结新病灶需使用箭头工具添加标记！
                await this.showValidationDialog(this.$t('trials:reading:warnning:msg46'))
                return
              }
            }
          }
        }
        // 获取截图
        const obj = Object.assign({}, measureData)
        obj.visitTaskId = this.visitTaskId
        obj.lesionName = innerForm.LesionName
        let picturePath = ''
        if (measureData) {
          const base64Str = await this.getScreenshots(obj)
          const pictureObj = await this.uploadScreenshots(`${new Date().getTime()}`, base64Str)
          picturePath = pictureObj.isSuccess ? this.$getObjectName(pictureObj.result.url) : ''
        }
        const answers = []
        const reg = new RegExp(/^[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}$/)
        for (const k in innerForm) {
          if (reg.test(k)) {
            if (answers.findIndex(i => i.tableQuestionId === k) === -1) {
              answers.push({ tableQuestionId: k, answer: innerForm[k] })
            }
          }
        }
        const params = {
          questionId: table.Id,
          rowId: innerForm.RowId,
          rowIndex: innerForm.RowIndex,
          visitTaskId: this.visitTaskId,
          trialId: this.$route.query.trialId,
          measureData: measureData ? JSON.stringify(measureData) : '',
          answerList: answers,
          isCanEditPosition: innerForm.IsCanEditPosition,
          studyId: measureData ? measureData.studyId : '',
          seriesId: measureData ? measureData.seriesId : '',
          instanceId: measureData ? measureData.instanceId : '',
          numberOfFrames: measureData ? measureData.numberOfFrames : null,
          picturePath: picturePath,
          organInfoId: innerForm.OrganInfoId,
          markTool: measureData ? measureData.markTool : '',
          isDicomReading: innerForm.IsDicomReading
        }
        if (this.deleteTargetInfo && this.deleteTargetInfo.newLesionName === innerForm.LesionName) {
          await deleteReadingRowAnswer({
            visitTaskId: this.visitTaskId,
            questionId: this.deleteTargetInfo.tableId,
            rowId: this.deleteTargetInfo.rowId
          })
          this.deleteTargetInfo = null
          params.rowId = ''
        }
        const res = await submitTableQuestion(params)
        if (res.IsSuccess) {
          // 保存成功！
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          // this.getTableQuestions()
          // this.$emit('getAnnotations', this.visitTaskId)
          if (!this.innerFormData[`${table.Id}_${rowIndex}`].RowId) {
            this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'RowId', res.Result.RowId)
          }
          this.$set(this.innerFormData[`${table.Id}_${rowIndex}`], 'SaveTypeEnum', 2)
          this.activeName = ''
        }
        loading.close()
      } catch (e) {
        console.log(e)
        if (loading) {
          loading.close()
        }
      } finally {
        this.$set(this.rowSaveLoadingMap, rowKey, false)
        if (loading) {
          loading.close()
        }
      }
    },
    // 上传截图
    async uploadScreenshots(fileName, file) {
      try {
        file = this.convertBase64ToBlob(file)
        const trialId = this.$route.query.trialId
        const subjectId = this.taskInfo.SubjectId
        const result = await this.OSSclient.put(`/${trialId}/Read/${subjectId}/${this.visitTaskId}/${fileName}.png`, file)
        return { isSuccess: true, result: result }
      } catch (e) {
        console.log(e)
        return { isSuccess: false, result: e }
      }
    },
    convertBase64ToBlob(imageEditorBase64) {
      const base64Arr = imageEditorBase64.split(',')
      let imgtype = ''
      let base64String = ''
      if (base64Arr.length > 1) {
        base64String = base64Arr[1]
        imgtype = base64Arr[0].substring(
          base64Arr[0].indexOf(':') + 1,
          base64Arr[0].indexOf(';')
        )
      }
      const bytes = atob(base64String)
      const bytesCode = new ArrayBuffer(bytes.length)
      const byteArray = new Uint8Array(bytesCode)
      for (let i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i)
      }
      return new Blob([bytesCode], { type: imgtype })
    },
    // 获取截图
    getScreenshots(obj) {
      return new Promise((resolve, reject) => {
        obj.visitTaskId = this.visitTaskId
        this.$emit('getScreenshots', obj, resolve) // 将resolve传递给父组件
      })
    },
    // 更新表格问题表单信息
    innerFormDataUpdate(obj) {
      const innerForm = this.innerFormData[`${obj.tableId}_${obj.rowIndex}`]
      if (innerForm === undefined || typeof innerForm !== 'object') return
      this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], obj.questionId, obj.val)
      // QuestionMark：0--长径；1--短径；2--是否淋巴结；5--所在器官；7--状态；8--所在部位；
      if (obj.questionMark === 0) {
        this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'LesionLength', obj.val)
      }
      if (obj.questionMark === 1) {
        this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'LesionShort', obj.val)
      }

      if (obj.questionMark === 7) {
        this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'LesionState', obj.val)
        let annotation = this.innerFormData[`${obj.tableId}_${obj.rowIndex}`].MeasureData
        if (annotation) {
          this.setMarkName(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`].LesionType, obj.val, this.innerFormData[`${obj.tableId}_${obj.rowIndex}`].LesionName, annotation)
        }

      }
      if (obj.questionMark === 8) {
        this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'LesionPart', obj.val)
      }
      if (obj.updateArr) {
        obj.updateArr.forEach(i => {
          this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], i.questionId, i.val)
          if (i.questionMark === 2) {
            this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'IsLymphNodes', i.val)
          } else if (i.questionMark === 5) {
            this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'LesionOrgan', i.val)
          }
        })
      }

      const rowId = this.innerFormData[`${obj.tableId}_${obj.rowIndex}`].RowId
      this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'SaveTypeEnum', rowId ? 1 : 0)
    },
    handleCollapseChange(v) {
      if (!v) return
      const tableId = v.split('_')[0]
      const rowIndex = v.split('_')[1]
      const innerForm = this.innerFormData[`${tableId}_${rowIndex}`]
      // if (!innerForm.MeasureData) return
      const obj = Object.assign({ visitTaskId: this.visitTaskId }, innerForm.MeasureData)
      obj.lesionName = innerForm.LesionName
      obj.markTool = innerForm.MarkTool ? innerForm.MarkTool : ''
      obj.isMarked = !!innerForm.MeasureData
      obj.SplitOrMergeType = innerForm.SplitOrMergeType
      if (this.visitTaskId === this.taskInfo.VisitTaskId) {
        obj.isActiveTarget = true
      }
      this.$emit('imageLocation', obj)
    },
    collapseRightClick(e, tableId, rowIndex) {
      const innerForm = this.innerFormData[`${tableId}_${rowIndex}`]
      if (!innerForm.MeasureData) return
      const obj = Object.assign({ visitTaskId: this.visitTaskId }, innerForm.MeasureData)
      obj.lesionName = innerForm.LesionName
      obj.SplitOrMergeType = innerForm.SplitOrMergeType
      this.$emit('imageLocation', obj)
      e.stopImmediatePropagation()
      e.stopPropagation()
      e.preventDefault()
    },
    // 病灶分裂
    async lesionSplit(tableId, rowId) {
      try {
        // 判断是否有病灶未保存
        const obj = Object.values(this.innerFormData).find(
          obj => !obj.RowId
        )
        if (obj !== undefined && typeof obj === 'object') {
          let msg = this.$t('trials:reading:warnning:msg5')
          msg = msg.replace('xxx', obj.LesionName)

          this.$confirm(msg, {
            type: 'warning',
            showCancelButton: false,
            callback: action => { }
          })
          return
        }
        const confirm = await this.$confirm(
          this.$t('trials:reading:warnning:msg4'),
          {
            type: 'warning',
            distinguishCancelAndClose: true
          }
        )
        console.log(confirm)
        if (confirm !== 'confirm') return
        this.split(tableId, rowId)
      } catch (e) {
        console.log(e)
      }
    },
    async split(tableId, rowId) {
      const loading = this.$loading({ fullscreen: true })
      try {
        var params = {
          visitTaskId: this.visitTaskId,
          questionId: tableId,
          rowId: rowId
        }
        await splitLesion(params)
        await this.getTableQuestions()
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      } finally {
        this.$set(this.rowSaveLoadingMap, rowKey, false)
      }
    },
    // 重置表单
    async resetForm() {
      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.getOuterQuestions()
          this.getTableQuestions()
          this.$emit('resetAnnotations', this.visitTaskId)
          DicomEvent.$emit('removeNoneDicomMeasureData', null)
        }
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    },
    getMaxRowIndex(answers) {
      if (answers.length > 0) {
        const arr = []
        answers.forEach(item => {
          var rowIndex = item.RowIndex
          arr.push(parseInt(rowIndex))
        })
        const max = Math.max.apply(null, arr)
        return max
      } else {
        return 0
      }
    },
    getQuestionId(questionMark, tableQuestions) {
      const idx = tableQuestions.findIndex(i => i.QuestionMark === questionMark)
      if (idx > -1) {
        return tableQuestions[idx].Id
      } else {
        return ''
      }
    },
    // 获取病灶名称
    getLesionName(orderMark, rowIndex) {
      let lessionName = ''
      const rowIndexArr = rowIndex.split('.')
      const x = parseInt(rowIndexArr[0])
      let 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
    },
    // 查看反馈记录
    openFeedBackTable() {
      this.$FB({
        type: 'imgfail',
        trialId: this.$route.query.trialId,
        visitTaskId: this.visitTaskId,
        callBack: async () => {
          const confirm = await this.$confirm(
            this.$t('trials:reading:confirm:feedbackmsg'),
            {
              type: 'warning',
              distinguishCancelAndClose: true
            }
          )
          if (confirm !== 'confirm') return
          this.loading = true
          try {
            const res = await setSkipReadingCache({ visitTaskId: this.visitTaskId })
            this.loading = false
            if (res.IsSuccess) {
              window.location.reload()
            }
          } catch (e) {
            this.loading = false
            console.log(e)
          }
        }
      })
    },
    // 病灶类型切换
    lesionTypeChange(obj) {
      const innerForm = this.innerFormData[`${obj.tableId}_${obj.rowIndex}`]
      // 判断是否存在未保存的病灶，否则不允许添加
      const formData = Object.values(this.innerFormData).find(
        obj => !obj.RowId && obj.LesionName !== innerForm.LesionName
      )
      if (formData !== undefined && typeof formData === 'object') {
        let msg = this.$t('trials:reading:warnning:msg5')
        msg = msg.replace('xxx', formData.LesionName)

        this.$confirm(msg, {
          type: 'warning',
          showCancelButton: false,
          callback: action => { }
        })
        this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'LesionType', innerForm.LesionType)
        return
      }

      const targetTable = this.tableQuestions[0].Childrens.find(
        child => child.LesionType === obj.newLesionType
      )
      if (typeof targetTable !== 'object') return
      // 判断当前病灶类型下的病灶个数是否超过最大行数，否则不允许添加
      if (!!targetTable.MaxQuestionCount && targetTable.MaxQuestionCount <= targetTable.TableQuestions.Answers.length) {
        let msg = this.$t('trials:reading:warnning:msg14')
        msg = msg.replace('xxx', targetTable.MaxQuestionCount)
        this.$confirm(msg, {
          type: 'warning',
          showCancelButton: false,
          callback: action => { }
        })
        this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'LesionType', innerForm.LesionType)
        return
      }
      // 基线时，切换为靶病灶时：1.如果存在标注，标注只能是用直径和长短径标注；2.非dicom文件的标注不能作为靶病灶。提示：当前病灶不允许设置为靶病灶
      if ((this.isBaseLineTask || innerForm.IsDicomReading === false) && innerForm.MeasureData && innerForm.MeasureData.markTool === 'ArrowAnnotate' && obj.newLesionType === 0) {
        // 当前病灶不允许设置为靶病灶
        this.$confirm(this.$t(' trials:reading:warnning:msg15'), {
          type: 'warning',
          showCancelButton: false,
          callback: action => { }
        })
        this.$set(this.innerFormData[`${obj.tableId}_${obj.rowIndex}`], 'LesionType', innerForm.LesionType)
        return
      }
      // 移除当前病灶
      this.removeAnswer(obj.tableId, obj.rowIndex)
      delete this.innerFormData[`${obj.tableId}_${obj.rowIndex}`]
      // 添加新病灶
      const answer = Object.assign({}, this.innerFormData[targetTable.Id])
      answer.RowId = ''
      const maxIndex = this.getMaxRowIndex(targetTable.TableQuestions.Answers)
      answer.RowIndex = `${maxIndex + 1}.00`
      answer.IsDicomReading = true
      answer.SaveTypeEnum = 0
      answer.LesionType = targetTable.LesionType
      answer.LesionName = this.getLesionName(targetTable.OrderMark, answer.RowIndex)
      answer.TableId = targetTable.Id
      let state = null
      if (this.isBaseLineTask && targetTable.LesionType === 0) {
        state = 0
      }
      if (this.isBaseLineTask && targetTable.LesionType === 1) {
        state = 0
      }
      let lesionLength = null
      let lesionShort = null
      if (innerForm.MeasureData) {
        if (innerForm.MeasureData.metadata.toolName === 'Length') {
          const referencedImageId = innerForm.MeasureData.metadata.referencedImageId
          const length = innerForm.MeasureData.data.cachedStats[`imageId:${referencedImageId}`].length
          lesionLength = length ? parseFloat(length).toFixed(this.digitPlaces) : length
        } else if (innerForm.MeasureData.metadata.toolName === 'Bidirectional') {
          const referencedImageId = innerForm.MeasureData.metadata.referencedImageId
          const length = innerForm.MeasureData.data.cachedStats[`imageId:${referencedImageId}`].length
          lesionLength = length ? parseFloat(length).toFixed(this.digitPlaces) : length
          const short = innerForm.MeasureData.data.cachedStats[`imageId:${referencedImageId}`].width
          lesionShort = short ? parseFloat(short).toFixed(this.digitPlaces) : short
        }
        this.$emit('setMarkName', {
          annotationUID: innerForm.MeasureData.annotationUID,
          name: answer.LesionName
        })
        answer.MeasureData = innerForm.MeasureData
      }
      const lengthId = this.getQuestionId(0, targetTable.TableQuestions.Questions)
      answer[lengthId] = lesionLength
      const shortId = this.getQuestionId(1, targetTable.TableQuestions.Questions)
      answer[shortId] = lesionShort
      const stateId = this.getQuestionId(7, targetTable.TableQuestions.Questions)
      answer[stateId] = state
      targetTable.TableQuestions.Answers.push(answer)
      this.innerFormData[`${targetTable.Id}_${answer.RowIndex}`] = answer
      this.activeName = `${targetTable.Id}_${answer.RowIndex}`

      if (innerForm.RowId) {
        this.deleteTargetInfo = { rowId: innerForm.RowId, tableId: obj.tableId, newLesionName: answer.LesionName }
      }
    },
    async closeInnerForm(obj) {
      const innerForm = this.innerFormData[`${obj.tableId}_${obj.rowIndex}`]
      if (innerForm === undefined || typeof innerForm !== 'object') return
      if (!innerForm.RowId) {
        // 当前病灶为新建病灶，未保存。如果关闭窗口，将会删除病灶信息，是否继续？
        const confirm = await this.$confirm(
          this.$t('trials:reading:warnning:msg49'),
          {
            type: 'warning',
            distinguishCancelAndClose: true
          }
        )
        if (confirm !== 'confirm') return
        // 移除病灶信息
        this.removeAnswer(obj.tableId, obj.rowIndex)
        delete this.innerFormData[`${obj.tableId}_${obj.rowIndex}`]
        // 移除标注信息
        if (innerForm.MeasureData) {
          const obj = Object.assign({}, innerForm.MeasureData)
          if (innerForm.IsDicomReading && innerForm.IsDicomReading !== 'False') {
            this.$emit('removeAnnotation', obj)
          } else {
            DicomEvent.$emit('removeNoneDicomMeasureData', obj)
          }
        }
        // 关闭窗口
        this.activeName = ''
      } else {
        // 关闭窗口
        this.activeName = ''
      }
    },
    changeLesionState() {
      Object.values(this.innerFormData).forEach(i => {
        if (isNaN(parseInt(i.LesionState)) && i.IsCurrentTaskAdd === 'False') {
          i.LesionState = 2
          const targetTable = this.tableQuestions[0].Childrens.find(
            child => child.Id === i.TableId
          )
          const stateId = this.getQuestionId(7, targetTable.TableQuestions.Questions)
          i[stateId] = 2
        }
      })
    },
    removeAnswer(tableId, rowIndex) {
      const targetTable = this.tableQuestions[0].Childrens.find(
        child => child.Id === tableId
      )
      if (targetTable?.TableQuestions?.Answers) {
        const originalAnswers = targetTable.TableQuestions.Answers
        const index = originalAnswers.findIndex(item => item.RowIndex === rowIndex)
        if (index > -1) {
          targetTable.TableQuestions.Answers.splice(index, 1)
        }
      }
    },
    validTool(toolName) {
      const obj = Object.values(this.innerFormData).find(
        obj => !obj.RowId
      )
      if (typeof obj === 'object') {
        if (this.activeName) {
          const tableId = this.activeName.split('_')[0]
          const rowIndex = this.activeName.split('_')[1]
          const innerForm = this.innerFormData[`${tableId}_${rowIndex}`]
          if (innerForm.SplitOrMergeType === '1' || innerForm.SplitOrMergeType === '3') {
            return { isCanActiveTool: false, reason: '' }
          }
          if (!innerForm.MeasureData) {
            return this.checkToolCanActive(toolName)
          } else {
            let msg = this.$t('trials:reading:warnning:msg5')
            msg = msg.replace('xxx', innerForm.LesionName)
            // `病灶xxx信息未保存，不允许继续添加！`
            return { isCanActiveTool: false, reason: msg }
          }
        } else {
          let msg = this.$t('trials:reading:warnning:msg5')
          msg = msg.replace('xxx', obj.LesionName)
          // `病灶xxx信息未保存，不允许继续添加！`
          return { isCanActiveTool: false, reason: msg }
        }
      } else {
        if (this.activeName) {
          return this.checkToolCanActive(toolName)
        } else {
          if (this.isBaseLineTask && (toolName === 'Bidirectional' || toolName === 'Length' || toolName === 'RectangleRoi' || toolName === 'RectangleROI')) {
            return { isCanActiveTool: true, reason: '' }
          } else if (!this.isBaseLineTask && (toolName === 'ArrowAnnotate' || toolName === 'Bidirectional' || toolName === 'Length' || toolName === 'RectangleRoi' || toolName === 'RectangleROI')) {
            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) {
      const tableId = this.activeName.split('_')[0]
      const rowIndex = this.activeName.split('_')[1]
      const innerForm = this.innerFormData[`${tableId}_${rowIndex}`]
      const isLymphNodes = innerForm.IsLymphNodes
      if (innerForm.SplitOrMergeType === '1' || innerForm.SplitOrMergeType === '3') {
        return { isCanActiveTool: false, reason: '' }
      }
      if (!innerForm.MeasureData) {
        if (this.isBaseLineTask) {
          if (innerForm.LesionType === 0 && isLymphNodes === 1 && toolName !== 'Bidirectional') {
            // '淋巴结靶病灶需使用长短径测量工具'
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg6') }
          } else if (innerForm.LesionType === 0 && isLymphNodes === 0 && toolName !== 'Length') {
            // '非淋巴结靶病灶需使用直径测量工具'
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg7') }
          } else if (innerForm.LesionType === 1 && isLymphNodes === 1 && toolName !== 'Bidirectional' && toolName !== 'RectangleRoi' && toolName !== 'RectangleROI') {
            // '淋巴结非靶病灶需使用长短径测量工具或矩形工具'
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg8') }
          } else if (innerForm.LesionType === 1 && isLymphNodes === 0 && toolName !== 'Length' && toolName !== 'RectangleRoi' && toolName !== 'RectangleROI') {
            // '非淋巴结非靶病灶需使用直径测量工具或矩形工具'
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg9') }
          } else if (toolName === 'ArrowAnnotate') {
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg54') }
          } else {
            return { isCanActiveTool: true, reason: '' }
          }
        } else {
          if (innerForm.LesionType === 0 && isLymphNodes === 1 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate') {
            // 淋巴结靶病灶需使用长短径测量工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg10') }
          } else if (innerForm.LesionType === 0 && isLymphNodes === 0 && toolName !== 'Length' && toolName !== 'ArrowAnnotate') {
            // 非淋巴结靶病灶需使用直径测量工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg11') }
          } else if (innerForm.LesionType === 1 && isLymphNodes === 1 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate' && toolName !== 'RectangleRoi' && toolName !== 'RectangleROI') {
            // 淋巴结非靶病灶需使用长短径测量工具或矩形工具或矩形工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg52') }
          } else if (innerForm.LesionType === 1 && isLymphNodes === 0 && toolName !== 'Length' && toolName !== 'ArrowAnnotate' && toolName !== 'RectangleRoi' && toolName !== 'RectangleROI') {
            // 非淋巴结非靶病灶需使用直径测量工具或矩形工具或矩形工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg53') }
          } else if (innerForm.LesionType === 2 && isLymphNodes === 1 && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate') {
            // 淋巴结新病灶需使用长短径测量工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg12') }
          } else if (innerForm.LesionType === 2 && isLymphNodes === 0 && toolName !== 'Length' && toolName !== 'ArrowAnnotate') {
            // 非淋巴结新病灶需使用直径测量工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg13') }
          } else if (innerForm.LesionType === 2 && toolName !== 'Length' && toolName !== 'Bidirectional' && toolName !== 'ArrowAnnotate') {
            // 新病灶需使用直径测量工具或箭头工具
            return { isCanActiveTool: false, reason: this.$t('trials:reading:warnning:msg51') }
          } else {
            return { isCanActiveTool: true, reason: '' }
          }
        }
      } else {
        return { isCanActiveTool: true, reason: '' }
      }
    },
    receiveMsg(event) {
      if (event.data.type === 'isCanActiveNoneDicomTool') {
        let obj = { isCanActiveTool: true, lesionName: '', reason: '', toolName: event.data.toolName }
        let { isCanActiveTool, reason } = this.validTool(event.data.toolName)
        obj.isCanActiveTool = isCanActiveTool
        obj.reason = reason
        DicomEvent.$emit('isCanActiveNoneDicomTool', obj)
      } else if (event.data.type === 'setMeasurement') {
        if (JSON.stringify(event.data.data) !== "{}") {
          this.setAnnotation(event.data.data)
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.login-cycle {
  width: 5px;
  height: 5px;
  display: inline-block;
  background-color: #428bca;
  border-radius: 50%;
  margin-right: 2px;
  margin-bottom: 2px;
}

.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;
    }
  }
}

.questionList-wrapper {
  height: 100%;
  overflow-y: auto;
  // overflow: hidden;

  .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;
      }
    }
  }

  .outer_form_wrapper {
    ::v-deep .el-form-item__label {
      color: #c3c3c3;
      text-align: left;
    }

    ::v-deep .el-input__inner {
      background-color: transparent;
      color: #ddd;
      border: 1px solid #5e5e5e;
    }

    ::v-deep .el-textarea__inner {
      background-color: transparent;
      color: #ddd;
      border: 1px solid #5e5e5e;
    }

    ::v-deep .el-form-item {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      flex-wrap: wrap;
    }

    ::v-deep .el-form-item__content {
      flex: 1;
    }

    ::v-deep .el-button--mini,
    .el-button--mini.is-round {
      padding: 7px 10px;
    }

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

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

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

        &:hover {
          color: #68a2d5;
        }
      }
    }

  }

  .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;

    ::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;
    }

  }
}
</style>
