<template>
  <el-form v-if="isRender" ref="measurementForm" v-loading="loading" :model="questionForm" size="mini"
    class="measurement-form">
    <div class="base-dialog-body">
      <div style="display: flex;justify-content: space-between;">
        <h3 v-if="lesionName" style="color: #ddd;padding: 5px 0px;margin: 0;">
          <!-- {{ `${questionName} (${orderMark}${String(rowIndex).padStart(2, '0')})` }} -->
          {{ lesionName }}
        </h3>
        <!-- 关闭 -->
        <div>
          <i class="el-icon-circle-close" style="font-size: 25px;cursor: pointer;" @click="handleClose" />
        </div>
      </div>

      <el-form-item :label="$t('trials:reading:title:lesionType')" prop="LesionType" :rules="[
        { required: true, message: $t('common:ruleMessage:select'), trigger: ['blur'] },
      ]">
        <!-- 下拉框 -->
        <el-select v-model="questionForm.LesionType" filterable
          :disabled="!isCurrentTask || readingTaskState >= 2 || !isBaseLineTask"
          @change="((val) => { lesionTypeChange(val) })">

          <el-option v-for="item of $d.LesionType" v-show="!(isBaseLineTask && item.value === 2)" :key="item.id"
            :value="item.value" :label="item.label" />

        </el-select>
      </el-form-item>

      <template v-for="qs in questions">
        <el-form-item v-if="qs.ShowQuestion !== 2 && qs.QuestionClassify === 0" :key="qs.Id"
          :label="`${qs.QuestionName}`" :prop="qs.Id" :rules="[
            {
              required: (qs.IsRequired === 0 || (qs.IsRequired === 1 && qs.RelevanceId && (questionForm[qs.RelevanceId] === qs.RelevanceValue)) || (qs.QuestionMark === 6 && questionForm.IsCanEditPosition === true) || (questionForm.IsCanEditPosition && qs.QuestionMark === 10)) && qs.Type !== 'group' && qs.Type !== 'summary',
              message: ['radio', 'select', 'checkbox'].includes(qs.Type) ? $t('common:ruleMessage:select') : $t('common:ruleMessage:specify'), trigger: ['blur', 'change']
            },
          ]">
          <!-- {{ isCurrentTaskAdd }}
        {{ questionForm.IsCanEditPosition }} -->

          <!-- 输入框 -->
          <template v-if="qs.Type === 'input' || qs.Type === 'number'">
            <div style="display: flex;justify-content: space-between;">
              <!-- {{ ((qs.QuestionMark === 6 && isCurrentTaskAdd === 'False') || (qs.QuestionMark === 6 && isCurrentTaskAdd === 'True' && !questionForm.IsCanEditPosition)) }} -->
              <el-input v-if="qs.Type === 'input' || qs.Type === 'number'" v-model="questionForm[qs.Id]"
                :disabled="!isCurrentTask || readingTaskState >= 2 || qs.QuestionMark === 0 || qs.QuestionMark === 1 || qs.QuestionMark === 2 || qs.QuestionMark === 5 || (qs.QuestionMark === 6 && (isCurrentTaskAdd === 'False' || (isCurrentTaskAdd === 'True' && !questionForm.IsCanEditPosition) || !!answers.SplitOrMergeLesionName)) || (qs.QuestionMark === 8 && (isCurrentTaskAdd === 'False' || !!answers.SplitOrMergeLesionName) && lesionType !== 2) || (qs.QuestionMark === 10 && (isCurrentTaskAdd === 'False' || !!answers.SplitOrMergeLesionName))"
                @change="((val) => { formItemChange(val, qs) })">
                <template v-if="(qs.QuestionMark === 0 || qs.QuestionMark === 1) && qs.Unit" slot="append">
                  {{ $fd('ValueUnit', parseInt(qs.Unit)) }}
                </template>
                <svg-icon v-if="qs.ShowChartTypeEnum > 0" icon-class="readingChart" class="svg-icon svg-readingChart"
                  @click.stop="(e) => handleReadingChart({
                    e,
                    data: {
                      TableQuestionId: qs.Id,
                      RowIndex: questionForm.RowIndex,
                      QuestionName: qs.QuestionName
                    }
                  })" />
              </el-input>

            </div>

          </template>
          <!-- 多行文本输入框 -->
          <el-input v-if="qs.Type === 'textarea'" v-model="questionForm[qs.Id]" type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }" maxlength="500" :disabled="!isCurrentTask || readingTaskState >= 2"
            @change="((val) => { formItemChange(val, qs) })" />
          <!-- 下拉框 -->

          <el-select v-if="qs.Type === 'select'" v-model="questionForm[qs.Id]" filterable
            :placeholder="qs.QuestionMark === 8 ? $t('common:placeholder:selectorsearch') : $t('common:placeholder:select')"
            :disabled="!isCurrentTask || readingTaskState >= 2 || qs.QuestionMark === 0 || qs.QuestionMark === 1 || qs.QuestionMark === 2 || qs.QuestionMark === 5 || (qs.QuestionMark === 6 && (isCurrentTaskAdd === 'False' || (isCurrentTaskAdd === 'True' && !questionForm.IsCanEditPosition) || !!answers.SplitOrMergeLesionName)) || (qs.QuestionMark === 8 && (isCurrentTaskAdd === 'False' || !!answers.SplitOrMergeLesionName)) || (qs.QuestionMark === 10 && (isCurrentTaskAdd === 'False' || (isCurrentTaskAdd === 'True' && !questionForm.IsCanEditPosition) || !!answers.SplitOrMergeLesionName))"
            @change="((val) => { formItemChange(val, qs) })">
            <template v-if="qs.QuestionMark === 8" #prefix>
              <span style="padding-left: 5px;">
                <i class="el-icon-search" />
              </span>
            </template>
            <template v-if="qs.TableQuestionType === 1">
              <el-option v-for="item in organList" :key="item.Id" :label="item[qs.DataTableColumn]"
                :value="item[qs.DataTableColumn]" />
            </template>
            <template v-else-if="qs.DictionaryCode && qs.QuestionMark !== 7">
              <el-option v-for="item of $d[qs.DictionaryCode]" :key="item.id" :value="item.value" :label="item.label" />
            </template>
            <template v-else>
              <el-option v-for="val in qs.TypeValue.split('|')" :key="val" :label="val" :value="val" />
            </template>

          </el-select>
          <!-- 单选 -->
          <el-radio-group v-if="qs.Type === 'radio'" v-model="questionForm[qs.id]"
            :disabled="!isCurrentTask || readingTaskState >= 2">
            <el-radio v-for="val in qs.options.split('|')" :key="val" :label="val">
              {{ val }}
            </el-radio>
          </el-radio-group>
          <template v-if="qs.QuestionMark === 20 && qs.Type === 'calculation'">
            <div style="display: flex;flex-direction: row;justify-content: flex-start;">
              <div style="display: flex;justify-content: space-between;">
                <el-input v-if="qs.Type === 'calculation'" v-model="questionForm[qs.Id]" disabled style="width:120px;">
                  <template v-if="qs.Unit" slot="append">
                    {{ $fd('ValueUnit', parseInt(qs.Unit)) }}
                  </template>
                </el-input>
                <svg-icon v-if="qs.ShowChartTypeEnum > 0" icon-class="readingChart" class="svg-icon svg-readingChart"
                  @click.stop="(e) => handleReadingChart({
                    e,
                    data: {
                      TableQuestionId: qs.Id,
                      RowIndex: questionForm.RowIndex,
                      QuestionName: qs.QuestionName
                    }
                  })" />
              </div>

              <!-- <span style="color:#409eff;cursor: pointer" @click="previewImages(answers.RowId)">
                {{ $t('trials:lugano:button:suvscreenshot') }}
              </span> -->
              <el-button v-if="!isBaseLineTask" type="text" @click="previewImages(answers.RowId)">{{
                $t('trials:lugano:button:suvscreenshot') }}</el-button>
            </div>
          </template>
          <div style="display: flex;justify-content: space-between;"
            v-else-if="qs.Type === 'calculation' && qs.QuestionMark !== 20">
            <el-input v-model="questionForm[qs.Id]" disabled>
              <template v-if="qs.Unit" slot="append">
                {{ $fd('ValueUnit', parseInt(qs.Unit)) }}
              </template>
            </el-input>
            <svg-icon v-if="qs.ShowChartTypeEnum > 0" icon-class="readingChart" class="svg-icon svg-readingChart"
              @click.stop="(e) => handleReadingChart({
                e,
                data: {
                  TableQuestionId: qs.Id,
                  RowIndex: questionForm.RowIndex,
                  QuestionName: qs.QuestionName
                }
              })" />
          </div>

        </el-form-item>
      </template>

    </div>

    <div v-if="isCurrentTask && readingTaskState < 2" class="base-dialog-footer"
      style="text-align:right;margin-top:10px;">

      <!-- 清除标记  -->
      <el-button v-if="questionForm.OtherMeasureData" size="mini" @click="handleDeleteMeasureData">
        {{ $t('trials:reading:button:removeMark') }}
      </el-button>
      <!-- 删除 -->
      <el-button v-if="isCurrentTaskAdd !== 'False'" size="mini" @click="handleDelete">
        {{ $t('common:button:delete') }}
      </el-button>
      <!-- 保存 -->
      <el-button size="mini" :loading="saveLoading" :disabled="saveLoading" @click="handleSave">
        {{ $t('common:button:save') }}
      </el-button>
    </div>
  </el-form>
