<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 === 1101 || qs.QuestionMark === 1102 || qs.QuestionMark === 1103)">
          <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[qs.Id] && 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[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 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: '',
      markList: [],
      digitPlaces: 2,
      isMeasurableId: '',
      isExitsMarks: false,
      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)
      // 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 : '')
      // 如果存在标记且是否可测量为否，则将是否可测量更改为是
      if (this.isCurrentTask && this.readingTaskState < 2) {
        const arr = JSON.parse(this.answers.TableQuestionMarkList)
        const isExitsMarks = arr.findIndex(i => i.MeasureData) > -1
        if (isExitsMarks && parseInt(this.questionForm[this.isMeasurableId]) === 0) {
          this.$set(this.questionForm, this.isMeasurableId, 1)
        }
      }
      // saveTypeEnum 0：未保存过（新建病灶）；1：已保存，信息不完整（随访初始化病灶/分裂病灶，通过状态判断）；2：已保存，信息完整
      const isMeasurable = this.getQuestionVal(1105)
      const mean = this.getQuestionVal(1104)
      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, 1101)
      this.originalQuestionForm = { ...this.questionForm }
      this.markList = []
      this.isExitsMarks = false
      this.isDisabledMeasurableRadio = false
      const seg = this.getQuestionVal(1106)
      this.liverSeg = this.$fd('LiverSegmentation', seg)
      if (this.answers.TableQuestionMarkList) {
        const arr = JSON.parse(this.answers.TableQuestionMarkList)
        arr.map(i => {
          if (i.MeasureData) {
            this.isExitsMarks = true
            if (!isNaN(parseInt(isMeasurable)) && parseInt(isMeasurable) === 1 && this.isCurrentTask && this.readingTaskState < 2) {
              this.isDisabledMeasurableRadio = true
            }
            i.MeasureData = JSON.parse(i.MeasureData)
          }
          this.markList.push({ tableQuestionId: i.TableQuestionId, measureData: i, saveEnum: 1 })
        })
      }

      const newMean = this.getMean()
      if (newMean !== mean) {
        const meanId = this.getQuestionId(1104)
        this.$set(this.questionForm, meanId, newMean || '')
      }
      if (this.questionForm.saveTypeEnum === 1 && this.isCurrentTask && this.readingTaskState < 2) {
        this.setQuestions()
      }
      this.isRender = true
      // loading.close()
    },
    getLesionName(orderMark, questionMark) {
      // 根据肝脏分段枚举和第一次（或第二次或第三次）测量问题标识定义标记名称
      // 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) {
        const i = questionMark === 1101 ? '01' : questionMark === 1102 ? '02' : questionMark === 1103 ? '03' : ''
        lessionName = `${orderMark}-${segArr[segmentVal - 1]}-${i}`
      }
      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) {
      // 维护平均值、是否可测量等信息
      this.$set(this.questionForm, 'saveTypeEnum', 1)
      const mean = this.getQuestionVal(1104)
      if (qs.QuestionMark === 1101 || qs.QuestionMark === 1102 || qs.QuestionMark === 1103) {
        const newMean = this.getMean()
        if (newMean !== mean) {
          const meanId = this.getQuestionId(1104)
          this.$set(this.questionForm, meanId, newMean || '')
        }
      } else if (qs.QuestionMark === 1105) {
        if (!v) {
          const meanId = this.getQuestionId(1104)
          this.$set(this.questionForm, meanId, 'NE')
        } else {
          const mean = this.getMean()
          const meanId = this.getQuestionId(1104)
          this.$set(this.questionForm, meanId, mean)
        }
      }
      this.setQuestions()
    },
    getMean() {
      let mean = null
      let isMeasurable = this.getQuestionVal(1105)
      isMeasurable = !isNaN(parseInt(isMeasurable)) ? parseInt(isMeasurable) : null
      const l1 = this.getQuestionVal(1101)
      const l2 = this.getQuestionVal(1102)
      const l3 = this.getQuestionVal(1103)
      if (isMeasurable && !isNaN(parseFloat(l1)) && !isNaN(parseFloat(l2)) && !isNaN(parseFloat(l3))) {
        const sum = l1 + l2 + l3
        mean = sum / 3
        return parseFloat(mean.toFixed(this.digitPlaces))
      } else if (isMeasurable === 0) {
        return 'NE'
      } else {
        return ''
      }
    },
    setMeasureData(measureData, isInit = false) {
      return new Promise(resolve => {
        if (!measureData || (measureData && measureData.tableQuestionId !== this.activeQuestionId)) {
          resolve()
        }
        var data = {}
        // 创建标记
        if (!measureData.data.remark) {
          // 维护标记信息
          measureData.data.remark = this.getLesionName(this.orderMark, this.activeQuestionMark)
        }
        // const val = measureData.data.cachedStats.mean / 10
        let val = parseFloat(measureData.data.cachedStats.mean)
        // 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: '',
          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,
          TableQuestionId: measureData.tableQuestionId
        }
        store.dispatch('reading/addMeasuredData', { visitTaskId: this.visitTaskId, data: data })
        let mean = this.getQuestionVal(1104)
        const newMean = this.getMean()
        if (newMean !== mean) {
          mean = newMean
          const meanId = this.getQuestionId(1104)
          this.$set(this.questionForm, meanId, newMean || '')
        }
        const isMeasurable = this.getQuestionVal(1105)
        DicomEvent.$emit('refreshStudyListMeasureData')
        const i = this.markList.findIndex(i => i.tableQuestionId === measureData.tableQuestionId)
        if (i === -1) {
          this.markList.push({ tableQuestionId: measureData.tableQuestionId, measureData: data, saveEnum: 0 })
        } else {
          this.markList[i].saveEnum = 0
          this.markList[i].measureData = data
        }
        if (!isNaN(parseInt(isMeasurable)) && parseInt(isMeasurable) === 1) {
          this.isDisabledMeasurableRadio = true
        }
        this.$set(this.questionForm, 'saveTypeEnum', 1)
        this.setQuestions()
        resolve()
      })
    },
    addAnnotation(qs) {
      // 判断是否有测量数据未保存
      const i = this.markList.findIndex(i => i.saveEnum === 0)
      if (i > -1 && this.markList[i].measureData && this.markList[i].measureData.MeasureData) {
        this.$alert(this.$t('trials:MRIPDFF:message:message3'))
        // this.$message.warning(this.$t('trials:MRIPDFF:message:message3'))
        return
      }
      const orderMarkName = this.getLesionName(this.orderMark, qs.QuestionMark)
      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 } })
    },
    getAnnotationSaveEnum(qs) {
      const i = this.markList.findIndex(i => i.tableQuestionId === qs.Id)
      if (i > -1) {
        return this.markList[i].saveEnum
      } else {
        return 1
      }
    },
    getAnnotationStatus(qs) {
      const i = this.markList.findIndex(i => i.tableQuestionId === qs.Id)
      if (i > -1 && this.markList[i].measureData && this.markList[i].measureData.MeasureData) {
        return true
      } else {
        return false
      }
    },
    getIsExitsMarks() {
      const isMeasurable = this.getQuestionVal(1105)
      if (!isNaN(parseInt(isMeasurable)) && parseInt(isMeasurable) === 1) {
        return this.markList.findIndex(i => i.measureData && i.measureData.MeasureData) > -1
      } else {
        return false
      }
    },
    async removeAnnotation(qs) {
      const i = this.markList.findIndex(i => i.tableQuestionId === qs.Id)
      DicomEvent.$emit('imageLocation', { questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, visitTaskId: this.visitTaskId, lesionName: this.markList[i].measureData.OrderMarkName, lesionType: null, markTool: 'Probe', readingTaskState: this.readingTaskState, isMarked: true })
      // 是否确认清除标记？
      const confirm = await this.$confirm(
        this.$t('trials:reading:warnning:msg47'),
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return

      const measureData = Object.assign({}, this.markList[i].measureData)
      if (measureData.Id) {
        await deleteSingleTableQuestionMark({ Id: measureData.Id }, 11)
      }
      // 移除缓存中的measureData
      await store.dispatch('reading/removeMeasuredData', { visitTaskId: this.visitTaskId, measureData: measureData, questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, orderMarkName: measureData.OrderMarkName })
      DicomEvent.$emit('getMeasureData')
      this.markList[i].measureData = null
      this.markList[i].saveEnum = 0
      // 清除测量值、清除平均值
      this.$set(this.questionForm, this.markList[i].tableQuestionId, '')
      const meanId = this.getQuestionId(1104)
      this.$set(this.questionForm, meanId, '')
      this.isDisabledMeasurableRadio = this.getIsExitsMarks()
      this.$set(this.questionForm, 'saveTypeEnum', 1)
      this.setQuestions()
    },
    locateAnnotation(qs) {
      const i = this.markList.findIndex(i => i.tableQuestionId === qs.Id)
      const measureData = this.markList[i].measureData
      // 定位
      var markTool = 'Probe'
      var readingTaskState = this.readingTaskState
      var isMarked = !!measureData
      DicomEvent.$emit('imageLocation', { questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, visitTaskId: this.visitTaskId, lesionName: measureData.OrderMarkName, lesionType: null, markTool, readingTaskState, isMarked })
    },
    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 })
    },
    async saveAnnotation(qs) {
      const loading = this.$loading({ fullscreen: true })
      try {
        const i = this.markList.findIndex(i => i.tableQuestionId === qs.Id)
        let params = {}
        if (i > -1 && this.markList[i].measureData && this.markList[i].measureData.MeasureData) {
          const measureData = this.markList[i].measureData.MeasureData
          const tableQuestionId = this.markList[i].tableQuestionId
          if (this.questionForm[tableQuestionId] > 100) {
            const confirm = await this.$confirm(
              this.$t('trials:MRIPDFF:message:message4'),
              {
                type: 'warning',
                distinguishCancelAndClose: true
              }
            )
            if (confirm !== 'confirm') return
          }
          // 上传截图

          DicomEvent.$emit('getScreenshots', { questionId: this.parentQsId, rowIndex: this.questionForm.RowIndex, visitTaskId: this.visitTaskId, lesionName: measureData.OrderMarkName, lesionType: null, isMarked: !!measureData }, async val => {
            params = Object.assign({}, this.markList[i].measureData)
            if (val) {
              const pictureObj = await this.uploadScreenshots(`${new Date().getTime()}`, val)
              params.PicturePath = pictureObj.isSuccess ? this.$getObjectName(pictureObj.result.url) : ''
            }

            params.Answer = this.questionForm[tableQuestionId]
            params.MeasureData = JSON.stringify(this.markList[i].measureData.MeasureData)
            loading.close()
            this.saveTableQuestionInfo(params, qs)
          })
        } else {
          params = {
            Answer: '',
            VisitTaskId: this.visitTaskId,
            QuestionId: this.parentQsId,
            InstanceId: '',
            SeriesId: '',
            StudyId: '',
            MarkTool: '',
            PicturePath: '',
            NumberOfFrames: 0,
            MeasureData: '',
            QuestionType: 0,
            OrderMarkName: '',
            RowId: this.questionForm.RowId,
            TableQuestionId: qs.Id,
            RowIndex: this.questionForm.RowIndex
          }
          loading.close()
          this.saveTableQuestionInfo(params, qs)
        }
      } catch (e) {
        console.log(e)
        loading.close()
      }
    },
    async saveTableQuestionInfo(params, qs) {
      const loading = this.$loading({ fullscreen: true })
      try {
        const res = await saveTableQuestionMark(params, 11)
        if (res.IsSuccess) {
          // 保存后设置保存状态
          const i = this.markList.findIndex(i => i.tableQuestionId === qs.Id)
          this.markList[i].saveEnum = 1
          // 保存病灶
          const j = this.markList.findIndex(i => !(i.saveEnum === 1 && i.measureData && i.measureData.MeasureData))
          if (j === -1) {
            const answers = []
            const reg = new RegExp(/^[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}$/)
            for (const k in this.questionForm) {
              if (reg.test(k)) {
                if (answers.findIndex(i => i.tableQuestionId === k) === -1) {
                  answers.push({ tableQuestionId: k, answer: this.questionForm[k] })
                }
              }
            }
            const params = {
              questionId: this.parentQsId,
              rowId: this.questionForm.RowId,
              rowIndex: this.answers.RowIndex,
              visitTaskId: this.visitTaskId,
              trialId: this.trialId,
              answerList: answers,
              isDicomReading: true
            }
            const res = await submitTaskRowInfo(params, 11)
            if (res.IsSuccess) {
              this.$set(this.questionForm, 'saveTypeEnum', 2)
              this.originalQuestionForm = { ...this.questionForm }
              this.$set(this.questionForm, 'RowId', res.Result.RowId)
              this.setQuestions()
              DicomEvent.$emit('getReportInfo', true)
            }
          }
          // 保存成功
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          // 刷新表格、刷新标记信息
          this.$emit('getReadingQuestionAndAnswer')
          DicomEvent.$emit('setMeasuredToolsPassive')
          loading.close()
        }
      } catch (e) {
        console.log(e)
        loading.close()
      }
    },
    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 handleSave() {
      if (this.saveLoading) return
      this.saveLoading = true
      try {
        const valid = await this.$refs.measurementForm.validate()
        if (!valid) {
          this.saveLoading = false
          return
        }
        if (parseInt(this.questionForm[this.isMeasurableId]) === 1) {
          // 检验是否有标记为保存
          const i = this.markList.findIndex(i => i.saveEnum === 0)
          if (i > -1) {
            // 请先保存标注信息！
            this.$alert(this.$t('trials:MRIPDFF:message:message1'))
            // this.$message.warning(this.$t('trials:MRIPDFF:message:message1'))
            this.saveLoading = false
            return
          }
        } else {
          // 不可测量时，清空测量值，平均值
          // '是否确认不可测量？'
          const confirm = await this.$confirm(
            this.$t('trials:MRIPDFF:message:message2'),
            {
              type: 'warning',
              distinguishCancelAndClose: true
            }
          )
          if (confirm !== 'confirm') {
            this.saveLoading = false
            return
          }
          const l1Id = this.getQuestionId(1101)
          this.$set(this.questionForm, l1Id, '')
          const l2Id = this.getQuestionId(1102)
          this.$set(this.questionForm, l2Id, '')
          const l3Id = this.getQuestionId(1103)
          this.$set(this.questionForm, l3Id, '')
          const meanId = this.getQuestionId(1104)
          this.$set(this.questionForm, meanId, 'NE')
        }

        const loading = this.$loading({ fullscreen: true })

        try {
          // let isResetMarks = this.markList.findIndex(i=>i.measureData && i.measureData.MeasureData) > -1 ? true : false
          if (parseInt(this.questionForm[this.isMeasurableId]) === 0 && this.isExitsMarks) {
            await deleteTableQuestionMark({ rowId: this.questionForm.RowId }, 11)
            this.markList.forEach(i => {
              if (i.measureData && i.measureData.MeasureData) {
                i.measureData = ''
              }
            })
            this.isExitsMarks = false
          }
          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,
            rowId: this.questionForm.RowId,
            rowIndex: this.answers.RowIndex,
            visitTaskId: this.visitTaskId,
            trialId: this.trialId,
            answerList: answers,
            isDicomReading: true
          }
          const res = await submitTaskRowInfo(params, 11)
          if (res.IsSuccess) {
            // 保存成功！
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            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) {
          console.log(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>
