<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;">
          {{ lesionName }}
        </h3>
        <!-- 关闭 -->
        <div>
          <i class="el-icon-circle-close" style="font-size: 25px;cursor: pointer;" @click="handleClose" />
        </div>
      </div>

      <el-form-item v-for="qs in questions" v-show="qs.ShowQuestion !== 2" :key="qs.Id" :label="`${qs.QuestionName}`"
        :prop="qs.Id" :rules="[
          {
            required: (qs.IsRequired === 0 || (qs.IsRequired === 1 && qs.RelevanceId && (String(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']
          },
        ]" style="flex-wrap: wrap">

        <!-- 输入框 -->
        <template
          v-if="(qs.Type === 'input' || qs.Type === 'number') && (qs.QuestionMark === 1104)">
          <div style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center;">
            <el-input v-model="questionForm[qs.Id]" disabled style="width: 100px;">
              <template v-if="qs.Unit" slot="append">
                {{ $fd('ValueUnit', parseInt(qs.Unit)) }}
              </template>
            </el-input>
            <!-- 测量 -->
            <el-button
              v-if="questionForm[isMeasurableId] && parseInt(questionForm[isMeasurableId]) === 1 && !questionForm.MeasureData && readingTaskState !== 2"
              size="mini" type="text" @click="addAnnotation(qs)">
              {{ $t('trials:MRIPDFF:button:measure') }}
            </el-button>
            <!-- 清除标记 -->
            <!-- <el-button v-if="getAnnotationStatus(qs) && readingTaskState !== 2" size="mini" type="text"
              style="margin-left: 0px" @click="removeAnnotation(qs)">
              {{ $t('trials:MRIPDFF:button:clear') }}
            </el-button> -->
            <el-button v-if="questionForm.MeasureData  && readingTaskState !== 2" size="mini"  type="text"  @click="handleDeleteMeasureData">
              {{ $t('trials:reading:button:removeMark') }}
            </el-button>
            <!-- 返回 -->
            <!-- <el-button v-if="questionForm[qs.Id]" size="mini" type="text" style="margin-left: 0px"
              @click="locateAnnotation(qs)">
              {{ $t('trials:MRIPDFF:button:return') }}
            </el-button> -->
            <!-- 保存 -->
            <!-- <el-button
              v-if="questionForm[isMeasurableId] && parseInt(questionForm[isMeasurableId]) === 1 && questionForm[qs.Id] && readingTaskState !== 2"
              size="mini" type="text" style="margin-left: 0px" @click="saveAnnotation(qs)">
              <el-tooltip v-if="getAnnotationSaveEnum(qs) === 0" class="item" effect="dark"
                :content="$t('trials:reading:button:unsaved')" placement="bottom">
                <i class="el-icon-warning" style="color:red" />
              </el-tooltip>
              {{ $t('common:button:save') }}
            </el-button> -->
          </div>
        </template>
        <template v-else-if="qs.Type === 'input' || qs.Type === 'number'">
          <div style="display: flex;justify-content: space-between;">
            <el-input v-model="questionForm[qs.Id]" :disabled="!isCurrentTask || readingTaskState >= 2"
              @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>
            <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>
        </template>
        <!-- 多行文本输入框 -->
        <el-input v-else-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-else-if="qs.Type === 'select'" v-model="questionForm[qs.Id]" filterable
          :placeholder="$t('common:placeholder:select')"
          :disabled="!isCurrentTask || readingTaskState >= 2 || qs.QuestionMark === 1106"
          @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">
            <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-else-if="qs.Type === 'radio'" v-model="questionForm[qs.Id]"
          :disabled="!isCurrentTask || readingTaskState >= 2 || (qs.QuestionMark === 1105 && isDisabledMeasurableRadio)"
          @change="((val) => { formItemChange(val, qs) })">
          <template v-if="qs.DictionaryCode.length > 0">
            <el-radio v-for="item in $d[qs.DictionaryCode]" :key="item.id" :label="item.value">
              {{ item.label }}
            </el-radio>
          </template>
          <template v-else-if="qs.options.length > 0">
            <el-radio v-for="val in qs.options.split('|')" :key="val" :label="val">
              {{ val }}
            </el-radio>
          </template>
        </el-radio-group>
        <div style="display: flex;justify-content: space-between;" v-else-if="qs.Type === 'calculation'">
          <!-- 自动计算 -->
          <el-input v-model="questionForm[qs.Id]" disabled @change="((val) => { formItemChange(val, qs) })">
            <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>

    </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" @click="handleDeleteMeasureData">
        {{ $t('trials:reading:button:removeMark') }}
      </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 } from '@/api/trials'
import { saveTableQuestionMark, submitTaskRowInfo, deleteTableQuestionMark, deleteSingleTableQuestionMark } from '@/api/reading'
import DicomEvent from './../DicomEvent'
import store from '@/store'
import * as cornerstone from 'cornerstone-core'
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: '',
      originalQuestionForm: {},
      isRender: false,
      lesionName: '',
      lesionMark: '',
      activeQuestionId: '',
      activeQuestionMark: '',
      digitPlaces: 2,
      isMeasurableId: '',
      isDisabledMeasurableRadio: false,
      liverSeg: '',
      saveLoading: false
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    const digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.initForm()
    DicomEvent.$on('handleImageQualityAbnormal', () => {
      this.setState()
    })
  },
  beforeDestroy() {
    DicomEvent.$off('handleImageQualityAbnormal')
  },
  methods: {
    handleReadingChart(e) {
      this.$emit('handleReadingChart', e)
    },
    async initForm() {
      this.isRender = false
      this.isMeasurableId = this.getQuestionId(1105)
      this.isDisabledMeasurableRadio = false
      // const loading = this.$loading({ fullscreen: true })
      this.questions.forEach(item => {
        if (this.answers.hasOwnProperty(item.Id)) {
          let val = this.answers[item.Id]
          if (item.DictionaryCode) {
            val = isNaN(parseInt(this.answers[item.Id])) ? this.answers[item.Id] : parseInt(this.answers[item.Id])
          }
          this.$set(this.questionForm, item.Id, val)
        } else {
          this.$set(this.questionForm, item.Id, '')
        }
      })
      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.toolType = this.questionForm.MeasureData ? this.questionForm.MeasureData.type : ''
      this.currentMarkTool = this.questionForm.MeasureData ? this.questionForm.MeasureData.type : this.answers.MarkTool
      const isMeasurable = this.getQuestionVal(1105)
      const mean = this.getQuestionVal(1104)
      if (this.isCurrentTask && this.readingTaskState < 2) {
        if (this.answers.MeasureData) {
          if (!isNaN(parseInt(isMeasurable)) && parseInt(isMeasurable) === 1 ) {
            this.isDisabledMeasurableRadio = true
          } else if (!isNaN(parseInt(isMeasurable)) && parseInt(this.questionForm[this.isMeasurableId]) === 0) {
            // 如果存在标记且是否可测量为否，则将是否可测量更改为是
            this.$set(this.questionForm, this.isMeasurableId, 1)
          }
        }
      }
      // saveTypeEnum 0：未保存过（新建病灶）；1：已保存，信息不完整（随访初始化病灶/分裂病灶，通过状态判断）；2：已保存，信息完整
      if (this.questionForm.saveTypeEnum !== 1 && this.isCurrentTask && this.readingTaskState < 2) {
        this.$set(this.questionForm, 'saveTypeEnum', parseInt(isMeasurable) === 1 && isNaN(parseFloat(mean)) ? 1 : 2)
      }
      this.lesionName = this.getLesionInfo(this.orderMark, this.rowIndex)
      this.lesionMark = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
      this.originalQuestionForm = { ...this.questionForm }
      
      
      const seg = this.getQuestionVal(1106)
      this.liverSeg = this.$fd('LiverSegmentation', seg)
      if (this.questionForm.saveTypeEnum === 1 && this.isCurrentTask && this.readingTaskState < 2) {
        this.setQuestions()
      }
      this.isRender = true
      // loading.close()
    },
    // getLesionName(orderMark) {
    //   // 根据肝脏分段枚举和第一次（或第二次或第三次）测量问题标识定义标记名称
    //   // I II III IV V VI VII VIII
    //   // L-I-01 L-I-02 L-I-03
    //   // L-II-01 L-II-02 L-II-03
    //   const segArr = ['I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII']
    //   let lessionName = ''
    //   const segmentId = this.getQuestionId(1106)
    //   let segmentVal = this.answers[segmentId]
    //   segmentVal = segmentVal ? parseInt(segmentVal) : null
    //   if (segmentVal) {
        
    //     lessionName = `${orderMark}-${segArr[segmentVal - 1]}`
    //   }
    //   return lessionName
    // },
    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)
      }
      return arr.join(' ')
    },
    getQuestionId(questionMark) {
      var idx = this.questions.findIndex(i => i.QuestionMark === questionMark)
      if (idx > -1) {
        return this.questions[idx].Id
      } else {
        return ''
      }
    },
    async formItemChange(v, qs) {
      // 维护平均值、是否可测量等信息
      // 1101 -- 第一次测量  1102 -- 第二次测量  1103 -- 第三次测量  1107 -- 第四次测量
      // 1104 -- MRI-PDFF  1105 -- 是否可测量
      this.$set(this.questionForm, 'saveTypeEnum', 1)
      if (qs.QuestionMark === 1105) {
        const meanId = this.getQuestionId(1104)
        if (!v) {
          this.$set(this.questionForm, meanId, 'NE')
        } else {
          this.$set(this.questionForm, meanId, '')
        }
      }
      this.setQuestions()
    },
    setMeasureData(measureData, isInit = false) {
      return new Promise(resolve => {
        if (!measureData) {
          resolve()
        }
        let data = {}
        // 创建标记
        if (!measureData.data.remark) {
          // 维护标记信息
          measureData.data.remark = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
        }
        // const val = measureData.data.cachedStats.mean / 10
        let val = parseFloat(measureData?.data?.cachedStats?.mean)
        if (isNaN(val)) {
          resolve()
          return
        }
        // let imagePixelModule = cornerstone.metaData.get('imagePixelModule', measureData.imageId)
        if (measureData.largestPixelValue >= 500) {
          val = val / 10
        }
        this.$set(this.questionForm, measureData.tableQuestionId, val.toFixed(this.digitPlaces))
        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,
          NumberOfFrames: isNaN(parseInt(measureData.frame)) ? 0 : measureData.frame,
          frame: isNaN(parseInt(measureData.frame)) ? 0 : measureData.frame,
          OrderMarkName: measureData.data.remark
        }
        store.dispatch('reading/addMeasuredData', { visitTaskId: this.visitTaskId, data: data })
        DicomEvent.$emit('refreshStudyListMeasureData')
        const isMeasurable = this.getQuestionVal(1105)
       
        if (!isNaN(parseInt(isMeasurable)) && parseInt(isMeasurable) === 1) {
          this.isDisabledMeasurableRadio = true
        }
        this.$set(this.questionForm, 'saveTypeEnum', 1)
        this.$set(this.questionForm, 'MeasureData', measureData)
        this.setQuestions()
        resolve()
      })
    },
    addAnnotation(qs) {
      const orderMarkName = this.getLesionName(this.orderMark, this.questionForm.RowIndex)
      this.activeQuestionId = qs.Id
      this.activeQuestionMark = qs.QuestionMark
      DicomEvent.$emit('addAnnotation', { question: qs, locateInfo: { questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, visitTaskId: this.visitTaskId, lesionName: orderMarkName, lesionType: null, markTool: 'Probe', readingTaskState: this.readingTaskState, isMarked: true } })
    },
    setQuestions() {
      const mean = this.getQuestionVal(1104)
      const isMeasurable = this.getQuestionVal(1105)
      this.$emit('resetQuestions', { mean, isMeasurable, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })
    },
    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) {
      const idx = this.questions.findIndex(i => i.QuestionMark === questionMark)
      if (idx > -1) {
        const questionId = this.questions[idx].Id
        const answer = this.questionForm[questionId]
        if (isNaN(parseFloat(answer))) {
          return answer
        } else {
          return parseFloat(answer)
        }
      } 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}/${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 })
    },
    // async handleDeleteMeasureData() {
    //   // 是否确认清除标记？
    //   const confirm = await this.$confirm(
    //     this.$t('trials:reading:warnning:msg47'),
    //     {
    //       type: 'warning',
    //       distinguishCancelAndClose: true
    //     }
    //   )
    //   if (confirm !== 'confirm') return
    //   // 重置MRI-PDFF
    //   var mripdffId = this.getQuestionId(1104)
    //   this.$set(this.questionForm, mripdffId, '')
    //   if (this.questionForm.RowId) {
    //     this.$set(this.questionForm, 'saveTypeEnum', 1)
    //   } else {
    //     this.$set(this.questionForm, 'saveTypeEnum', 0)
    //   }
    //   await store.dispatch('reading/removeMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.questionForm.MeasureData, questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex })
    //   DicomEvent.$emit('getMeasureData')

    //   if (!this.questionForm.IsDicomReading) {
    //     DicomEvent.$emit('removeNoneDicomMeasureData', this.questionForm.MeasureData)
    //   }
    //   this.$set(this.questionForm, 'IsDicomReading', true)

    //   this.$set(this.questionForm, 'MeasureData', '')


    //   const mean = this.getQuestionVal(1104)
    //   const isMeasurable = this.getQuestionVal(1105)
    //   this.$emit('resetQuestions', { mean, isMeasurable, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: this.questionForm })

    //   DicomEvent.$emit('refreshStudyListMeasureData')
    // },

    async handleDeleteMeasureData() {
      // 是否确认清除标记？
      const confirm = await this.$confirm(
        this.$t('trials:reading:warnning:msg47'),
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      let isMeasurable = this.getQuestionVal(1105)
      // 重置MRI-PDFF
      let mripdffId = this.getQuestionId(1104)
      this.$set(this.questionForm, mripdffId, '')
      if (this.questionForm.RowId) {
        this.$set(this.questionForm, 'saveTypeEnum', 1)
      } else {
        this.$set(this.questionForm, 'saveTypeEnum', 0)
      }
      await store.dispatch('reading/removeMeasuredData', { visitTaskId: this.visitTaskId, measureData: this.questionForm.MeasureData, questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex })
      DicomEvent.$emit('getMeasureData')

      this.$set(this.questionForm, 'MeasureData', '')
      this.isDisabledMeasurableRadio = false
      let anwsers = Object.assign({}, this.questionForm)
      this.$emit('resetQuestions', { mean: '', isMeasurable, saveTypeEnum: this.questionForm.saveTypeEnum, rowIndex: this.rowIndex, questionId: this.parentQsId, anwsers: anwsers })
      DicomEvent.$emit('refreshStudyListMeasureData')
    },
    async handleSave() {
      if (this.saveLoading) return
      this.saveLoading = true
      try {
        const valid = await this.$refs.measurementForm.validate()
        if (!valid) {
          this.saveLoading = false
          return
        }
        const loading = this.$loading({ fullscreen: true })
        let measureData = this.questionForm.MeasureData
        if (parseInt(this.questionForm[this.isMeasurableId]) === 0 && measureData) {
          await deleteTableQuestionMark({ rowId: this.questionForm.RowId }, 11)
        }
        DicomEvent.$emit('getScreenshots', { questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, visitTaskId: this.visitTaskId, lesionName: this.lesionMark, lesionType: this.lesionType, isMarked: !!measureData }, async val => {
          try {
            let picturePath = ''
            if (val && measureData) {
              let pictureObj = await this.uploadScreenshots(`${new Date().getTime()}`, val)
             
              picturePath = pictureObj.isSuccess ? this.$getObjectName(pictureObj.result.url) : ''
            }
            let answers = []
            let 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] })
                }
              }
            }
            let params = {
              questionId: this.parentQsId,
              rowId: this.questionForm.RowId,
              rowIndex: this.answers.RowIndex,
              visitTaskId: this.visitTaskId,
              trialId: this.trialId,
              measureData: measureData ? JSON.stringify(measureData) : '',
              answerList: answers,
              isDicomReading: true,
              studyId: measureData ? this.questionForm.MeasureData.studyId : '',
              seriesId: measureData ? this.questionForm.MeasureData.seriesId : '',
              instanceId: measureData ? this.questionForm.MeasureData.instanceId : '',
              numberOfFrames: measureData && !isNaN(parseInt(this.questionForm.MeasureData.frame)) ? parseInt(this.questionForm.MeasureData.frame) : 0,
              picturePath: picturePath,
              markTool: measureData ? measureData.type : ''
            }
            const res = await submitTaskRowInfo(params, 13)
            if (res.IsSuccess) {
              // 保存成功！
              this.$message.success(this.$t('common:message:savedSuccessfully'))
              this.currentMarkTool = measureData ? measureData.type : ''
              this.$set(this.questionForm, 'saveTypeEnum', 2)
              this.originalQuestionForm = { ...this.questionForm }
              this.$set(this.questionForm, 'RowId', res.Result.RowId)
              this.setQuestions()
              this.$emit('close')
              DicomEvent.$emit('getReportInfo', true)
              DicomEvent.$emit('setMeasuredToolsPassive')
              // await store.dispatch('reading/refreshMeasuredData', this.visitTaskId)
              // DicomEvent.$emit('getMeasureData')
              this.$emit('getReadingQuestionAndAnswer')
            }
            loading.close()
            this.saveLoading = false
          } catch(e) {
            loading.close()
            this.saveLoading = false
          }
        })
      } catch (e) {
        console.log(e)
        this.saveLoading = false
      }
    },
    async handleClose() {
      this.$emit('close')
    },
    setState() {
      this.$nextTick(() => {
        if (this.isCurrentTask && this.readingTaskState < 2) {
          // 是否要将是否可测量设置为否？
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.measurement-form {
  ::v-deep .el-form-item__label {
    color: #c3c3c3;
  }

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

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

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

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

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

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

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

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