<template>
  <div class="criterion-table-form-item">
    <el-form-item
      v-if="(question.ShowQuestion === 1 && !!~question.ParentTriggerValueList.indexOf(String(questionForm[question.ParentId]))) || question.ShowQuestion === 0"
      :title="question.Remark" :label="`${question.QuestionName}`" :prop="question.Id" :rules="[
        {
          required: (question.IsRequired === 0 || (question.IsRequired === 1 && question.RelevanceId && !!~question.RelevanceValueList.indexOf(questionForm[question.RelevanceId]))) && question.Type !== 'group' && question.Type !== 'summary',
          message: $t('common:ruleMessage:select'), trigger: ['blur', 'change']
        },
        {
          validator: question.Type === 'number' && !question.TypeValue ? validatorNumberInput : (rule, value, callback) => { callback() },
          trigger: ['blur', 'change']
        }
      ]"
      :class="[question.Type === 'group' ? 'mb' : question.Type === 'upload' || question.Type === 'screenshot' ? 'uploadWrapper' : '']">
      <!-- 输入框 -->
      <el-input v-if="question.Type === 'input'" v-model="questionForm[question.Id]"
        :disabled="question.TableQuestionType === 2 || (question.IsCopy && type === 'edit' && !isBaseline && questionForm.IsCurrentTaskAdd === 'False') || question.IsPreinstall || readingTaskState >= 2" />
      <!-- 多行文本输入框 -->
      <el-input v-if="question.Type === 'textarea'" v-model="questionForm[question.Id]" type="textarea"
        :disabled="question.TableQuestionType === 2 || (question.IsCopy && type === 'edit' && !isBaseline && questionForm.IsCurrentTaskAdd === 'False') || question.IsPreinstall || readingTaskState >= 2"
        :autosize="{ minRows: 2, maxRows: 4 }" />
      <!-- 下拉框 -->
      <el-select v-if="question.Type === 'select'" v-model="questionForm[question.Id]" clearable
        :multiple="question.OptionTypeEnum === 1"
        :disabled="(question.TableQuestionType === 2 || question.IsPreinstall || question.QuestionGenre === 2) || (question.IsCopy && type === 'edit' && !IsBaseline && questionForm.IsCurrentTaskAdd === 'False') || readingTaskState >= 2"
        @change="((val) => { formItemChange(val, question) })">
        <template v-if="question.TableQuestionType === 1">
          <el-option v-for="item in organList" :key="item.Id" :label="item[question.DataTableColumn]"
            :value="item[question.DataTableColumn]" />
        </template>
        <template v-else-if="question.TableQuestionType === 3 || question.QuestionGenre === 3">
          <el-option v-for="item of $d[question.DictionaryCode]" :key="item.id" :value="String(item.value)"
            :label="item.label" />
        </template>
        <template
          v-else-if="(question.TableQuestionType === 2 || question.QuestionGenre === 2) && question.DictionaryCode">
          <el-option v-for="item of $d[question.DictionaryCode]" :key="item.id" :value="String(item.value)"
            :label="item.label" />
        </template>
        <template v-else>
          <el-option v-for="val in question.TypeValue.split('|')" :key="val" :label="val" :value="val" />
        </template>

      </el-select>
      <!-- 单选 -->
      <el-radio-group v-if="question.Type === 'radio'" v-model="questionForm[question.Id]"
        :disabled="question.TableQuestionType === 2 || question.IsPreinstall || (question.IsCopy && type === 'edit' && !isBaseline && questionForm.IsCurrentTaskAdd === 'False') || readingTaskState >= 2"
        @change="((val) => { formItemChange(val, question) })">
        <template v-if="question.DictionaryCode">
          <el-radio v-for="val in $d[question.DictionaryCode]" :key="val.id" :label="String(val.value)">
            {{ val.label }}
          </el-radio>
        </template>
        <template v-else>
          <el-radio v-for="val in question.TypeValue.split('|')" :key="val.trim()" :label="val.trim()">
            {{ val.trim() }}
          </el-radio>
        </template>
      </el-radio-group>
      <!-- 复选框 -->
      <el-checkbox-group v-if="question.Type === 'checkbox'"
        :disabled="question.TableQuestionType === 2 || question.IsPreinstall || (question.IsCopy && type === 'edit' && !isBaseline && questionForm.IsCurrentTaskAdd === 'False') || readingTaskState >= 2"
        v-model="questionForm[question.Id]">
        <el-checkbox v-for="val in question.TypeValue.split('|')" :key="val" :label="val">
          {{ val }}
        </el-checkbox>
      </el-checkbox-group>
      <!-- 自动分类 -->
      <el-input v-if="question.Type === 'class' && question.ClassifyShowType === 1"
        v-model="questionForm[question.Id]" />
      <el-select v-if="question.Type === 'class' && question.ClassifyShowType === 2" v-model="questionForm[question.Id]"
        :disabled="!question.ClassifyEditType || question.IsPreinstall || readingTaskState >= 2"
        @change="(val) => { formItemChange(val, question) }">
        <el-option v-for="val in question.TypeValue.split('|')" :key="val" :label="val.trim()" :value="val.trim()" />
      </el-select>
      <el-radio-group v-if="question.Type === 'class' && question.ClassifyShowType === 3"
        v-model="questionForm[question.Id]"
        :disabled="!question.ClassifyEditType || question.IsPreinstall || readingTaskState >= 2"
        @change="(val) => { formItemChange(val, question) }">
        <template v-if="question.DictionaryCode">
          <el-radio v-for="val in $d[question.DictionaryCode]" :key="val.id" :label="String(val.value)">
            {{ val.label }}
          </el-radio>
        </template>
        <template v-else>
          <el-radio v-for="val in question.TypeValue.split('|')" :key="val.trim()" :label="val.trim()">
            {{ val.trim() }}
          </el-radio>
        </template>
      </el-radio-group>
      <!-- 自动计算 -->
      <!-- :precision="2" :step="0.1" :max="10" -->
      <div style="display: flex;justify-content: space-between;" v-if="question.Type === 'calculation'">
        <el-input v-if="question.Type === 'calculation'" v-model="questionForm[question.Id]"
          oninput="value=value.replace(/^\D*(\d*(?:.\d{0,2})?).*$/g, '$1')" disabled />
        <svg-icon v-if="question.ShowChartTypeEnum > 0 && taskInfo.IsReadingTaskViewInOrder === 1"
          icon-class="readingChart" class="svg-icon svg-readingChart" @click.stop="(e) => handleReadingChart({
            e,
            data: {
              TableQuestionId: question.Id,
              RowIndex: questionForm.RowIndex,
              QuestionName: question.QuestionName
            }
          })" />
      </div>
      <!-- 自增 -->
      <el-input v-if="question.Type === 'increment'" v-model="questionForm[question.Id]" disabled />
      <!-- 数值 -->
      <template v-if="question.Type === 'number' && (question.ImageMarkEnum === 1 || question.ImageMarkEnum === 2)">
        <div style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center;"
          v-if="question.ImageMarkTypeEnum === 1">
          <el-input type="text" @change="(val) => { formItemNumberChange(val, question) }"
            @input="numberInput(question.Id)"
            @blur="questionsSegmentMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] ? () => { } : handleMarkedQsBlur(questionForm[question.Id], questionForm, question.Id, question)"
            v-model="questionForm[question.Id]"
            :title="questionsSegmentMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] ? `${questionsSegmentMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].SegmentationName}\n${questionsSegmentMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].SegmentName}\n${questionForm[question.Id]}` : question.Remark"
            :disabled="(questionsSegmentMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] && question.ImageMarkEnum === 2) || question.ImageMarkEnum === 1 || question.IsPreinstall || readingTaskState >= 2"
            style="width: 150px;margin-right: 5px;">
            <template v-if="question.Unit !== 0" slot="append">
              {{ question.Unit !== 4 ? $fd('ValueUnit', question.Unit) : question.CustomUnit }}
            </template>
          </el-input>
          <svg-icon v-if="question.ShowChartTypeEnum > 0 && taskInfo.IsReadingTaskViewInOrder === 1"
            icon-class="readingChart" class="svg-icon svg-readingChart" @click.stop="(e) => handleReadingChart({
              e,
              data: {
                TableQuestionId: question.Id,
                RowIndex: questionForm.RowIndex,
                QuestionName: question.QuestionName
              }
            })" />
          <!-- 绑定 -->
          <el-button
            v-if="readingTaskState < 2 && (!questionsSegmentMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id])"
            size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 21, question })">
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:bind') }}
          </el-button>
          <!-- 查看 -->
          <el-button v-if="questionsSegmentMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id]" size="mini"
            type="text" @click="operateImageMarker({ operateStateEnum: 23, question })">
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:view') }}
          </el-button>
          <!-- 更改 -->
          <el-button
            v-if="readingTaskState < 2 && (questionsSegmentMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id])"
            size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 22, question })">
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:edit') }}
          </el-button>
          <!-- 移除 -->
          <el-button
            v-if="readingTaskState < 2 && (questionsSegmentMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id])"
            size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 24, question })">
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:remove') }}
          </el-button>
        </div>
        <div style="display: flex;flex-direction: row;justify-content: flex-start;align-items: center;" v-else>
          <el-input type="text" @change="(val) => { formItemNumberChange(val, question) }"
            @input="numberInput(question.Id)"
            @blur="questionsMarkStatus[question.Id] && questionsMarkStatus[question.Id].isMarked ? () => { } : handleMarkedQsBlur(questionForm[question.Id], questionForm, question.Id, question)"
            v-model="questionForm[question.Id]"
            :title="questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] ? questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].OrderMarkName : question.Remark"
            :disabled="(questionsMarkStatus[question.Id] && questionsMarkStatus[question.Id].isMarked && question.ImageMarkEnum === 2) || question.ImageMarkEnum === 1 || question.IsPreinstall || readingTaskState >= 2"
            style="width: 150px;margin-right: 5px;">
            <template v-if="question.Unit !== 0" slot="append">
              {{ question.Unit !== 4 ? $fd('ValueUnit', question.Unit) : question.CustomUnit }}
            </template>
          </el-input>
          <svg-icon v-if="question.ShowChartTypeEnum > 0 && taskInfo.IsReadingTaskViewInOrder === 1"
            icon-class="readingChart" class="svg-icon svg-readingChart" @click.stop="(e) => handleReadingChart({
              e,
              data: {
                TableQuestionId: question.Id,
                RowIndex: questionForm.RowIndex,
                QuestionName: question.QuestionName
              }
            })" />
          <!-- 测量 -->
          <el-button
            v-if="readingTaskState < 2 && (!questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] || (questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] && !questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].isMarked))"
            size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 1, question })">
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:measure') }}
          </el-button>
          <!-- 绑定 -->
          <el-button
            v-if="readingTaskState < 2 && (!questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] || (questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] && !questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].isMarked))"
            size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 0, question })">
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:bind') }}
          </el-button>
          <!-- 查看 -->
          <el-button
            v-if="questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] && questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].isMarked"
            size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 2, question })">
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:view') }}
          </el-button>
          <!-- 更改 -->
          <el-button
            v-if="readingTaskState < 2 && (questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] && questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].isMarked)"
            size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 3, question })">
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:edit') }}
          </el-button>
          <!-- 移除 -->
          <el-button
            v-if="readingTaskState < 2 && (questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] && questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].isMarked)"
            size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 4, question })">
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:remove') }}
          </el-button>
          <!-- 保存 -->
          <el-button
            v-if="readingTaskState < 2 && (questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] && !questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].isSaved)"
            size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 7, question })">
            <el-tooltip
              v-if="questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id] && !questionsMarkStatus[rowId ? `${rowId}_${question.Id}` : question.Id].isSaved"
              class="item" effect="dark" :content="$t('trials:reading:button:unsaved')" placement="bottom">
              <i class="el-icon-warning" style="color:red" />
            </el-tooltip>
            {{ $t('dicom3D:CustomizeQuestionFormItem:button:save') }}
          </el-button>
        </div>
      </template>
      <template v-else-if="question.Type === 'number'">
        <div style="display: flex;justify-content: space-between;">
          <el-select v-if="question.Type === 'number' && question.TypeValue" v-model="questionForm[question.Id]"
            clearable @change="((val) => { formItemChange(val, question) })">
            <el-option v-for="val in question.TypeValue.split('|')" :key="val" :label="val" :value="val" />
            <template v-if="question.Unit !== 0" slot="prefix">{{ question.Unit !== 4 ? $fd('ValueUnit', question.Unit)
              :
              question.CustomUnit }}</template>
            <template v-else-if="question.ValueType === 2" slot="prefix">%</template>
          </el-select>
          <el-input type="text" v-else-if="question.Type === 'number' && question.DataSource !== 1"
            :disabled="question.TableQuestionType === 2 || (question.IsCopy && type === 'edit' && !isBaseline && questionForm.IsCurrentTaskAdd === 'False') || question.IsPreinstall || readingTaskState >= 2"
            @change="((val) => { formItemNumberChange(val, question) })" @input="numberInput(question.Id)"
            @blur="handleBlur(questionForm[question.Id], questionForm, question.Id)"
            v-model="questionForm[question.Id]">
            <template slot="append" v-if="question.Unit !== 0">{{ question.Unit !== 4 ? $fd('ValueUnit', question.Unit)
              :
              question.CustomUnit }}</template>
          </el-input>
          <el-input type="text" v-else-if="question.Type === 'number' && question.DataSource === 1"
            :disabled="question.DataSource === 1"
            @input="numberInput(question.Id, true) || question.IsPreinstall || readingTaskState >= 2"
            @blur="handleCalculationBlur(calculationValue)" v-model="calculationValue">
            <template slot="append" v-if="question.Unit !== 0">{{ question.Unit !== 4 ? $fd('ValueUnit', question.Unit)
              :
              question.CustomUnit }}</template>
          </el-input>
          <svg-icon v-if="question.ShowChartTypeEnum > 0 && taskInfo.IsReadingTaskViewInOrder === 1"
            icon-class="readingChart" class="svg-icon svg-readingChart" @click.stop="(e) => handleReadingChart({
              e,
              data: {
                TableQuestionId: question.Id,
                RowIndex: questionForm.RowIndex,
                QuestionName: question.QuestionName
              }
            })" />
        </div>

      </template>
      <!-- 上传图像 -->
      <el-upload v-if="question.Type === 'upload' || question.Type === 'screenshot'"
        :disabled="readingTaskState === 2 || question.IsPreinstall || readingTaskState >= 2" action
        :accept="question.FileType" :limit="question.ImageCount === 0 ? 100 : question.ImageCount"
        :on-preview="handlePictureCardPreview"
        :before-upload="(file) => { return handleBeforeUpload(file, question.FileType, question.Type) }"
        :http-request="uploadScreenshot" :on-remove="handleRemove" :file-list="fileList"
        :class="{ disabled: question.ImageCount === 0 ? false : fileList.length >= question.ImageCount }">
        <el-button slot="default" class="el-icon-plus" v-if="readingTaskState < 2">
          {{ this.$t('common:button:upload') }}
        </el-button>
      </el-upload>
      <viewer v-if="(question.Type === 'upload' || question.Type === 'screenshot') && imgVisible" :ref="imageUrl"
        style="margin:0 10px;" :images="[imageUrl]">
        <img v-show="false" crossorigin="anonymous" :src="imageUrl" alt="Image">
      </viewer>
    </el-form-item>
  </div>
