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

    <div class="container">
      <div class="basic-info">
        <h3 v-if="isReadingShowSubjectInfo">
          <span v-if="subjectCode">{{ subjectCode }} </span>
          <span style="margin-left:5px;">{{ taskBlindName }}</span>
        </h3>
        <div v-if="readingTaskState < 2">
          <el-tooltip class="item" effect="dark" :content="$t('trials:dicomReading:message:confirmReset')"
            placement="bottom">
            <i class="el-icon-refresh-left" @click="resetMeasuredData" />
          </el-tooltip>
        </div>
      </div>

      <!-- 影像质量问题 -->
      <div class="lesions">
        <Questions ref="ecrf" :question-form-change-state="true" :question-form-change-num="0" :is-qulity-issues="false"
          :group-classify="1" @handleReadingChart="handleReadingChart" />
      </div>
      <!-- 测量问题 -->
      <template v-if="questions.length > 0">
        <div v-for="(qs, index) in questions" :key="index" v-loading="loading" class="lesions lesions_wrapper"
          style="margin-bottom: 10px">
          <h4 v-if="qs.Type === 'group'" style="color: #ddd;padding: 5px 0px;margin: 0;">
            {{ language === 'en' ? qs.GroupEnName : qs.GroupName }}
          </h4>
          <div class="lesion_list">
            <el-form v-if="questions.length > 0" :ref="`questions${index}`" size="small" :model="questionForm">
              <div class="table-wrapper">
                <div v-for="item in qs.Childrens" :key="item.Id">
                  <div v-if="item.Type === 'basicTable'" class="flex-row" style="margin:3px 0;">
                    <div class="title">{{ item.QuestionName }}</div>
                    <div v-if="item.LesionType === 104">
                      <div 
                        class="add-icon" @click.prevent="downloadTpl" v-if="readingTaskState < 2">
                        <i class="el-icon-download" />
                      </div>
                      <div class="add-icon" style="margin: 0 5px;"
                        @click.prevent="uploadTpl(item.LesionType, item.QuestionName)" v-if="readingTaskState < 2">
                        <i class="el-icon-upload2" />
                      </div>
                      <div class="add-icon" @click.prevent="handleAddOrEdit('add', item)" v-if="readingTaskState < 2">
                        <i class="el-icon-plus" />
                      </div>
                      <div class="add-icon" @click.prevent="handleView(item)">
                        <i class="el-icon-view" />
                      </div>
                    </div>

                  </div>
                  <el-table v-if="item.Type === 'basicTable' && item.TableQuestions" :ref="item.Id"
                    :data="item.TableQuestions.Answers">
                    <el-table-column v-for="q of item.TableQuestions.Questions" :key="q.Id" :prop="q.Id"
                      :label="q.QuestionName" show-overflow-tooltip :render-header="renderHeader">
                      <template slot-scope="scope">
                        <span v-if="q.Unit > 0 && !isNaN(parseFloat(scope.row[q.Id]))">
                          {{ `${scope.row[q.Id]} ${$fd('ValueUnit', parseInt(q.Unit))}` }}
                        </span>
                        <span v-else-if="q.DictionaryCode">
                          {{`${scope.row[q.Id] instanceof Array ? scope.row[q.Id].map(item => $fd(q.DictionaryCode,
                            parseInt(item))).join(',') : $fd(q.DictionaryCode, parseInt(scope.row[q.Id]))}`}}
                        </span>
                        <span v-else-if="q.OptionTypeEnum === 1">
                          {{ `${scope.row[q.Id] instanceof Array ? scope.row[q.Id].join(',') : scope.row[q.Id]}` }}
                        </span>
                        <span v-else>
                          {{ `${scope.row[q.Id]}` }}
                        </span>
                      </template>
                    </el-table-column>
                    <el-table-column v-if="readingTaskState < 2 && (item.LesionType === 104)"
                      :label="$t('common:action:action')" width="90px" fixed="right">
                      <template slot-scope="scope">
                        <el-button type="text" size="mini" @click="handleAddOrEdit('edit', item, scope.$index)">
                          {{ $t('common:button:edit') }}
                        </el-button>
                        <el-button type="text" size="mini" @click="handleDelete(item, scope.$index)"
                          v-if="item.LesionType === 104">
                          {{ $t('common:button:delete') }}
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>

                  <template v-else>
                    <!-- 数值 -->
                    <el-form-item v-if="item.ShowQuestion !== 2" :key="item.Id" :label="`${item.QuestionName}`"
                      :prop="item.Id" :rules="[
                        {
                          required: (item.IsRequired === 0 || (item.IsRequired === 1 && item.RelevanceId && (item.RelevanceValue.includes(questionForm[item.RelevanceId])))) && item.Type !== 'group' && item.Type !== 'summary',
                          message: ['radio', 'select', 'checkbox'].includes(item.Type) ? $t('common:ruleMessage:select') : (item.QuestionType === 1016 || item.QuestionType === 1017) ? $t('trials:reading:ruleMessage:validatorNumberInput') : $t('common:ruleMessage:specify'), trigger: ['blur', 'change']
                        },
                        {
                          validator: item.Type === 'number' && !item.TypeValue && (item.QuestionType === 1016 || item.QuestionType === 1017) ? validatorNumberOrNEInput : (rule, value, callback) => { callback() }, trigger: ['blur', 'change']
                        }
                      ]">
                      <template v-if="item.Type === 'textarea'">
                        <el-input v-model="questionForm[item.Id]" type="textarea" :autosize="{ minRows: 2, maxRows: 4 }"
                          :disabled="!isCurrentTask || readingTaskState >= 2"
                          @change="((val) => { formItemChange(val, item) })" />
                      </template>
                      <template v-if="item.Type === 'number'">
                        <div style="display: flex;justify-content: space-between;">
                          <el-input
                            v-if="item.QuestionType === 1016 || item.QuestionType === 1017"
                            type="text" 
                            @change="(val) => { formItemChange(val, item) }" 
                            @input="numberOrNEInput(item.Id)"
                            @blur="handleNumberOrNEBlur(item)"
                            v-model.trim="questionForm[item.Id]" :disabled="readingTaskState === 2">
                            <template slot="append" v-if="item.Unit !== 0">{{ item.Unit !== 4 ? $fd('ValueUnit', item.Unit) : item.CustomUnit }}</template>
                            <template slot="append" v-else-if="item.ValueType === 2">%</template>
                          </el-input>
                          <el-input
                            v-else
                            @change="(val) => { formItemChange(val, item) }" 
                            @input="numberInput(item.Id)"
                            @blur="handleBlur(questionForm[item.Id], questionForm, item)"
                            v-model.trim="questionForm[item.Id]" :disabled="readingTaskState === 2">
                            <template slot="append" v-if="item.Unit !== 0">{{ item.Unit !== 4 ? $fd('ValueUnit', item.Unit) : item.CustomUnit }}</template>
                            <template slot="append" v-else-if="item.ValueType === 2">%</template>
                          </el-input>
                          <!-- <el-input-number v-model="questionForm[item.Id]"
                            :disabled="!isCurrentTask || readingTaskState >= 2" :precision="0"
                            @change="((val) => { formItemChange(val, item) })" /> -->
                          <svg-icon v-if="item.ShowChartTypeEnum > 0" icon-class="readingChart"
                            class="svg-icon svg-readingChart" @click.stop="(e) => handleReadingChart({
                              e,
                              data: {
                                QuestionId: item.Id,
                                QuestionName: item.QuestionName
                              }
                            })" />
                        </div>
                      </template>
                      <template v-if="item.Type === 'calculation'">
                        <el-input v-model="questionForm[item.Id]"
                        disabled type="number" @change="((val) => { formItemChange(val, item) })">
                        <template slot="append" v-if="item.Unit !== 0">
                          {{ item.Unit !== 4 ? $fd('ValueUnit', item.Unit) : item.CustomUnit }}
                        </template>
                        <template slot="append" v-else-if="item.ValueType === 2">%</template>
                        </el-input>
                      </template>
                      <template v-if="item.Type === 'select'">
                        <el-select v-model="questionForm[item.Id]" :disabled="!isCurrentTask || readingTaskState >= 2"
                          :multiple="item.OptionTypeEnum === 1" @change="((val) => { formItemChange(val, item) })">
                          <el-option v-for="dict of $d[item.DictionaryCode]" :key="dict.id" :value="String(dict.value)"
                            :label="dict.label" />
                        </el-select>
                      </template>
                    </el-form-item>
                    <template v-if="item.Childrens && item.Childrens.length > 0">
                      <template v-for="child in item.Childrens">
                        <el-form-item :key="child.Id"
                          v-if="(child.ShowQuestion === 1 && (child.ParentTriggerValueList.includes(String(questionForm[item.Id])) || (Array.isArray(questionForm[item.Id]) && child.ParentTriggerValueList.some(da => questionForm[item.Id].includes(da))))) || child.ShowQuestion === 0"
                          :label="`${child.QuestionName}`" :prop="child.Id" :rules="[
                            {
                              required: (child.IsRequired === 0 || (child.IsRequired === 1 && child.RelevanceId && ((child.RelevanceValue.includes(questionForm[child.RelevanceId])) || (Array.isArray(questionForm[child.RelevanceId]) && child.RelevanceValueList.some(da => questionForm[child.RelevanceId].includes(da)))))) && child.Type !== 'group' && child.Type !== 'summary',
                              message: ['radio', 'select', 'checkbox'].includes(child.Type) ? $t('common:ruleMessage:select') : $t('common:ruleMessage:specify'), trigger: ['blur', 'change']
                            },
                          ]">
                          <template v-if="child.Type === 'input'">
                            <el-input v-model="questionForm[child.Id]"
                              :disabled="!isCurrentTask || readingTaskState >= 2"
                              @change="((val) => { formItemChange(val, child) })" />
                          </template>
                        </el-form-item>
                      </template>

                    </template>
                  </template>
                </div>
                <div v-if="isCurrentTask && readingTaskState < 2 && (qs.GroupClassify === 5 || qs.GroupClassify === 6)"
                  class="base-dialog-footer" style="text-align:right;margin-top:10px;">
                  <!-- 保存 -->
                  <el-button type="primary" size="mini" :loading="!!rowSaveLoadingMap[index]"
                    :disabled="!!rowSaveLoadingMap[index] || !formChanged" @click="handleSave(index)">
                    {{ $t('common:button:save') }}
                  </el-button>
                </div>
              </div>
            </el-form>
          </div>
        </div>
      </template>

      <!-- 计算值 -->
      <Questions 
        ref="ecrf2" 
        :question-form-change-state="true" 
        :question-form-change-num="0" 
        :is-qulity-issues="false"
        :group-classify="4" 
        :question-type="12"
        style="margin-top:20px" />

      <!-- 评估结果 -->
      <Questions 
        ref="ecrf3" 
        :question-form-change-state="true" 
        :question-form-change-num="0" 
        :is-qulity-issues="false"
        :question-type="12"
        :group-classify="5" />
      <!-- 新增、编辑弹窗 -->
      <el-dialog v-if="addOrEdit.visible" :visible.sync="addOrEdit.visible" :close-on-click-modal="false"
        :title="addOrEdit.title" width="500px">
        <el-form ref="tableQsForm" v-loading="loading" :model="qsForm" size="small">
          <QuestionTableFormItem v-for="item in qsList" :key="item.Id" :question="item" :question-form="qsForm"
            :reading-task-state="readingTaskState" @setFormItemData="setFormItemData"
            @resetFormItemData="resetFormItemData" @handleReadingChart="handleReadingChart" />
          <el-form-item style="text-align: right">
            <el-button size="small" @click="addOrEdit.visible = false">
              {{ $t('common:button:cancel') }}
            </el-button>
            <!-- 保存 -->
            <el-button size="small" class="my_upload_btn" :loading="dialogSaveLoading"
              :disabled="dialogSaveLoading" @click="saveFormData">
              {{ $t('common:button:save') }}
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!-- 导入 -->
      <el-dialog v-if="upload.visible" :visible.sync="upload.visible" :close-on-click-modal="false"
        :title="upload.title" width="500px">
        <UploadExcel :visit-task-id="visitTaskId" :TableName="upload.TableName" :lesion-type="upload.lesionType"
          @close="uploadDlgClose" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { saveTaskQuestion, submitTableQuestion, deleteReadingRowAnswer } from '@/api/trials'
