<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="questionName" 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="true"
        >
          <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>
      <el-form-item
        v-for="qs in questions"
        v-show="qs.ShowQuestion!==2"
        :key="qs.Id"
        :label="`${qs.QuestionName}`"
        :prop="qs.Id"
        :rules="qs.QuestionMark===11?[
          { required: (qs.IsRequired === 0 || (qs.IsRequired ===1 && qs.RelevanceId && (questionForm[qs.RelevanceId] === qs.RelevanceValue))) && qs.Type!=='group' && qs.Type!=='summary',
            message: ['radio', 'select', 'checkbox'].includes(qs.Type) ? $t('common:ruleMessage:select') : $t('common:ruleMessage:specify'), trigger: ['blur', 'change']},{validator:validateLesionCount, trigger: ['blur', 'change']}]:[
              { 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 }} -->

        <!-- 输入框    min="1"
              @input="questionForm[qs.Id]=questionForm[qs.Id].replace(/^(0+)|[^\d]+/g,'')"-->
        <template v-if="qs.Type==='input' || qs.Type==='number'">
          <template v-if="qs.QuestionMark===11">
            <el-input
              v-model="questionForm[qs.Id]"
              :disabled="!isCurrentTask || readingTaskState>=2 "
              type="number"

              @focus="focusQs = {...qs}"
              @change="((val)=>{formItemChange(val, qs)})"
            >
              <template v-if="(qs.QuestionMark===0 || qs.QuestionMark===1) && qs.Unit" slot="append">
                {{ $fd('ValueUnit', parseInt(qs.Unit)) }}
              </template>
            </el-input>
          </template>
          <template v-else>
            <el-input
              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') && lesionType !== 2) || qs.QuestionMark === 9 || (qs.QuestionMark === 10 && isCurrentTaskAdd === 'False')"
              @focus="focusQs = {...qs}"
              @change="((val)=>{formItemChange(val, qs)})"
            >
              <template v-if="(qs.QuestionMark===0 || qs.QuestionMark===1) && qs.Unit" slot="append">
                {{ $fd('ValueUnit', parseInt(qs.Unit)) }}
              </template>
            </el-input>
          </template>
        </template>
        <!-- 多行文本输入框 -->
        <el-input
          v-if="qs.Type==='textarea'"
          v-model="questionForm[qs.Id]"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          :disabled="!isCurrentTask || readingTaskState>=2"
          @change="((val)=>{formItemChange(val, qs)})"
        />
        <el-select
          v-if="qs.Type==='select'"
          v-model="questionForm[qs.Id]"
          filterable
          :disabled="((!isBaseLineTask && qs.QuestionMark === 11) || (isBaseLineTask || lesionType === 2) && qs.QuestionMark === 7) || !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)"
          @change="((val)=>{formItemChange(val, qs)})"
        >
          <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 && isBaseLineTask">
            <el-option
              v-for="item of $d[qs.DictionaryCode]"
              :key="item.id"
              :value="item.value"
              :label="item.label"
            />
          </template>
          <template v-else-if="qs.DictionaryCode && qs.QuestionMark === 7 && !isBaseLineTask">
            <el-option
              v-for="item of $d[qs.DictionaryCode]"
              :key="item.id"
              :value="item.value"
              :label="item.label"
            />
          </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>
      </el-form-item>

    </div>
    <div
      v-if="isCurrentTask && readingTaskState<2"
      class="base-dialog-footer"
      style="text-align:right;margin-top:10px;"
    >
      <!-- 清除标记 -->
      <el-button
        v-if="questionForm.MeasureData"
        size="mini"
        style="padding:7px 10px"
        @click="handleDeleteMeasureData"
      >
        {{ $t('trials:reading:button:removeMark') }}
      </el-button>
      <!-- 删除 -->
      <el-button
        v-if="isCurrentTaskAdd !== 'False'"
        size="mini"
        style="margin-left: 5px;padding:7px 10px"
        @click="handleDelete"
      >
        {{ $t('common:button:delete') }}
      </el-button>
      <!-- 保存 -->
      <el-button
        size="mini"
        style="margin-left: 5px;padding:7px 10px"
        @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 DicomEvent from './../DicomEvent'