</template>
<script>
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
export default {
  name: 'QuestionTableFormItem',
  props: {
    isBaseline: {
      type: Boolean,
      required: true
    },
    questionForm: {
      type: Object,
      default() {
        return {}
      }
    },
    question: {
      type: Object,
      default() {
        return []
      }
    },
    criterionId: {
      type: String,
      required: true
    },
    calculationList: {
      type: Array,
      default() {
        return []
      }
    },
    readingTaskState: {
      type: Number,
      required: true
    },
    visitTaskId: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'add'
    },
    questionsMarkStatus: {
      type: Object,
      default() {
        return {}
      }
    },
    questionsSegmentMarkStatus: {
      type: Object,
      default() {
        return {}
      }
    },
    parentQsId: {
      type: String,
      default: ''
    },
  },
  computed: {
    calculationValue: {
      get() {
        return this.questionForm[this.question.Id]
      },
      set() {

      }
    }
  },
  data() {
    return {
      addOrEdit: { visible: false, title: '' },
      fileList: [],
      accept: '.png,.jpg,.jpeg',
      imgVisible: false,
      imageUrl: '',
      urls: [],
      organList: [],
      QuestionsList: [],
      QuestionsForm: {},
      digitPlaces: 2,
      rowId: '',
      taskInfo: {}
    }
  },
  watch: {
    questionForm: {
      deep: true,
      immediate: true,
      handler(v, oldv) {
        // try {
        //   if (!v[this.question.Id] || !oldv[this.question.Id]) return
        // } catch (e) {
        // }
        // this.formItemNumberChange(this.question.Id, false)
        this.rowId = this.questionForm.RowId
      }
    },
    questionsMarkStatus: {
      deep: true,
      immediate: true,
      handler(v) {
        this.$forceUpdate()
      }
    }
  },
  mounted() {
    this.taskInfo = JSON.parse(sessionStorage.getItem('taskInfo'))
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    if (this.question.Type === 'upload' || this.question.Type === 'screenshot') {
      if (this.questionForm[this.question.Id]) {
        this.urls = this.questionForm[this.question.Id].split('|')
        this.fileList = []
        this.urls.map((url, index) => {
          var index = url.lastIndexOf('.')
          var suffix = url.substring(index + 1, url.length)
          this.fileList.push({ name: `${this.$t('trials:emailManageCfg:title:fileName')}${index + 1}(${suffix})`, url: `${url}` })
        })
      }
    }
    DicomEvent.$on('operateImageMarkerTable', (data) => {
      let { operateStateEnum, QuestionId, picturePath } = data
      if (this.question.Id === QuestionId) {
        this.operateImageMarker({ operateStateEnum, question: this.question, picturePath })
      }
    })
    if (this.type === 'edit') return
  },
  methods: {
    handleReadingChart(row) {
      this.$emit('handleReadingChart', row)
    },
    numberInput(id, notId = false) {
      if (notId) {
        this.calculationValue = this.calculationValue.toUpperCase();
      } else {
        this.questionForm[id] = this.questionForm[id].toUpperCase();
      }
    },
    validatorNumberInput(rule, value, callback) {
      let reg = new RegExp(/^(?:-?(?:(?:0|[1-9]\d*)(?:\.\d+)?|\.\d+)|NE)$/, 'g')
      if (value === '' || value == null) {
        callback();
      } else {
        if (!reg.test(value)) {
          callback(new Error(this.$t('trials:reading:ruleMessage:validatorNumberInput')));
        } else {
          callback();
        }
      }
    },
    save() {
    },
    openAddTableCol(row) {
      this.addOrEdit.visible = true
      this.addOrEdit.title = row.QuestionName + this.$t('trials:readingUnit:qsList:title:tableQs')
      this.QuestionsList = row.TableQuestions.Questions
      this.AnswersList = row.TableQuestions.Answers
      this.QuestionsForm = {}
    },
    formItemChange(v, question) {
      if (question.Childrens && question.Childrens.length > 0) {
        this.resetChild(question.Childrens)
      }
      if (question.TableQuestionType === 1 && question.RelationQuestions.length > 0) {
        var index = this.organList.findIndex(item => item[question.DataTableColumn] === v)
        if (index < 0) return
        var selected = this.organList[index]
        this.question.RelationQuestions.map(qs => {
          var val = selected[qs.DataTableColumn]
          // if (typeof val === 'boolean') {
          //   // val = String(val)
          // }
          this.$emit('setFormItemData', { key: qs.Id, val: val, question: qs })
        })
      } else {
        this.$emit('setFormItemData', { key: question.Id, val: v, question: question })
      }
      this.$emit('formItemTableNumberChange', v, question)
    },
    handleBlur(value, a, b) {
      if (!value) return false
      if (!isNaN(parseFloat(value))) {
        this.$set(a, b, parseFloat(value).toFixed(this.digitPlaces))
      }
    },
    handleMarkedQsBlur(value, a, b, question) {
      this.$set(a, b, !isNaN(parseFloat(value)) ? parseFloat(value).toFixed(this.digitPlaces) : value)
      question.IsTableQuestion = true
      // this.$emit('operateImageMarker', {operateStateEnum: 6, question})
    },
    handleCalculationBlur(v) {
      if (!v) return false
      if (!isNaN(parseFloat(v))) {
        this.calculationValue = parseFloat(v).toFixed(this.digitPlaces)
      }
    },
    limitInput(value, q) {
      if (value.indexOf('.') > -1) {
        if (value.split('.')[1].length >= this.digitPlaces) {
          this.$set(this.questionForm, q.Id, parseFloat(value).toFixed(this.digitPlaces))
        }
      } else {
      }
    },
    logic(rules, num = 0) {
      let isNE = false
      try {
        if (rules.CalculateQuestionList.length === 0) {
          return false
        }
        let dataArr = []
        var count = 0
        var maxList = [], minList = []
        rules.CalculateQuestionList.forEach((o, i) => {
          if (this.questionForm[o.TableQuestionId] === 'NE') {
            isNE = true
          }
          if (rules.CustomCalculateMark > 4 && rules.CustomCalculateMark < 10) {
            if (i !== 0) {
              switch (rules.CustomCalculateMark) {
                case 7:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    count += parseFloat(this.questionForm[o.TableQuestionId])
                  }

                  if (i === rules.CalculateQuestionList.length - 1) {
                    num = count / rules.CalculateQuestionList.length
                  }
                  break;
                case 8:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    maxList.push(this.questionForm[o.TableQuestionId])
                  }

                  if (i === rules.CalculateQuestionList.length - 1) {
                    num = minList.length > 0 ? Math.max(...maxList) : 0
                  }
                  break;
                case 9:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    minList.push(this.questionForm[o.TableQuestionId])
                  }

                  if (i === rules.CalculateQuestionList.length - 1) {
                    num = minList.length > 0 ? Math.min(...minList) : 0
                  }
                  break;
              }
            } else {
              if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                maxList.push(this.questionForm[o.TableQuestionId])
                minList.push(this.questionForm[o.TableQuestionId])
                count = parseFloat(this.questionForm[o.TableQuestionId])
                num = parseFloat(this.questionForm[o.TableQuestionId])
                dataArr.push(num)
              }

            }
          } else {
            if (i !== 0) {
              switch (rules.CustomCalculateMark) {
                case 1:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    num += parseFloat(this.questionForm[o.TableQuestionId])
                  }

                  break;
                case 2:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    num -= parseFloat(this.questionForm[o.TableQuestionId])
                  }

                  break;
                case 3:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    num *= parseFloat(this.questionForm[o.TableQuestionId])
                  }

                  break;
                case 4:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    if (parseFloat(this.questionForm[o.TableQuestionId]) === 0) {
                      num = 0
                    } else {
                      num /= parseFloat(this.questionForm[o.TableQuestionId])
                    }
                  }

                  break;
                case 10:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                  }
                  num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => {
                    return acc + (typeof curr === "number" ? curr : 0);
                  }, 0) / dataArr.length;
                  break;
                case 11:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                  }
                  num = Math.max(...dataArr);
                  break;
                case 12:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                  }
                  num = Math.min(...dataArr);
                  break;
              }
            } else {
              if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                num = parseFloat(this.questionForm[o.TableQuestionId])
              }

            }
          }
        })
      } catch (e) {
        console.log(e)
      }
      if (isNE) {
        return 'NE'
      }
      if (rules.ValueType === 2) {
        num = num * 100
      }
      return num.toFixed(this.digitPlaces)
    },
    formItemNumberChange(v, question) {
      this.$emit('formItemTableNumberChange', v, question)
      this.$emit('setFormItemData', { key: question.Id, val: v, question: question })
      // this.$emit('formItemTableNumberChange', v, question)
    },
    resetChild(obj) {
      obj.forEach(i => {
        this.$emit('resetFormItemData', i.Id)
        if (i.Childrens && i.Childrens.length > 0) {
          this.resetChild(i.Childrens)
        }
      })
    },
    resetFormItemData(v) {
      this.$emit('resetFormItemData', v)
    },
    setFormItemData(obj) {
      this.$emit('setFormItemData', obj)
    },
    async operateImageMarker(obj) {
      obj.question.IsTableQuestion = true
      obj.question.RowId = this.rowId
      obj.question.ParentQsId = this.parentQsId
      if (obj.operateStateEnum === 7 && this.questionForm[obj.question.Id] && isNaN(parseFloat(this.questionForm[obj.question.Id])) && this.questionForm[obj.question.Id] !== 'NE') return false
      if (obj.operateStateEnum === 7) {
        // 保存表格问题标记
        // if (!obj.question.RowId) {
        //   // 生成rowId
        //   const loading = this.$loading({ fullscreen: true })
        //   try {
        //     let params = {
        //       questionId: this.parentQsId,
        //       RowIndex: this.questionForm.RowIndex,
        //       visitTaskId: this.visitTaskId,
        //       trialId: this.$route.query.trialId,
        //       answerList: [],
        //     }
        //     let res = await submitTableQuestion(params)
        //     // this.$emit('save',rowId)
        //     this.QuestionsForm.RowId = res.Result.RowId
        //     obj.rowId = res.Result.RowId
        //     this.rowId = res.Result.RowId
        //     loading.close()
        //   } catch(e) {
        //     loading.close()
        //   }
        // }
        obj.rowIndex = this.questionForm.RowIndex
        // obj.parentQsId = this.parentQsId
        obj.answer = this.questionForm[obj.question.Id]
      }
      this.$emit('operateImageMarker', obj)
    },
    async uploadScreenshot(param) {
      if (!this.visitTaskId) return
      const loading = this.$loading({
        target: document.querySelector('.el-dialog'),
        fullscreen: false,
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      })
      var fileName = param.file.name
      var index = fileName.lastIndexOf('.')
      var suffix = fileName.substring(index + 1, fileName.length)
      var file = await this.fileToBlob(param.file)
      // let res = await this.OSSclient.put(`/${this.$route.query.trialId}/Customize/${this.visitTaskId}/${fileName}`, file)
      const taskInfo = JSON.parse(sessionStorage.getItem('taskInfo'))
      const subjectId = taskInfo.SubjectId
      let res = await this.OSSclient.put(`/${this.$route.query.trialId}/Read/${subjectId}/${this.visitTaskId}/${fileName}`, file)
      this.fileList.push({ name: `${this.$t('trials:emailManageCfg:title:fileName')}${this.fileList.length + 1}(${suffix})`, url: this.$getObjectName(res.url) })
      this.urls.push(this.$getObjectName(res.url))
      this.$emit('setFormItemData', { key: this.question.Id, val: this.urls.length > 0 ? this.urls.join('|') : '', question: this.question })
      loading.close()
    },
    handleBeforeUpload(file, accept, type) {
      if (type === 'screenshot') {
        accept = '.png,.jpeg,.jpg'
      }
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name, accept) || accept === '-1') {
        return true
      } else {
        const msg = this.$t('trials:adReview:title:msg4').replace('xxx', accept)
        this.$alert(msg)
        return false
      }
    },
    checkFileSuffix(fileName, accept) {
      var index = fileName.lastIndexOf('.')
      var suffix = fileName.substring(index + 1, fileName.length)
      if (accept.toLocaleLowerCase().search(suffix.toLocaleLowerCase()) === -1) {
        return false
      } else {
        return true
      }
    },
    // 预览图片
    handlePictureCardPreview(file) {
      var suffix = file.url.substring(file.url.lastIndexOf(".") + 1)
      suffix = suffix ? suffix.toLowerCase() : ''
      if (['ppt',
        'pptx',
        'doc',
        'docx',
        'xls',
        'xlsx'].includes(suffix)) {
        // window.open(this.OSSclientConfig.basePath + file.url,'_blank')
        this.$onlyOffice({
          path: file.url,
          type: suffix,
          title: file.name
        })
        // this.currentPath = file.url
        // this.currentType = suffix
        // this.previewVisible = true
      } else if (['pdf'].includes(suffix)) {
        this.$preview({
          path: file.url,
          type: 'pdf',
          title: file.name,
        })
      } else {
        this.imageUrl = this.OSSclientConfig.basePath + file.url
        this.imgVisible = true
        this.$nextTick(() => {
          this.$refs[this.imageUrl].$viewer.show()
        })
      }
    },
    // 删除图片
    handleRemove(file, fileList) {
      if (file && file.status === "success") {
        this.imageUrl = ''
        this.fileList.splice(this.fileList.findIndex(f => f.url === file.url), 1)
        this.fileList.forEach((i, index) => {
          i.name = `${this.$t('trials:emailManageCfg:title:fileName')}${index + 1}`
        })
        this.urls.splice(this.fileList.findIndex(f => f === file.url), 1)
        this.$emit('setFormItemData', { key: this.question.Id, val: this.urls.length > 0 ? this.urls.join('|') : '', question: this.question })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.criterion-table-form-item {
  .el-form-item {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
  }

  ::v-deep .el-select .el-input__prefix {
    left: calc(100% - 50px);
    cursor: pointer;
  }

  ::v-deep .el-select .el-input__inner {
    padding-left: 15px;
    padding-right: 50px;
  }

  .el-input {
    width: 100%;
  }

  .el-select {
    width: 100%;
  }

  .mb {
    margin-bottom: 0px;
  }

  .disabled {
    ::v-deep .el-upload--picture-card {
      display: none;
    }
  }

  .uploadWrapper {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

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