import { resetReadingTask, getIVUSTemplatesZip } from '@/api/reading'
import { getToken } from '@/utils/auth'
import DicomEvent from './../DicomEvent'
import store from '@/store'
import { mapGetters } from 'vuex'
import Questions from './../Questions'
import QuestionTableFormItem from './QuestionTableFormItem'
import UploadExcel from './UploadExcel'
export default {
  name: 'MeasurementList',
  components: {
    Questions,
    QuestionTableFormItem,
    UploadExcel
  },
  props: {
    isShow: {
      type: Boolean,
      required: true
    },
    isReadingShowSubjectInfo: {
      type: Boolean,
      required: true
    },
    questionFormChangeState: {
      type: Boolean,
      default() {
        return false
      }
    },
    questionFormChangeNum: {
      type: Number,
      default() {
        return 0
      }
    }
  },
  data() {
    return {
      questions: [],
      visitTaskId: '',
      isCurrentTask: false,
      loading: false,
      readingTaskState: 2,
      isBaseLineTask: false,
      taskBlindName: '',
      tableQuestions: [],
      CriterionType: null,
      subjectCode: '',
      questionForm: {},
      formChanged: false,
      digitPlaces: 2,
      addOrEdit: { visible: false, title: '', lesionType: null },
      upload: { visible: false, title: '', TableName: '', lesionType: null },
      qsList: [],
      answersList: [],
      qsForm: {},
      diffId: '',
      eemId: '',
      lumenId: '',
      sRoiStartDistanceId: '',
      sRoiEndDistanceId: '',
      sRoiDistanceId: '',
      rowSaveLoadingMap: {},
      dialogSaveLoading: false,
      childWindows: []
    }
  },
  computed: {
    ...mapGetters(['visitTaskList', 'language', 'lastCanvasTaskId', 'currentReadingTaskState'])
  },
  watch: {
    lastCanvasTaskId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initList()
        }
      }
    },
    currentReadingTaskState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.readingTaskState = val
        }
      }
    }
  },
  mounted() {
    // this.subjectCode = this.$router.currentRoute.query.subjectCode
    this.subjectCode = localStorage.getItem('subjectCode')
    this.digitPlaces = Number(localStorage.getItem('digitPlaces'))
    window.addEventListener('message', this.receiveMsg)
    this.CriterionType = parseInt(localStorage.getItem('CriterionType'))
    DicomEvent.$on('setCollapseActive', measureData => {
      this.setCollapseActive(measureData)
      console.log('setCollapseActive')
    })
    DicomEvent.$on('getAllUnSaveLesions', (callback) => {
      callback([])
    })
    DicomEvent.$on('refreshQuestions', _ => {
      this.refreshQuestions()
    })
    window.addEventListener('beforeunload', this.closeAllChildWindows)
  },
  beforeDestroy() {
    DicomEvent.$off('setCollapseActive')
    DicomEvent.$off('getUnSaveTarget')
    DicomEvent.$off('refreshQuestions')
    window.removeEventListener('beforeunload', this.closeAllChildWindows)
  },
  methods: {
    handleReadingChart(e) {
      this.$emit('handleReadingChart', e)
    },
    async initList() {
      var i = this.visitTaskList.findIndex(i => i.VisitTaskId === this.lastCanvasTaskId)
      if (i > -1) {
        this.visitTaskId = this.visitTaskList[i].VisitTaskId
        this.taskBlindName = this.visitTaskList[i].TaskBlindName
        this.readingTaskState = this.visitTaskList[i].ReadingTaskState
        this.isBaseLineTask = this.visitTaskList[i].IsBaseLineTask
        this.isCurrentTask = this.visitTaskList[i].IsCurrentTask
        if (!this.visitTaskList[i].IsInit) {
          var loading = this.$loading({ fullscreen: true })
          var triald = this.trialId = this.$router.currentRoute.query.trialId
          if (!this.visitTaskList[i].studyListInit) {
            await store.dispatch('reading/getStudyInfo', { trialId: triald, subjectVisitId: this.visitTaskList[i].VisitId, visitTaskId: this.visitTaskList[i].VisitTaskId, taskBlindName: this.visitTaskList[i].TaskBlindName })
          }
          if (!this.visitTaskList[i].readingQuestionsInit) {
            await store.dispatch('reading/getReadingQuestionAndAnswer', { trialId: triald, visitTaskId: this.visitTaskList[i].VisitTaskId })
          }
          if (!this.visitTaskList[i].questionsInit) {
            await store.dispatch('reading/getDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskList[i].VisitTaskId })
          }

          await store.dispatch('reading/setStatus', { visitTaskId: this.visitTaskList[i].VisitTaskId })
          loading.close()
        }
        this.questions = this.visitTaskList[i].ReadingQuestions
        this.setQuestionForm(this.questions)
        
        this.$nextTick(() => {
          this.$refs['ecrf'].getQuestions(this.visitTaskId)
          this.$refs['ecrf2'].getQuestions(this.visitTaskId)
          this.$refs['ecrf3'].getQuestions(this.visitTaskId)
        })
      }
    },
    setQuestionForm(questions) {
      const type = ['number', 'radio', 'select', 'input', 'textarea', 'calculation']
      questions.forEach(item => {
        if (type.includes(item.Type)) {
          const answer = item.Type === 'select' && item.OptionTypeEnum === 1 && item.Answer ? JSON.parse(item.Answer) : item.Answer
          this.$set(this.questionForm, item.Id, answer)
        }
        if (item.QuestionType === 1013) {
          // ROI起始回撤距离
          this.sRoiStartDistanceId = item.Id
        }
        if (item.QuestionType === 1014) {
          // ROI终止回撤距离
          this.sRoiEndDistanceId = item.Id
        }
        if (item.QuestionType === 1015) {
          // ROI段落总长度
          this.sRoiDistanceId = item.Id
        }
        if (item.Childrens.length > 0) {
          this.setQuestionForm(item.Childrens)
        }
      })
    },
    async resetQuestions(obj) {
      this.setQuestions(this.questions, obj)
      await store.dispatch('reading/setReadingQuestionAndAnswer', { questions: this.questions, visitTaskId: this.visitTaskId })

      this.getTableQuestions()
    },
    setQuestions(questions, obj) {
      questions.forEach(item => {
        if ((item.Type === 'table' || item.Type === 'basicTable') && item.Id === obj.questionId) {
          var idx = item.TableQuestions.Answers.findIndex(i => i.RowIndex === obj.rowIndex)
          item.TableQuestions.Answers[idx].saveTypeEnum = obj.saveTypeEnum
          item.TableQuestions.Answers[idx].area1 = obj.area1
          item.TableQuestions.Answers[idx].area2 = obj.area2
          item.TableQuestions.Answers[idx].diff = obj.diff
          for (const i in obj.anwsers) {
            item.TableQuestions.Answers[idx][i] = String(obj.anwsers[i])
          }
        }
       
        if (item.Childrens.length > 0) {
          this.setQuestions(item.Childrens, obj)
        }
      })
    },
    getQuestions(questions) {
      questions.forEach(item => {
        if ((item.Type === 'table' || item.Type === 'basicTable') && item.TableQuestions && item.TableQuestions.Answers.length > 0) {
          item.TableQuestions.Answers.forEach(answerObj => {
            if (answerObj.RowId) {
              var diffVal = this.getQuestionAnswer(item.TableQuestions.Questions, 1003, answerObj)
              this.$set(answerObj, 'saveTypeEnum', isNaN(parseFloat(diffVal)) ? 1 : 2)
            } else {
              this.$set(answerObj, 'saveTypeEnum', 0)
            }
          })
        }
        if (item.Childrens.length > 0) {
          this.getQuestions(item.Childrens)
        }
      })
      return questions
    },
    getReadingQuestionAndAnswer() {
      return new Promise(async resolve => {
        try {
          const loading = this.$loading({ fullscreen: true })
          await store.dispatch('reading/refreshReadingQuestionAndAnswer', { trialId: this.$router.currentRoute.query.trialId, visitTaskId: this.visitTaskId }).then(() => {
            var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
            if (idx > -1) {
              if (this.visitTaskList[idx].ReadingQuestions.length > 0) {
                this.questions = this.visitTaskList[idx].ReadingQuestions
                this.setQuestionForm(this.questions)
              }
              this.readingTaskState = this.visitTaskList[idx].ReadingTaskState
              this.isBaseLineTask = this.visitTaskList[idx].IsBaseLineTask
              this.isCurrentTask = this.visitTaskList[idx].IsCurrentTask
            }
          })
          loading.close()
          resolve()
        } catch (e) { console.log(e) }
      })
    },
    getQuestionAnswer(questions, questionMark, answers) {
      var idx = questions.findIndex(i => i.QuestionMark === questionMark)
      if (idx > -1) {
        var questionId = questions[idx].Id
        return answers[questionId]
      } else {
        return ''
      }
    },
    isCanActiveTool(toolName) {
      return { isCanActiveTool: true, reason: '' }
    },
    getMaxRowIndex(answerList) {
      if (answerList.length > 0) {
        var arr = []
        answerList.forEach(item => {
          var rowIndex = item.RowIndex
          arr.push(parseInt(rowIndex))
        })
        var max = Math.max.apply(null, arr)
        return max
      } else {
        return 0
      }
    },
    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
    },
    modifyMeasuredData(measureObj) {
    },
    // 设置测量数据
    setMeasuredData(measureData) {

    },
    formItemChange(val, item) {
      this.formChanged = true
      // if (item.Type === 'number') {
      //   this.limitBlur(item.Id, item.ValueType)
      // }
      if (item.Childrens && item.Childrens.length > 0) {
        this.resetChild(item.Childrens)
      }
      if ((item.QuestionType === 1013 || item.QuestionType === 1014) && !isNaN(parseFloat(this.questionForm[this.sRoiStartDistanceId])) && !isNaN(parseFloat(this.questionForm[this.sRoiEndDistanceId]))) {
        let num = parseFloat(this.questionForm[this.sRoiEndDistanceId]) - parseFloat(this.questionForm[this.sRoiStartDistanceId])
        this.$set(this.questionForm, this.sRoiDistanceId, parseFloat(num).toFixed(this.digitPlaces))
      }
    },
    resetChild(obj) {
      obj.forEach(i => {
        this.resetData(i.Id)
        if (i.Childrens && i.Childrens.length > 0) {
          this.resetChild(i.Childrens)
        }
      })
    },
    limitBlur(qId, valueType) {
      const value = this.questionForm[qId]
      if (isNaN(parseInt(value))) {
        this.$set(this.questionForm, qId, '')
      } else {
        if (valueType === 0) {
          this.$set(this.questionForm, qId, parseInt(value))
        } else if (valueType === 3) {
          this.$set(this.questionForm, qId, value)
        } else {
          this.$set(this.questionForm, qId, this.numberToFixed(value))
        }
      }
    },
    validatorNumberOrNEInput(rule, value, callback) {
      let reg = new RegExp(/^(?:-?(?:(?:0|[1-9]\d*)(?:\.\d+)?|\.\d+)|NE)$/, 'g')
      if (value === '') {
        callback();
      } else {
        if (!reg.test(value)) {
          callback(new Error(this.$t('trials:reading:ruleMessage:validatorNumberInput')));
        } else {
          callback();
        }
      }
    },
    numberOrNEInput(id) {
      this.formChanged = true
      // this.questionForm[id] = this.questionForm[id].toUpperCase();
      if (!this.questionForm[id]) {
        return
      }
      let value = this.questionForm[id].toUpperCase().replace(/[^0-9.NE]/g, '')
      if (value.startsWith('N')) {
        if (value.length > 2) {
          value = value.substring(0, 2)
        }
        if (value.length === 2 && value[1] !== 'E') {
           value = 'N'
        }
      } else {
        value = value.replace(/[NE]/g, '')
      }
      this.questionForm[id] = value
      this.$set(this.questionForm, id, value)
    }, 
    numberInput(id) {
      this.formChanged = true
      let value = this.questionForm[id].replace(/[^\d.]/g, '')
      this.$set(this.questionForm, id, value)
    },
    handleNumberOrNEBlur(item) {
      if (this.questionForm[item.Id] && !isNaN(parseFloat(this.questionForm[item.Id]))) {
        if (item.ValueType === 3) {
          // 文本
          this.$set(this.questionForm, item.Id, value)
        } else {
          const num = parseFloat(this.questionForm[item.Id])
          if (!isNaN(num)) {
            this.$set(this.questionForm, item.Id, parseFloat(num).toFixed(this.digitPlaces))
            if (item.ValueType === 0) {
              // 整型
              this.$set(this.questionForm, item.Id, parseInt(num))
            }  else if (item.ValueType === 1 || item.ValueType === 2){
              // 小数、百分比
              this.$set(this.questionForm, item.Id, parseFloat(num).toFixed(this.digitPlaces))
            }
          }
        }
        
      }
    },
    handleBlur(value, a, item) {
      if (!value || item.ValueType === 3) return false
      const num = parseFloat(this.questionForm[item.Id])
      if (!isNaN(num)) {
        this.$set(this.questionForm, item.Id, parseFloat(num).toFixed(this.digitPlaces))
        if (item.ValueType === 0) {
          // 整型
          this.$set(this.questionForm, item.Id, parseInt(num))
        }  else if (item.ValueType === 1 || item.ValueType === 2){
          // 小数、百分比
          this.$set(this.questionForm, item.Id, parseFloat(num).toFixed(this.digitPlaces))
        }
      }
    },
    numberToFixed(v) {
      if (this.digitPlaces > -1) {
        return isNaN(parseFloat(v)) ? null : `${parseFloat(v).toFixed(this.digitPlaces)}`
      } else {
        return v
      }
    },
    async handleSave(index, options = {}) {
      if (this.rowSaveLoadingMap[index]) return
      const refName = `questions${index}`
      this.$set(this.rowSaveLoadingMap, index, true)
      let loading = null
      try {
        const valid = await this.$refs[refName][0].validate()
        if (!valid) return
        loading = this.$loading({ fullscreen: true })
        var answers = []
        for (const k in this.questionForm) {
          answers.push({ id: k, answer: Array.isArray(this.questionForm[k]) ? JSON.stringify(this.questionForm[k]) : this.questionForm[k] })
        }
        var params = {
          visitTaskId: this.visitTaskId,
          answers: answers
        }
        await saveTaskQuestion(12, params)
        if (!options.silentSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        }
        DicomEvent.$emit('getReportInfo', true)
        if (!options.skipRefresh) {
          await this.refreshQuestions()
        }
        this.formChanged = false
      } catch (e) {
        console.log(e)
      } finally {
        if (loading) loading.close()
        this.$set(this.rowSaveLoadingMap, index, false)
      }
    },
    getECRFQuestions(obj) {
      this.$refs['ecrf'].getQuestions(obj.visitTaskId)
      this.$refs['ecrf2'].getQuestions(obj.visitTaskId)
      this.$refs['ecrf3'].getQuestions(obj.visitTaskId)
    },
    async resetMeasuredData() {
      const confirm = await this.$confirm(
        this.$t('trials:dicomReading:message:confirmReset1'),
        this.$t('trials:dicomReading:message:confirmReset2'),
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      const loading = this.$loading({ fullscreen: true })
      try {
        const res = await resetReadingTask({ visitTaskId: this.visitTaskId })
        this.loading = false
        if (res.IsSuccess) {
          await this.getReadingQuestionAndAnswer(this.visitTaskId)
          const triald = this.$router.currentRoute.query.trialId
          await store.dispatch('reading/refreshDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskId })
          this.$refs['ecrf'].getQuestions(this.visitTaskId, true)
          this.$refs['ecrf2'].getQuestions(this.visitTaskId, true)
          this.$refs['ecrf3'].getQuestions(this.visitTaskId, true)
          DicomEvent.$emit('getReportInfo', true)
        }
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    },
    async refreshQuestions() {
      const triald = this.$router.currentRoute.query.trialId
      await this.getReadingQuestionAndAnswer(this.visitTaskId)
      await store.dispatch('reading/refreshDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskId })
      this.$refs['ecrf'].getQuestions(this.visitTaskId, true)
      this.$refs['ecrf2'].getQuestions(this.visitTaskId, true)
      this.$refs['ecrf3'].getQuestions(this.visitTaskId, true)
    },
    receiveMsg(event) {
    },
    resetData(v) {
      this.questionForm[v] = null
    },
    resetFormItemData(v) {
      this.qsForm[v] = null
    },
    setFormItemData(obj) {
      this.qsForm[obj.key] = obj.val
      if (obj.key === this.eemId || obj.key === this.lumenId) {
        const eem = this.qsForm[this.eemId]
        const lumen = this.qsForm[this.lumenId]
        if (isNaN(parseFloat(eem)) || isNaN(parseFloat(lumen))) {
          this.$set(this.qsForm, this.diffId, null)
        } else {
          const diff = parseFloat(eem) - parseFloat(lumen)
          this.$set(this.qsForm, this.diffId, this.numberToFixed(diff))
        }
      }
    },
    handleAddOrEdit(type, row, index) {
      this.addOrEdit.title = row.QuestionName
      this.qsList = row.TableQuestions.Questions
      this.qsForm = {}
      this.qsForm.questionId = row.Id
      this.qsForm.rowId = type === 'add' ? null : row.TableQuestions.Answers && row.TableQuestions.Answers[index] ? row.TableQuestions.Answers[index].RowId : null
      if (type === 'add') {
        var maxIndex = this.getMaxRowIndex(row.TableQuestions.Answers)
        this.qsForm.rowIndex = `${maxIndex + 1}.00`
      } else {
        this.qsForm.rowIndex = row.TableQuestions.Answers && row.TableQuestions.Answers[index] ? row.TableQuestions.Answers[index].RowIndex : null
      }
      row.TableQuestions.Questions.map(i => {
        if (i.QuestionMark === 1001) {
          this.eemId = i.Id
        }
        if (i.QuestionMark === 1002) {
          this.lumenId = i.Id
        }
        if (i.QuestionMark === 1003) {
          this.diffId = i.Id
        }
        let v = null
        if (type === 'add') {
          v = i.Type === 'number' ? undefined : null
        } else {
          v = row.TableQuestions.Answers && row.TableQuestions.Answers[index] ? row.TableQuestions.Answers[index][i.Id] : null
        }
        this.$set(this.qsForm, i.Id, v)
      })
      this.addOrEdit.visible = true
      this.addOrEdit.lesionType = row.LesionType
    },
    handleView(item) {
      localStorage.setItem('taskBlindName', this.taskBlindName)
      localStorage.setItem('isReadingShowSubjectInfo', this.isReadingShowSubjectInfo)
      let token = getToken()
      let routeData = this.$router.resolve({ path: `/ecrfList?trialId=${this.$route.query.trialId}&visitTaskId=${this.visitTaskId}&questionId=${item.Id}&TokenKey=${token}` })
      const win = window.open(routeData.href, '_blank')
      if (win) {
        this.childWindows.push(win)
      }
    },
    closeAllChildWindows() {
      this.childWindows.forEach(win => {
        if (win && !win.closed) {
          win.close()
        }
      })
      this.childWindows = []
    },
    async saveFormData() {
      if (this.dialogSaveLoading) return
      this.dialogSaveLoading = true
      let loading = null
      try {
        const valid = await this.$refs.tableQsForm.validate()
        if (!valid) return
        loading = this.$loading({ fullscreen: true })
        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.qsForm) {
          if (reg.test(k)) {
            if (answers.findIndex(i => i.tableQuestionId === k) === -1) {
              answers.push({ tableQuestionId: k, answer: Array.isArray(this.qsForm[k]) ? JSON.stringify(this.qsForm[k]) : this.qsForm[k] })
            }
          }
        }

        var params = {
          questionId: this.qsForm.questionId,
          rowId: this.qsForm.rowId,
          rowIndex: this.qsForm.rowIndex,
          visitTaskId: this.visitTaskId,
          trialId: this.trialId,
          answerList: answers
        }
        if (this.addOrEdit.lesionType === 103) {
          params.computationTrigger = 9
        }
        const res = await submitTableQuestion(params)
        if (res.IsSuccess) {
          this.refreshQuestions()
          DicomEvent.$emit('getReportInfo', true)
          // 保存成功！
          this.addOrEdit.visible = false
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        }
      } catch (e) {
        console.log(e)
      } finally {
        if (loading) loading.close()
        this.dialogSaveLoading = false
      }
    },
    async handleDelete(row, index) {
      const loading = this.$loading({ fullscreen: true })
      try {
        const confirm = await this.$confirm(
          this.$t('trials:reading:warnning:msg48'),
          {
            type: 'warning',
            distinguishCancelAndClose: true
          }
        )
        if (confirm !== 'confirm') return
        if (row.TableQuestions.Answers[index].RowId) {
          var param = {
            visitTaskId: this.visitTaskId,
            questionId: row.Id,
            rowId: row.TableQuestions.Answers[index].RowId
          }
          const res = await deleteReadingRowAnswer(param)
          if (res.IsSuccess) {
            // await this.getReadingQuestionAndAnswer(this.visitTaskId)
            this.refreshQuestions()
            DicomEvent.$emit('getReportInfo', true)
            // '删除成功！'
            this.$message.success(this.$t('common:message:deletedSuccessfully'))
          }
        }
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    },
    uploadTpl(lesionType, TableName) {
      this.upload.lesionType = lesionType
      this.upload.TableName = TableName
      this.upload.title = `${this.$fd('LesionType', lesionType)}`
      this.upload.visible = true
    },
    async downloadTpl() {
      try {
        const params = {
          visitTaskId: this.visitTaskId
        }
        await getIVUSTemplatesZip(params)
      } catch (e) {
        console.log(e)
      }
    },
    async uploadDlgClose() {
      try {
        await this.refreshQuestions()
        const saveTasks = []
        for (let index = 0; index < this.questions.length; index++) {
          const qs = this.questions[index]
          if (qs.GroupClassify === 6) {
            saveTasks.push(() => this.handleSave(index, { silentSuccess: true, skipRefresh: true }))
          }
        }
        saveTasks.push(() => this.$refs['ecrf2'] && this.$refs['ecrf2'].handleSave({ silentSuccess: true, skipRefresh: true }))
        saveTasks.push(() => this.$refs['ecrf3'] && this.$refs['ecrf3'].handleSave({ silentSuccess: true, skipRefresh: true }))
        for (const saveTask of saveTasks) {
          try {
            await saveTask()
          } catch (e) {
            console.log(e)
          }
        }
      } catch (e) {
        console.log(e)
      } finally {
        this.upload.visible = false
      }
    },
    renderHeader(h, { column, $index }) {
      const span = document.createElement('span')
      span.innerText = column.label
      document.body.appendChild(span)
      const w = span.getBoundingClientRect().width
      column.minWidth = w > 65 ? w + 10 : w > 60 ? w + 15 : w + 20
      document.body.removeChild(span)
      return h('span', column.label)
    }
  }
}
</script>
<style lang="scss" scoped>
.measurement-wrapper {
  height: calc(100% - 50px);
  overflow-y: auto;
  .container {
    padding: 10px;

    .basic-info {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        color: #ddd;
        padding: 5px 0px;
        margin: 0;
      }

      i {
        color: #fff;
        font-size: 22px;
        font-weight: bold;
        cursor: pointer;
      }
    }
  }

  .title {
    padding: 5px;
    font-weight: bold;
    color: #ddd;
    font-size: 15px;

  }

  .add-icon {
    display: inline-block;
    padding: 5px;
    font-weight: bold;
    color: #ddd;
    font-size: 15px;
    border: 1px solid #938b8b;
    margin-bottom: 2px;
    cursor: pointer;
  }

  .add-icon:hover {
    background-color: #607d8b;
  }

  .flex-row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    background-color: #424242;

  }

  .lesion_list {
    position: relative;

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

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

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

    ::v-deep .el-form-item {
      display: flex;
      flex-direction: column;
      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;
    }

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

  .table-wrapper {
    ::-webkit-scrollbar {
      width: 5px;
      height: 8px;
    }

    ::-webkit-scrollbar-thumb {
      border-radius: 10px;
      background: #d0d0d0;
    }

    ::v-deep .el-table,
    .el-table__expanded-cell {
      background-color: #000;
      color: #fff;
      border-color: #444444;
    }

    ::v-deep .el-table th,
    .el-table tr {
      background-color: #000;
      color: #fff;
      border-color: #444444;
    }

    ::v-deep .el-table__body tr>td {
      background-color: #000 !important;
      color: #fff;
      border-color: #444444;
    }

    ::v-deep .el-table__body tr:hover>td {
      background-color: #858282 !important;
      color: #fff;
      border-color: #444444;
    }

    ::v-deep .el-table--border th.gutter:last-of-type {
      border: none;
    }

    ::v-deep .el-table__fixed-right {
      height: 100% !important;
    }

    // ::v-deep .el-table .cell {
    //   line-height: 20px;
    // }
    ::v-deep .el-table__cell {
      padding: 5px 0;
    }

    ::v-deep .el-table__fixed-right-patch {
      background-color: #000 !important;
      border-color: #444444;
    }

    ::v-deep .el-table__fixed-body-wrapper tr:hover>td {
      background-color: #000 !important;
    }

    ::v-deep .el-table--scrollable-x .el-table__body-wrapper {
      z-index: 2;
    }
    
  }
  ::v-deep .el-tag.el-tag--info {
    color: #000;
  }
}
</style>