import store from '@/store'
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: [],
      lesionNameId: '',
      lesionOrganId: '',
      lesionLocId: '',
      originalQuestionForm: {},
      isRender: false,
      toolType: '',
      lesionName: '',
      isCurrentTaskAdd: 'False',
      splitOrMergeLesionName: '',
      lesionMark: '',
      pictureBaseStr: '',
      digitPlaces: 0,
      focusQs: null,
      currentMarkTool: ''
    }
  },

  mounted() {
    this.trialId = this.$route.query.trialId
    this.initForm()
    DicomEvent.$on('handleImageQualityAbnormal', () => {
      this.setState()
    })
  },
  beforeDestroy() {
    DicomEvent.$off('handleImageQualityAbnormal')
  },
  methods: {
    validateLesionCount(rule, value, callback) {
      // const reg = /^[1-9][0-9]?$|^100$/
      // const reg = /^(0+)|[^\d]+/g
      const reg = /^(?:[1-9]|[1-9][0-9])$/
      if (!value) {
        callback(new Error(this.$t('common:ruleMessage:specify')))
      } else if (!reg.test(value) || (parseInt(value) > 99 || parseInt(value) <= 0)) {
        callback(new Error(this.$t('trials:readingPGWC:warnning:msg1')))
      } else if (parseInt(value) > parseInt(this.questionForm.BaseLineLesionNumber)) {
        callback(new Error(this.$t('trials:reading:pcwg:msg6') + this.questionForm.BaseLineLesionNumber))
      } else {
        callback()
      }
    },
    limitInputValidator(rule, value, callback) {
      console.log(this.focusQs)
      if (this.focusQs && !this.isBaseLineTask && this.focusQs.QuestionMark === 11 && (parseInt(value) > parseInt(this.questionForm.BaseLineLesionNumber))) {
        // '基线病灶初始数量为'
        callback(new Error(this.$t('trials:reading:pcwg:msg6') + this.questionForm.BaseLineLesionNumber))
      } else if (this.focusQs && this.focusQs.QuestionMark === 11 && (parseInt(value) > 99 || parseInt(value) <= 0)) {
        callback(new Error(this.$t('trials:readingPGWC:warnning:msg1')))
      } else {
        callback()
      }
    },
    initForm() {
      this.questions.forEach(item => {
        var val = this.answers[item.Id]
        if (item.DictionaryCode) {
          val = this.answers[item.Id] ? Number(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
        }

        this.$set(this.questionForm, item.Id, val)
      })
      this.$set(this.questionForm, 'MeasureData', this.answers.MeasureData ? JSON.parse(this.answers.MeasureData) : '')
      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)

      var lesionNum = this.getQuestionVal(11)
      var idx = this.questions.findIndex(i => i.QuestionMark === 11)
      if (this.questionForm.RowId) {
        if (idx > -1) {
          this.$set(this.questionForm, 'saveTypeEnum', isNaN(parseInt(lesionNum)) ? 1 : 2)
        } else {
          this.$set(this.questionForm, 'saveTypeEnum', isNaN(parseInt(lesionState)) ? 1 : 2)
        }
      } else {
        this.$set(this.questionForm, 'saveTypeEnum', 0)
      }
      this.$set(this.questionForm, 'IsCanEditPosition', this.answers.IsCanEditPosition === 'True')
      this.$set(this.questionForm, 'BaseLineLesionNumber', this.answers.BaseLineLesionNumber)

      this.toolType = this.questionForm.MeasureData ? this.questionForm.MeasureData.type : ''
      this.currentMarkTool = this.questionForm.MeasureData ? this.questionForm.MeasureData.type : this.answers.MarkTool
      if (!this.questionForm.LesionType) {
        this.$set(this.questionForm, 'LesionType', this.lesionType)
      }
      this.lesionNameId = this.getQuestionId(4)
      this.lesionOrganId = this.getQuestionId(5)
      this.lesionLocId = this.getQuestionId(6)

      this.originalQuestionForm = { ...this.questionForm }
      this.lesionType === 0 && this.questionForm.MeasureData
      this.organList = []
      this.getOrganInfoList()
      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.isRender = true
    },
    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 ''
      }
    },
    handleLocation() {
      DicomEvent.$emit('imageLocation', this.questionForm)
    },
    getOrganInfoList(isLymphNodes) {
      return new Promise(async resolve => {
        if (!sessionStorage.getItem('organList')) {
          await store.dispatch('reading/getOrganInfo', this.visitTaskId)
        }
        var 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()
      })
    },
    deleteLesionInfo() {
      return new Promise((resolve, reject) => {
        var param = {
          visitTaskId: this.visitTaskId,
          questionId: this.parentQsId,
          rowIndex: this.questionForm.RowIndex
        }
        deleteReadingRowAnswer(param)
          .then(async res => {
            if (res.IsSuccess) {
              DicomEvent.$emit('getReportInfo', true)
            }
            resolve()
          }).catch(() => {
            reject()
          })
      })
    },
    formItemChange(v, question) {
      if (question.QuestionMark === 11) {
        return
      }
      if (question.QuestionMark === 8 && question.RelationQuestions.length > 0) {
        // 当选择部位时，联动器官、位置、是否淋巴结问题答案
        var index = this.organList.findIndex(item => item[question.DataTableColumn] === v)
        console.log('index', index)
        if (index > -1) {
          var selected = this.organList[index]
          question.RelationQuestions.map(qs => {
            console.log('qs', 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, '')
          })
        }
      }
      if (question.Id === this.lesionOrganId || question.Id === this.lesionLocId) {
        // 设置病灶名称
        this.$set(this.questionForm, this.lesionNameId, `${this.questionForm[this.lesionOrganId]} ${this.questionForm[this.lesionLocId]}`)
      }

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

      const lesionPart = this.getQuestionVal(8)
      const lesionOrgan = this.getQuestionVal(6)
      const lesionState = Number(this.getQuestionVal(7))
      const lesionNum = Number(this.getQuestionVal(11))
      this.$emit('resetQuestions', { lesionPart, lesionOrgan, lesionState, saveTypeEnum: this.questionForm.saveTypeEnum, lesionNum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })
    },

    setMeasureData(measureData, isInit = false) {
      return new Promise(resolve => {
        if (measureData) {
          if (measureData.pictureBaseStr) {
            this.pictureBaseStr = measureData.pictureBaseStr
            measureData.pictureBaseStr = ''
          }

          var data = {}
          if (measureData.isDicomReading === false) {
            this.$set(this.questionForm, 'IsDicomReading', false)
            data = {
              Id: '',
              IsDicomReading: false,
              StudyId: measureData.studyId,
              InstanceId: measureData.instanceId,
              SeriesId: measureData.seriesId,
              MeasureData: measureData,
              QuestionId: this.parentQsId,
              RowIndex: this.questionForm.RowIndex,
              RowId: this.questionForm.RowId,
              VisitTaskId: this.visitTaskId
            }
          } else {
            this.$set(this.questionForm, 'IsDicomReading', true)
            measureData.data.remark = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
            data = {
              Id: '',
              IsDicomReading: true,
              StudyId: measureData.studyId,
              InstanceId: measureData.instanceId,
              SeriesId: measureData.seriesId,
              MeasureData: measureData,
              QuestionId: this.parentQsId,
              RowIndex: this.questionForm.RowIndex,
              RowId: this.questionForm.RowId,
              VisitTaskId: this.visitTaskId,
              OrderMarkName: measureData.data.remark,
              frame: isNaN(parseInt(measureData.frame)) ? 0 : measureData.frame
            }
          }
          store.dispatch('reading/addMeasuredData', { visitTaskId: this.visitTaskId, data: data })

          DicomEvent.$emit('getMeasureData', val => {
            this.pictureBaseStr = val
          })
        }
        if (!isInit) {
          // saveTypeEnum 0：未保存过（新建病灶）；1：已保存，信息不完整（随访初始化病灶/分裂病灶，通过状态判断）
          if (this.questionForm.RowId) {
            this.$set(this.questionForm, 'saveTypeEnum', 1)
          } else {
            this.$set(this.questionForm, 'saveTypeEnum', 0)
          }
        }
        this.$set(this.questionForm, 'MeasureData', measureData)
        const lesionPart = this.getQuestionVal(8)
        const lesionOrgan = this.getQuestionVal(6)
        const lesionState = Number(this.getQuestionVal(7))
        const lesionNum = Number(this.getQuestionVal(11))

        this.$emit('resetQuestions', { lesionPart, lesionOrgan, lesionState, lesionNum, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })
        this.toolType = measureData.type
        DicomEvent.$emit('refreshStudyListMeasureData')
        resolve()
      })
    },
    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
        return this.questionForm[questionId]
      } else {
        return ''
      }
    },
    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}/Visit/${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() {
      this.$refs.measurementForm.validate(async valid => {
        if (!valid) return
        var lesionState = this.getQuestionVal(7)
        var measureData = this.questionForm.MeasureData
        // 非基线
        if (!this.isBaseLineTask) {
          // 新病灶 2
          // 病灶状态为“存在”的新病灶，请使用箭头工具添加标记2
          if (this.lesionType === 2 && lesionState === 2) {
            if (!(measureData && measureData.type === 'ArrowAnnotate')) {
              this.$confirm(this.$t('trials:readingPGWC:warnning:msg2'), {
                type: 'warning',
                showCancelButton: false,
                callback: action => {}
              })
              loading.close()
              return
            }
          }
          // 既往新病灶 3
          // 病灶状态为“存在”的既往新病灶，请使用箭头工具添加标记2
          if (this.lesionType === 3 && lesionState === 2) {
            if (!(measureData && measureData.type === 'ArrowAnnotate')) {
              this.$confirm(this.$t('trials:readingPGWC:warnning:msg3'), {
                type: 'warning',
                showCancelButton: false,
                callback: action => {}
              })
              loading.close()
              return
            }
          }
          // 病灶状态为“良性”的既往新病灶，请使用箭头工具添加标记3
          if (this.lesionType === 3 && lesionState === 3) {
            if (!(measureData && measureData.type === 'ArrowAnnotate')) {
              this.$confirm(this.$t('trials:readingPGWC:warnning:msg4'), {
                type: 'warning',
                showCancelButton: false,
                callback: action => {}
              })
              loading.close()
              return
            }
          }
          // 病灶状态为“消失”的既往新病灶，请使用箭头工具添加标记1
          if (this.lesionType === 3 && lesionState === 1) {
            if (!(measureData && measureData.type === 'ArrowAnnotate')) {
              this.$confirm(this.$t('trials:readingPGWC:warnning:msg5'), {
                type: 'warning',
                showCancelButton: false,
                callback: action => {}
              })
              loading.close()
              return
            }
          }
          // 病灶状态为“不可评估”的既往新病灶，不需要添加标记4
          if (this.lesionType === 3 && lesionState === 4) {
            if (measureData) {
              this.$confirm(this.$t('trials:readingPGWC:warnning:msg6'), {
                type: 'warning',
                showCancelButton: false,
                callback: action => {}
              })
              loading.close()
              return
            }
          }
        }
        const loading = this.$loading({ fullscreen: true })
        DicomEvent.$emit('getScreenshots', async val => {
          var picturePath = ''
          if (val && measureData) {
            var pictureObj = await this.uploadScreenshots(`${new Date().getTime()}`, val)
            picturePath = pictureObj.isSuccess ? 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 = {
            questionId: this.parentQsId,
            rowIndex: this.answers.RowIndex,
            TaskNum: this.answers.TaskNum,
            visitTaskId: this.visitTaskId,
            trialId: this.trialId,
            measureData: measureData ? JSON.stringify(measureData) : '',
            answerList: answers,
            isCanEditPosition: this.questionForm.IsCanEditPosition,
            studyId: measureData ? this.questionForm.MeasureData.studyId : '',
            seriesId: measureData ? this.questionForm.MeasureData.seriesId : '',
            instanceId: measureData ? this.questionForm.MeasureData.instanceId : '',
            blindName: this.answers.BlindName,
            rowId: this.questionForm.RowId,
            numberOfFrames: measureData && !isNaN(parseInt(this.questionForm.MeasureData.frame)) ? parseInt(this.questionForm.MeasureData.frame) : 0,
            picturePath: picturePath,
            organInfoId: this.questionForm.OrganInfoId,
            markTool: measureData ? measureData.type : ''
          }
          submitTableQuestion(params).then(async res => {
            try {
              this.$message.success(this.$t('common:message:savedSuccessfully'))
              this.currentMarkTool = measureData ? measureData.type : ''
              this.$set(this.questionForm, 'saveTypeEnum', 2)
              this.originalQuestionForm = { ...this.questionForm }
              loading.close()
              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 lesionState = Number(this.getQuestionVal(7))
              const lesionNum = Number(this.getQuestionVal(11))

              this.$emit('resetQuestions', { isLymphLesion, lesionPart, lesionOrgan, saveTypeEnum: this.questionForm.saveTypeEnum, lesionState, lesionNum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })
              DicomEvent.$emit('getMeasureData')
              this.$emit('close')
              DicomEvent.$emit('getReportInfo', true)
              DicomEvent.$emit('setMeasuredToolsPassive')
            } catch (e) {
              console.log(e)
            }
          }).catch(() => { loading.close() })
        })
      })
    },
    handleDeleteMeasureData() {
      this.$confirm(this.$t('trials:reading:warnning:msg47'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(async() => {
          if (this.questionForm.RowId) {
            this.$set(this.questionForm, 'saveTypeEnum', 1)
          } else {
            this.$set(this.questionForm, 'saveTypeEnum', 0)
          }
          var remark = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
          await store.dispatch('reading/removeMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.questionForm.MeasureData, questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, orderMarkName: remark })
          DicomEvent.$emit('getMeasureData')
          const lesionPart = this.getQuestionVal(8)
          const lesionOrgan = this.getQuestionVal(6)
          const lesionState = Number(this.getQuestionVal(7))
          const lesionNum = Number(this.getQuestionVal(11))

          this.$set(this.questionForm, 'MeasureData', '')
          let anwsers = null
          if (this.answers.measureObj) {
            anwsers = Object.assign({ measureObj: '' }, this.questionForm)
          } else {
            anwsers = Object.assign({}, this.questionForm)
          }
          this.$emit('resetQuestions', { lesionPart, lesionOrgan, lesionState, lesionNum, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: anwsers })
          DicomEvent.$emit('refreshStudyListMeasureData')
        })
        .catch(() => {})
    },
    handleDelete() {
      this.$confirm(this.$t('trials:reading:warnning:msg48'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(async() => {
          if (this.questionForm.RowId) {
            const loading = this.$loading({ fullscreen: true })
            var param = {
              visitTaskId: this.visitTaskId,
              questionId: this.parentQsId,
              rowId: this.questionForm.RowId
            }
            deleteReadingRowAnswer(param)
              .then(async res => {
                loading.close()
                if (res.IsSuccess) {
                  if (this.questionForm.MeasureData) {
                    var remark = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
                    await store.dispatch('reading/removeMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.questionForm.MeasureData, questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, orderMarkName: remark })
                  }
                  DicomEvent.$emit('getMeasureData')
                  this.$emit('close', { lesionType: this.lesionType, rowIndex: this.rowIndex, visitTaskId: this.visitTaskId })
                  DicomEvent.$emit('getReportInfo', true)
                  this.$message.success(this.$t('common:message:deletedSuccessfully'))
                  loading.close()
                }
              }).catch(() => { loading.close() })
          } else {
            const loading = this.$loading({ fullscreen: true })
            // 移除新建病灶并关闭窗口
            if (this.questionForm.MeasureData) {
              var remark = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
              await store.dispatch('reading/removeMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.questionForm.MeasureData, questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, orderMarkName: remark })
            }

            DicomEvent.$emit('getMeasureData')
            this.$emit('close', { lesionType: this.lesionType, rowIndex: this.rowIndex, visitTaskId: this.visitTaskId })
            DicomEvent.$emit('refreshStudyListMeasureData')
            loading.close()
          }
        })
    },
    handleClose() {
      if (!this.questionForm.RowId) {
        this.$confirm(this.$t('trials:reading:warnning:msg49'), {
          type: 'warning',
          distinguishCancelAndClose: true
        })
          .then(async() => {
            // 移除新建病灶并关闭窗口
            if (this.questionForm.MeasureData) {
              var remark = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
              await store.dispatch('reading/removeMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.questionForm.MeasureData, questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, orderMarkName: remark })
            }
            DicomEvent.$emit('getMeasureData')
            this.$emit('close', { lesionType: this.lesionType, rowIndex: this.rowIndex, visitTaskId: this.visitTaskId })
          })
          .catch(() => {})
      } else {
        if (this.questionForm.isSave === false) {
          // '当前病灶信息有更新，未保存，是否继续？'
          this.$confirm(this.$t('trials:reading:pcwg:msg8'), {
            type: 'warning',
            distinguishCancelAndClose: true
          })
            .then(() => {
              this.$emit('close')
            })
            .catch(() => {})
        } else {
          this.$emit('close')
        }
      }
    },
    setState() {
      this.$nextTick(() => {
        if (this.isCurrentTask && this.readingTaskState < 2 && this.lesionType === 3) {
          var lesionState = this.getQuestionVal(7)
          if (isNaN(parseInt(lesionState)) && this.answers.IsFristAdd === 'False') {
            const stateId = this.getQuestionId(7)
            this.$set(this.questionForm, stateId, 4)
            const lesionPart = this.getQuestionVal(8)
            const lesionOrgan = this.getQuestionVal(6)
            const lesionState = !isNaN(parseInt(this.getQuestionVal(7))) ? parseInt(this.getQuestionVal(7)) : ''
            this.$emit('resetQuestions', { lesionPart, lesionOrgan, lesionState, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.measurement-form{
  /deep/ .el-form-item__label{
    color: #c3c3c3;
  }
  /deep/ .el-input .el-input__inner{
    background-color: transparent;
    color: #ddd;
    border: 1px solid #5e5e5e;
  }
  /deep/ .el-form-item{
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
  }
  /deep/ .el-form-item__content{
    flex: 1;
  }
  /deep/ .el-input.is-disabled .el-input__inner{
    background-color: #646464a1;
  }
  /deep/ .el-select.is-disabled .el-input__inner{
    background-color: #646464a1;
  }
  .el-form-item__content
  .el-select{
    width: 100%;
  }
  .input-width1{
    width: calc(100% -60px)!important;
  }
  .input-width2{
    width: 100% !important;
  }
}

</style>