</template>
<script>
import { submitTableQuestion, deleteReadingRowAnswer } from '@/api/trials'
// import { uploadPrintscreen } from '@/api/reading'
import store from '@/store'
import { getToken } from '@/utils/auth'
import FusionEvent from './FusionEvent'
export default {
  name: 'MeasurementForm',
  props: {
    questions: {
      type: Array,
      default() { return [] }
    },
    answers: {
      type: Object,
      default() { return {} }
    },
    lesionType: {
      type: Number,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    parentQsId: {
      type: String,
      required: true
    },
    isCurrentTask: {
      type: Boolean,
      required: true
    },
    readingTaskState: {
      type: Number,
      required: true
    },
    isBaseLineTask: {
      type: Boolean,
      required: true
    },
    orderMark: {
      type: String,
      default: ''
    },
    questionName: {
      type: String,
      required: true
    },
    rowIndex: {
      type: String,
      required: true
    },
    tableQuestions: {
      type: Array,
      default() { return [] }
    }
  },
  data() {
    return {
      questionForm: {},
      loading: false,
      trialId: '',
      organList: [],
      originalQuestionForm: {},
      isRender: false,
      toolType: '',
      lesionName: '',
      isCurrentTaskAdd: 'False',
      splitOrMergeLesionName: '',
      lesionMark: '',
      deleteInfo: null,
      pictureBaseStr: '',
      currentMarkTool: '',
      firstRenderAnnotation: true,
      isInsideVolume: true,
      saveLoading: false
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.initForm()
  },
  beforeDestroy() {

  },
  methods: {
    handleReadingChart(e) {
      this.$emit('handleReadingChart', e)
    },
    async initForm(isRerender = false) {
      const loading = this.$loading({ fullscreen: true })
      this.questions.forEach(item => {
        if (item.QuestionClassify === 0) {
          var val = this.answers[item.Id]
          if (item.DictionaryCode) {
            val = isNaN(parseInt(this.answers[item.Id])) ? this.answers[item.Id] : parseInt(this.answers[item.Id])
          }
          if (this.isBaseLineTask && item.QuestionMark === 7 && this.lesionType === 0) {
            val = 0
          }
          if (this.isBaseLineTask && item.QuestionMark === 7 && this.lesionType === 1) {
            val = 0
          }
          if (!isRerender || (isRerender && item.QuestionMark !== 20)) {
            this.$set(this.questionForm, item.Id, val)
          }
        }
      })
      this.$set(this.questionForm, 'MeasureData', this.answers.MeasureData ? JSON.parse(this.answers.MeasureData) : '')
      if (!isRerender) {
        this.$set(this.questionForm, 'OtherMeasureData', this.answers.OtherMeasureData ? JSON.parse(this.answers.OtherMeasureData) : '')
      }
      this.$set(this.questionForm, 'RowIndex', this.answers.RowIndex ? this.answers.RowIndex : '')
      this.$set(this.questionForm, 'RowId', this.answers.RowId ? this.answers.RowId : '')
      this.$set(this.questionForm, 'OrganInfoId', this.answers.OrganInfoId ? this.answers.OrganInfoId : '')

      // saveTypeEnum 0：未保存过（新建病灶）；1：已保存，信息不完整（随访初始化病灶/分裂病灶，通过状态判断）；2：已保存，信息完整
      // var lesionState = this.getQuestionVal(7)
      if (!isRerender) {
        if (this.questionForm.RowId) {
          this.$set(this.questionForm, 'saveTypeEnum', 2)
        } else {
          this.$set(this.questionForm, 'saveTypeEnum', 0)
        }
      }
      this.$set(this.questionForm, 'IsCanEditPosition', this.answers.IsCanEditPosition === 'True')
      this.$set(this.questionForm, 'IsDicomReading', this.answers.IsDicomReading !== 'False')

      this.toolType = this.questionForm.OtherMeasureData ? this.questionForm.OtherMeasureData.type : ''
      this.currentMarkTool = this.questionForm.OtherMeasureData ? this.questionForm.OtherMeasureData.type : this.answers.OtherMarkTool
      if (!this.questionForm.LesionType) {
        this.$set(this.questionForm, 'LesionType', this.lesionType)
      }
      this.lesionName = this.getLesionInfo(this.orderMark, this.rowIndex)
      this.isCurrentTaskAdd = this.answers.IsCurrentTaskAdd ? this.answers.IsCurrentTaskAdd : 'True'
      this.lesionMark = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
      this.originalQuestionForm = { ...this.questionForm }
      // this.lesionType === 0 && this.questionForm.MeasureData
      if (this.answers.measureObj) {
        await this.setMeasureData(this.answers.measureObj, true)
      } else {
        if (this.questionForm.MeasureData) {
          // 十字线工具 且是靶病灶  器官只能是淋巴结类型
          // if (this.answers.MarkTool === 'Bidirectional') {
          //   this.organList = []
          //   await this.getOrganInfoList(1)
          // } else if (this.answers.MarkTool === 'Length') {
          // // 直径测量工具 且是靶病灶  器官只能是非淋巴结类型
          //   this.organList = []
          //   await this.getOrganInfoList(0)
          // } else {
          //   this.organList = []
          //   await this.getOrganInfoList()
          // }
          this.organList = []
          await this.getOrganInfoList()
        } else {
          this.organList = []
          await this.getOrganInfoList()
        }
      }

      // 首次分裂的病灶默认状态为空时，设置默认值为存在
      if (this.answers.IsFristAdd === 'True' && this.answers.SplitOrMergeType === '0' && isNaN(parseInt(this.getQuestionVal(7)))) {
        const stateId = this.getQuestionId(7)
        this.$set(this.questionForm, stateId, 0)
      }
      var isLymphLesion = this.getQuestionVal(2)
      isLymphLesion = !isNaN(parseInt(isLymphLesion)) ? parseInt(isLymphLesion) : null
      const lesionPart = this.getQuestionVal(8)
      const lesionOrgan = this.getQuestionVal(6)
      const suvMax = this.getQuestionVal(20)
      this.$emit('resetQuestions', { isLymphLesion, lesionPart, lesionOrgan, suvMax, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })
      this.isRender = true
      loading.close()
    },
    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
    },
    getLesionInfo(orderMark, rowIndex) {
      var arr = []
      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}`
        arr.push(lessionName)
      } else {
        lessionName = `${orderMark}${String(x).padStart(2, '0')}`
        arr.push(lessionName)
      }
      if (this.answers.SplitOrMergeLesionName && parseInt(this.answers.SplitOrMergeType) === 0) {
        arr.push(`(Split from ${this.answers.SplitOrMergeLesionName})`)
      }
      return arr.join(' ')
    },
    getQuestionId(questionMark) {
      var idx = this.questions.findIndex(i => i.QuestionMark === questionMark)
      if (idx > -1) {
        return this.questions[idx].Id
      } else {
        return ''
      }
    },
    getOrganInfoList(isLymphNodes = null) {
      return new Promise(async resolve => {
        if (!sessionStorage.getItem('organList')) {
          await store.dispatch('reading/getOrganInfo', this.visitTaskId)
        }
        var organList = sessionStorage.getItem('organList') ? JSON.parse(sessionStorage.getItem('organList')) : []
        var idx = organList.findIndex(i => i.LesionType === this.lesionType)
        if (idx > -1) {
          organList = organList[idx].OrganList

          if (!isNaN(parseInt(isLymphNodes))) {
            this.organList = organList.filter((item) => item.IsLymphNodes === parseInt(isLymphNodes))
          } else {
            this.organList = organList
          }
        }
        resolve()
      })
    },
    async lesionTypeChange(v) {
      this.$emit('determineExistsUnsavedLession', async val => {
        if (val) {
          // 基线时，靶病灶只能用直径和长短径标注，非dicom文件的标注不能作为靶病灶
          //
          if ((this.isBaseLineTask || this.questionForm.IsDicomReading === false) && v === 0) {
            // 当前病灶不允许设置为靶病灶
            this.$confirm(this.$t(' trials:reading:warnning:msg15'), {
              type: 'warning',
              distinguishCancelAndClose: true
            })
              .then(() => { })
              .catch(() => { })
            this.$set(this.questionForm, 'LesionType', this.originalQuestionForm.LesionType)
            return
          }
          //  判断是否超过该病灶类型个数的最大值
          var idx = this.tableQuestions.findIndex(item => item.LesionType === v)
          if (idx > -1 && !!this.tableQuestions[idx].MaxQuestionCount && this.tableQuestions[idx].MaxQuestionCount <= this.tableQuestions[idx].TableQuestions.Answers.length) {
            let msg = this.$t('trials:reading:warnning:msg14')
            msg = msg.replace('xxx', this.tableQuestions[idx].MaxQuestionCount)
            this.$confirm(msg, {
              type: 'warning',
              showCancelButton: false,
              callback: action => { }
            })
            this.$set(this.questionForm, 'LesionType', this.originalQuestionForm.LesionType)
            return
          }

          var arr = []
          this.questionForm[this.getQuestionId(8)] = ''
          this.questionForm[this.getQuestionId(5)] = ''
          this.questionForm[this.getQuestionId(10)] = ''// 部位描述
          this.questionForm[this.getQuestionId(4)] = ''
          this.questionForm[this.getQuestionId(6)] = ''
          this.questionForm[this.getQuestionId(2)] = ''
          this.questions.forEach(item => {
            item.Answer = this.questionForm[item.Id] ? this.questionForm[item.Id] : ''
            arr.push(item)
          })
          // var obj = { questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, visitTaskId: this.visitTaskId, lesionType: this.lesionType }
          if (this.questionForm.OtherMeasureData) {
            FusionEvent.$emit('imageLocation', { otherMeasureData: this.questionForm.OtherMeasureData })
          }
          var type = null
          if (this.questionForm.RowId) {
            type = 1
          } else {
            type = 0
          }
          var suvMax = this.getQuestionVal(20)
          this.$emit('changeLesionType', { questionForm: arr, oldLesionType: this.lesionType, newLesionType: v, rowIndex: this.questionForm.RowIndex, questionId: this.parentQsId, suvMax: suvMax, otherMeasureData: this.questionForm.OtherMeasureData, type, rowId: this.questionForm.RowId })
        } else {
          this.$set(this.questionForm, 'LesionType', this.originalQuestionForm.LesionType)
        }
      })
    },
    deleteLesionInfo() {
      return new Promise((resolve, reject) => {
        const loading = this.$loading({ fullscreen: true })
        var param = {
          visitTaskId: this.visitTaskId,
          questionId: this.parentQsId,
          rowId: this.questionForm.RowId
        }
        deleteReadingRowAnswer(param)
          .then(async res => {
            if (res.IsSuccess) {

            }
            loading.close()
            resolve()
          }).catch(() => {
            loading.close()
            reject()
          })
      })
    },
    async formItemChange(v, question) {
      if (question.QuestionMark === 8 && question.RelationQuestions.length > 0) {
        // 当选择部位时，联动器官、位置、是否淋巴结问题答案
        var index = this.organList.findIndex(item => item[question.DataTableColumn] === v)
        if (index > -1) {
          var selected = this.organList[index]
          question.RelationQuestions.map(qs => {
            var val = selected[qs.DataTableColumn]
            this.$set(this.questionForm, qs.Id, val)
          })
          this.$set(this.questionForm, 'OrganInfoId', selected.OrganInfoId)
          this.$set(this.questionForm, 'IsCanEditPosition', selected['IsCanEditPosition'])
        } else {
          question.RelationQuestions.map(qs => {
            this.$set(this.questionForm, qs.Id, '')
          })
        }
      }
      // saveTypeEnum 0：未保存过（新建病灶）；1：已保存，信息不完整（随访初始化病灶/分裂病灶，通过状态判断）；2：已保存，信息完整
      if (this.questionForm.RowId) {
        this.$set(this.questionForm, 'saveTypeEnum', 1)
      } else {
        this.$set(this.questionForm, 'saveTypeEnum', 0)
      }
      var isLymphLesion = this.getQuestionVal(2)
      isLymphLesion = !isNaN(parseInt(isLymphLesion)) ? parseInt(isLymphLesion) : null
      const lesionPart = this.getQuestionVal(8)
      const lesionOrgan = this.getQuestionVal(6)
      const suvMax = this.getQuestionVal(20)
      this.$emit('resetQuestions', { isLymphLesion, lesionPart, lesionOrgan, suvMax, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })
    },
    setMeasureData(measureData, isInit = false) {
      return new Promise(resolve => {
        if (measureData.data.isHandleOutsideImage) {
          this.setOutsideMeasuredData(measureData)
        } else {
          this.isInsideVolume = true

          if (measureData) {
            // 获取SUVmax(20)
            var SUVmax = measureData.suvMax ? measureData.suvMax : null
            var suvObj = this.questions.find(i => i.QuestionMark === 20)
            this.$set(this.questionForm, suvObj.Id, SUVmax)
            var data = {}
            measureData.data.data.remark = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
            // measureData.data.data.studyId = measureData.studyId
            // measureData.data.data.seriesId = measureData.seriesId
            // measureData.data.data.instanceId = measureData.instanceId
            // measureData.data.data.viewportId = measureData.viewportId
            // measureData.data.data.questionId = this.parentQsId
            // measureData.data.data.rowIndex = this.questionForm.RowIndex
            data = {
              // OtherStudyId: measureData.studyId,
              // OtherSeriesId: measureData.seriesId,
              // OtherInstanceId: measureData.instanceId,
              OtherMeasureData: measureData.data,
              QuestionId: this.parentQsId,
              RowIndex: this.questionForm.RowIndex,
              RowId: this.questionForm.RowId,
              VisitTaskId: this.visitTaskId,
              OrderMarkName: measureData.data.data.remark
            }
            FusionEvent.$emit('addOrUpdateAnnotations', { data })
          }
          // if (!isInit) {
          //   // if (this.questionForm.RowId) {
          //   //   this.$set(this.questionForm, 'saveTypeEnum', 1)
          //   // } else {
          //   //   this.$set(this.questionForm, 'saveTypeEnum', 0)
          //   // }
          //   // saveTypeEnum 0：未保存过（新建病灶）；1：已保存，信息不完整（随访初始化病灶/分裂病灶，通过状态判断）
          //   if (this.questionForm.OtherMeasureData) {
          //     var annotation = Object.assign({}, this.questionForm.OtherMeasureData)

          //     if (annotation && this.firstRenderAnnotation) {
          //       for (const k in annotation.data.cachedStats) {
          //         if (annotation.data.cachedStats[k].pointsInShape.length !== 0) {
          //           this.firstRenderAnnotation = false
          //           break
          //         }
          //       }
          //     }
          //   } else {
          //     this.firstRenderAnnotation = false
          //   }
          //   if (!this.firstRenderAnnotation) {
          //     if (this.questionForm.RowId) {
          //       this.$set(this.questionForm, 'saveTypeEnum', 1)
          //     } else {
          //       this.$set(this.questionForm, 'saveTypeEnum', 0)
          //     }
          //   } else {
          //     this.$set(this.questionForm, 'saveTypeEnum', 2)
          //     this.$emit('close')
          //   }
          // }
          if (!isInit) {
            // saveTypeEnum 0：未保存过（新建病灶）；1：已保存，信息不完整（随访初始化病灶/分裂病灶，通过状态判断）
            if (this.questionForm.RowId) {
              if (this.questionForm.OtherMeasureData && this.firstRenderAnnotation) {
                var annotation = Object.assign({}, this.questionForm.OtherMeasureData)

                if (annotation && this.firstRenderAnnotation) {
                  for (const k in annotation.data.cachedStats) {
                    if (annotation.data.cachedStats[k].pointsInShape.length !== 0) {
                      this.firstRenderAnnotation = false
                      break
                    }
                  }
                }
              }
              // var lesionState = this.getQuestionVal(7)
              if (this.firstRenderAnnotation) {
                this.$set(this.questionForm, 'saveTypeEnum', 2)
              } else {
                this.$set(this.questionForm, 'saveTypeEnum', 1)
              }
            } else {
              this.$set(this.questionForm, 'saveTypeEnum', 0)
            }
          }
          this.$set(this.questionForm, 'OtherMeasureData', measureData.data)
          var isLymph = this.getQuestionVal(2)
          isLymph = !isNaN(parseInt(isLymph)) ? parseInt(isLymph) : null
          const lesionPart = this.getQuestionVal(8)
          const lesionOrgan = this.getQuestionVal(6)
          var suvMax = this.getQuestionVal(20)
          this.$emit('resetQuestions', { isLymphLesion: isLymph, lesionPart, lesionOrgan, suvMax, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })
          this.toolType = measureData.type
          if (this.questionForm.MeasureData) {
            // if (measureData.type === 'Bidirectional') {
            //   this.organList = []
            //   this.getOrganInfoList(1)
            // } else if (measureData.type === 'Length') {
            //   // 直径测量工具 且是靶病灶  器官只能是非淋巴结类型
            //   this.organList = []
            //   this.getOrganInfoList(0)
            // } else {
            //   this.organList = []
            //   this.getOrganInfoList()
            // }
            this.organList = []
            this.getOrganInfoList()
          } else {
            this.organList = []
            this.getOrganInfoList()
          }
        }
        resolve()
      })
    },
    setOutsideMeasuredData(measureData) {
      if (this.isInsideVolume === false) {
        return
      }
      this.isInsideVolume = false
      var suvObj = this.questions.find(i => i.QuestionMark === 20)
      this.$set(this.questionForm, suvObj.Id, '')
      if (this.questionForm.RowId) {
        this.$set(this.questionForm, 'saveTypeEnum', 1)
      } else {
        this.$set(this.questionForm, 'saveTypeEnum', 0)
      }
      this.$set(this.questionForm, 'OtherMeasureData', measureData.data)
      var isLymph = this.getQuestionVal(2)
      isLymph = !isNaN(parseInt(isLymph)) ? parseInt(isLymph) : null
      const lesionPart = this.getQuestionVal(8)
      const lesionOrgan = this.getQuestionVal(6)
      var suvMax = this.getQuestionVal(20)
      this.$emit('resetQuestions', { isLymphLesion: isLymph, lesionPart, lesionOrgan, suvMax, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })
      if (this.questionForm.MeasureData) {
        this.organList = []
        this.getOrganInfoList()
      } else {
        this.organList = []
        this.getOrganInfoList()
      }
    },
    returnFloat(num) {
      if (num) return
      var value = Math.round(parseFloat(num) * 100) / 100
      var s = value.toString().split('.')
      if (s.length === 1) {
        value = value.toString() + '.00'
        return value
      }
      if (s.length > 1) {
        if (s[1].length < 2) {
          value = value.toString() + '0'
        }
        return value
      }
    },
    getQuestionVal(questionMark) {
      var idx = this.questions.findIndex(i => i.QuestionMark === questionMark)
      if (idx > -1) {
        var questionId = this.questions[idx].Id
        var answer = this.questionForm[questionId] ? this.questionForm[questionId] : this.answers[questionId]
        return answer
      } else {
        return ''
      }
    },
    setDeleteInfo(deleteInfo) {
      this.deleteInfo = deleteInfo
    },
    deleteOldLesion(questionId, rowId) {
      return new Promise((resolve, reject) => {
        var param = {
          visitTaskId: this.visitTaskId,
          questionId: questionId,
          rowId: rowId
        }
        deleteReadingRowAnswer(param)
          .then(async res => {
            resolve()
          }).catch(() => {
          })
      })
    },
    async uploadScreenshots(fileName, file) {
      try {
        file = this.convertBase64ToBlob(file)
        var trialId = this.$route.query.trialId
        var subjectId = this.$route.query.trialId
        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) {
      var base64Arr = imageEditorBase64.split(',')
      var imgtype = ''
      var base64String = ''
      if (base64Arr.length > 1) {
        // 如果是图片base64，去掉头信息
        base64String = base64Arr[1]
        imgtype = base64Arr[0].substring(
          base64Arr[0].indexOf(':') + 1,
          base64Arr[0].indexOf(';')
        )
      }
      // 将base64解码
      var bytes = atob(base64String)
      // var bytes = base64;
      var bytesCode = new ArrayBuffer(bytes.length)
      // 转换为类型化数组
      var byteArray = new Uint8Array(bytesCode)

      // 将base64转换为ascii码
      for (var i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i)
      }

      // 生成Blob对象（文件对象）
      return new Blob([bytesCode], { type: imgtype })
    },
    handleSave() {
      if (this.saveLoading) return
      this.saveLoading = true
      this.$refs.measurementForm.validate(async valid => {
        if (!valid) {
          this.saveLoading = false
          return
        }
        const loading = this.$loading({ fullscreen: true })
        if (!this.isInsideVolume) {
          // this.$alert('当前标记在图像外，不允许保存！', '提示', {
          //   callback: action => {}
          // })
          loading.close()
          // 当前标记在图像外，不允许保存！
          this.$confirm(this.$t('trials:reading:lugano:warnning:outsideVolume'), {
            type: 'warning',
            showCancelButton: false,
            callback: action => { }
          })

          this.saveLoading = false
          return
        }
        // 消失、无法评估状态的病灶限制不能测量SUV值
        var lesionState = this.getQuestionVal(7)
        lesionState = parseInt(lesionState)
        if ((lesionState === 2 || lesionState === 3) && this.questionForm.OtherMeasureData) {
          loading.close()
          // 评估状态为无法评估或消失的病灶不能测量SUV值！
          this.$confirm(this.$t('trials:reading:lugano:warnning:cannotMeasuredSUV'), {
            type: 'warning',
            showCancelButton: false,
            callback: action => { }
          })
          this.saveLoading = false
          return
        }
        // suv测量值可以测量为0，但不能与病灶、肝脏、纵隔血池绑定。
        if (this.questionForm.OtherMeasureData) {
          var suvmax = this.getQuestionVal(20)
          if (suvmax === 0) {
            loading.close()
            // 当前病灶suv测量值为0，不允许保存！
            this.$confirm(this.$t('trials:reading:lugano:warnning:suvis0'), {
              type: 'warning',
              showCancelButton: false,
              callback: action => { }
            })
            this.saveLoading = false
            return
          }
        }

        var otherMeasureData = this.questionForm.OtherMeasureData ? Object.assign({}, this.questionForm.OtherMeasureData) : null
        if (otherMeasureData) {
          for (const k in otherMeasureData.data.cachedStats) {
            otherMeasureData.data.cachedStats[k].pointsInShape = []
          }
        }
        FusionEvent.$emit('getScreenshots', { otherMeasureData: this.questionForm.OtherMeasureData }, async val => {
          // 靶病灶状态为0（存在）时，一定存在长径或者长短径（长径、十字线 ）
          // 普通靶病灶：长径大于10mm且不小于2倍层厚（基线校验）
          // 淋巴结靶病灶：短径大于15mm且不小于2倍层厚（基线校验）
          var picturePath = ''
          if (val && otherMeasureData && this.questionForm.IsDicomReading) {
            var pictureObj = await this.uploadScreenshots(`${new Date().getTime()}`, val)
            picturePath = pictureObj.isSuccess ? this.$getObjectName(pictureObj.result.url) : ''
          }
          var answers = []
          var 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 this.questionForm) {
            if (reg.test(k)) {
              if (answers.findIndex(i => i.tableQuestionId === k) === -1) {
                answers.push({ tableQuestionId: k, answer: this.questionForm[k] })
              }
            }
          }
          var params = {
            computationTrigger: -3,
            questionId: this.parentQsId,
            rowId: this.questionForm.RowId,
            rowIndex: this.answers.RowIndex,
            visitTaskId: this.visitTaskId,
            trialId: this.trialId,
            otherMeasureData: otherMeasureData ? JSON.stringify(otherMeasureData) : '',
            answerList: answers,
            isCanEditPosition: this.questionForm.IsCanEditPosition,
            otherStudyId: this.$route.query.studyId,
            // otherStudyId: otherMeasureData ? otherMeasureData.data.studyId : '',
            // otherSeriesId: otherMeasureData ? otherMeasureData.data.seriesId : '',
            otherInstanceId: otherMeasureData ? otherMeasureData.data.instanceId : '',
            // numberOfFrames: measureData && !isNaN(parseInt(this.questionForm.MeasureData.frame)) ? parseInt(this.questionForm.MeasureData.frame) : 0,
            otherPicturePath: picturePath,
            organInfoId: this.questionForm.OrganInfoId,
            ptSeriesId: otherMeasureData ? this.$route.query.ptseriesId : '',
            ctSeriesId: otherMeasureData ? this.$route.query.ctseriesId : ''
          }
          if (this.questionForm.IsDicomReading === false) {
            params.isDicomReading = false
          }
          if (this.deleteInfo) {
            await this.deleteOldLesion(this.deleteInfo.questionId, this.deleteInfo.rowId)
            this.deleteInfo = null
            params.rowId = ''
          }
          try {
            const res = await submitTableQuestion(params)
            if (res.IsSuccess) {
              this.currentMarkTool = otherMeasureData ? otherMeasureData.type : ''
              this.$set(this.questionForm, 'saveTypeEnum', 2)
              this.originalQuestionForm = { ...this.questionForm }
              var isLymphLesion = this.getQuestionVal(2)
              isLymphLesion = isLymphLesion ? parseInt(isLymphLesion) : null
              var lesionOrgan = this.getQuestionVal(6)
              this.$set(this.questionForm, 'RowId', res.Result.RowId)
              const lesionPart = this.getQuestionVal(8)
              const suvMax = this.getQuestionVal(20)
              this.$emit('resetQuestions', { isLymphLesion, lesionPart, lesionOrgan, suvMax, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })

              FusionEvent.$emit('resetSuvQuestions')
              window.opener.postMessage({ type: 'petctLesionUpdate' }, window.location)
              this.$emit('close')

              this.$message({ message: this.$t('common:message:savedSuccessfully'), type: 'success', duration: 2000 })
            }
            loading.close()
            this.saveLoading = false
          } catch (e) {
            console.log(e)
            loading.close()
            this.saveLoading = false
          }
        })
      })
    },
    async handleDeleteMeasureData() {
      // 是否确认清除标记？
      const confirm = await this.$confirm(
        this.$t('trials:reading:warnning:msg47'),
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      this.organList = []
      await this.getOrganInfoList()
      // 重置SUV
      var suvId = this.getQuestionId(20)
      this.$set(this.questionForm, suvId, '')
      // saveTypeEnum 0：未保存过（新建病灶）；1：已保存，信息不完整（随访初始化病灶/分裂病灶，通过状态判断）
      if (this.questionForm.RowId) {
        this.$set(this.questionForm, 'saveTypeEnum', 1)
      } else {
        this.$set(this.questionForm, 'saveTypeEnum', 0)
      }
      FusionEvent.$emit('removeAnnotation', { otherMeasureData: this.questionForm.OtherMeasureData, type: 'clear' })
      // await store.dispatch('reading/removeMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.questionForm.MeasureData, questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex })

      // Store.$emit('updateImage', this.questionForm.MeasureData.instanceId)
      var isLymphLesion = this.getQuestionVal(2)
      isLymphLesion = !isNaN(parseInt(isLymphLesion)) ? parseInt(isLymphLesion) : null
      const lesionPart = this.getQuestionVal(8)
      const lesionOrgan = this.getQuestionVal(6)

      if (!this.questionForm.IsDicomReading) {

      }
      this.$set(this.questionForm, 'IsDicomReading', true)

      this.$set(this.questionForm, 'OtherMeasureData', '')
      let anwsers = null
      if (this.answers.measureObj) {
        anwsers = Object.assign({ measureObj: '' }, this.questionForm)
      } else {
        anwsers = Object.assign({}, this.questionForm)
      }
      var suvMax = this.getQuestionVal(20)
      this.$emit('resetQuestions', { isLymphLesion, lesionPart, lesionOrgan, suvMax, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: anwsers })
      this.isInsideVolume = true
    },
    async clearMeasurement() {
      this.organList = []
      await this.getOrganInfoList()
      // 重置SUV
      var suvId = this.getQuestionId(20)
      this.$set(this.questionForm, suvId, '')
      // saveTypeEnum 0：未保存过（新建病灶）；1：已保存，信息不完整（随访初始化病灶/分裂病灶，通过状态判断）
      if (this.questionForm.RowId) {
        this.$set(this.questionForm, 'saveTypeEnum', 1)
      } else {
        this.$set(this.questionForm, 'saveTypeEnum', 0)
      }
      FusionEvent.$emit('removeAnnotation', { otherMeasureData: this.questionForm.OtherMeasureData, type: 'clear' })
      var isLymphLesion = this.getQuestionVal(2)
      isLymphLesion = !isNaN(parseInt(isLymphLesion)) ? parseInt(isLymphLesion) : null
      const lesionPart = this.getQuestionVal(8)
      const lesionOrgan = this.getQuestionVal(6)

      if (!this.questionForm.IsDicomReading) {

      }
      this.$set(this.questionForm, 'IsDicomReading', true)

      this.$set(this.questionForm, 'OtherMeasureData', '')
      let anwsers = null
      if (this.answers.measureObj) {
        anwsers = Object.assign({ measureObj: '' }, this.questionForm)
      } else {
        anwsers = Object.assign({}, this.questionForm)
      }
      var suvMax = this.getQuestionVal(20)
      this.$emit('resetQuestions', { isLymphLesion, lesionPart, lesionOrgan, suvMax, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: anwsers })
      this.isInsideVolume = true
    },
    async handleDelete() {
      const confirm = await this.$confirm(
        this.$t('trials:reading:warnning:msg48'),
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      if (this.questionForm.RowId) {
        const loading = this.$loading({ fullscreen: true })
        try {
          var param = {
            visitTaskId: this.visitTaskId,
            questionId: this.parentQsId,
            rowId: this.questionForm.RowId
          }
          const res = await deleteReadingRowAnswer(param)
          if (res.IsSuccess) {
            if (this.questionForm.IsDicomReading && this.questionForm.OtherMeasureData) {
              FusionEvent.$emit('removeAnnotation', { otherMeasureData: this.questionForm.OtherMeasureData, type: 'delete' })
            }
            this.$emit('close', { lesionType: this.lesionType, rowIndex: this.rowIndex, visitTaskId: this.visitTaskId })
            // '删除成功！'
            this.$message.success(this.$t('common:message:deletedSuccessfully'))
            loading.close()
            window.opener.postMessage({ type: 'petctLesionUpdate' }, window.location)
          }
          loading.close()
        } catch (e) {
          console.log(e)
          loading.close()
        }
      } else {
        // 移除新建病灶并关闭窗口
        if (this.questionForm.OtherMeasureData && this.questionForm.IsDicomReading) {
          FusionEvent.$emit('removeAnnotation', { otherMeasureData: this.questionForm.OtherMeasureData })
        }
        this.$emit('close', { lesionType: this.lesionType, rowIndex: this.rowIndex, visitTaskId: this.visitTaskId })
      }
    },
    async handleClose() {
      if (!this.questionForm.RowId) {
        // '当前病灶为新建病灶，未保存。如果关闭窗口，将会删除病灶信息，是否继续？'
        const confirm = await this.$confirm(
          this.$t('trials:reading:warnning:msg49'),
          {
            type: 'warning',
            distinguishCancelAndClose: true
          }
        )
        if (confirm !== 'confirm') return
        // 移除新建病灶并关闭窗口
        if (this.questionForm.OtherMeasureData) {
          FusionEvent.$emit('removeAnnotation', { otherMeasureData: this.questionForm.OtherMeasureData })
        }
        this.$emit('close', { lesionType: this.lesionType, rowIndex: this.rowIndex, visitTaskId: this.visitTaskId })
      } else {
        if (this.questionForm.saveTypeEnum === 1) {
          this.$emit('close')
        } else {
          this.$emit('close')
        }
      }
    },
    previewImages(rowId) {
      var token = getToken()
      var subjectCode = this.$route.query.subjectCode
      var path = `/historyScreenshot?rowId=${rowId}&subjectCode=${subjectCode}&lesionName=${this.lesionName}&TokenKey=${token}`
      FusionEvent.$emit('viewHistoryScreenshot', path)
    }
  }
}
</script>
<style lang="scss" scoped>
.measurement-form {
  ::v-deep .el-form-item__label {
    color: #c3c3c3;
    // text-align: left;
  }

  ::v-deep .el-input .el-input__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-input.is-disabled .el-input__inner {
    background-color: #646464a1;
  }

  ::v-deep .el-input-group__append,
  .el-input-group__prepend {
    padding: 0 10px;
  }

  ::v-deep .el-select.is-disabled .el-input__inner {
    background-color: #646464a1;
  }

  ::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner {
    background-color: #428bca;
    border-color: #428bca;
  }

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

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

  .input-width1 {
    width: calc(100% - 60px) !important;
  }

  .input-width2 {
    width: 100% !important;
  }
}
</style>
