<template>
  <div class="criterion-form-item">
    <div
      v-if="(!!question.GroupName && question.Type === 'group') && ((question.ShowQuestion === 1 && question.ParentTriggerValueList.includes(String(questionForm[question.ParentId]))) || question.ShowQuestion === 0)"
      style="font-weight: bold;font-size: 16px;margin: 5px 0px;color:#fff;">
      {{ question.GroupName }}
    </div>
    <div
      v-if="(question.Type === 'table' || question.Type === 'basicTable') && ((question.ShowQuestion === 1 && question.ParentTriggerValueList.includes(String(questionForm[question.ParentId]))) || question.ShowQuestion === 0)"
      style="font-weight: bold;font-size: 14px;margin: 5px 0px;">
      <div style="display: flex;justify-content: space-between;align-items: center;color:#fff;margin: 10px 0 5px">
        <span :title="question.Remark">{{ question.QuestionName }}</span>
        <el-button size="mini"
          v-if="readingTaskState < 2 && !question.IsPreinstall && (question.AddDeleteTypeEnum === 0 || (isBaseline && question.AddDeleteTypeEnum === 1) || (!isBaseline && question.AddDeleteTypeEnum === 2))"
          @click="openAddTableCol(question)">
          {{ $t('common:button:add') }}
        </el-button>
      </div>
      <el-table :data="questionForm[question.Id]"
        v-if="(question.ShowQuestion === 1 && question.ParentTriggerValueList.includes(String(questionForm[question.ParentId]))) || question.ShowQuestion === 0">
        <el-table-column :label="$t('CustomizeQuestionFormItem:label:OrderMark')" width="60px" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ question.OrderMark }}{{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column :prop="item.Id" :label="item.QuestionName" :key="item.Id"
          v-for="item of question.TableQuestions.Questions" show-overflow-tooltip :render-header="renderHeader">
          <template slot-scope="scope">
            <span v-if="item.Type === 'upload' || item.Type === 'screenshot'">
              {{ scope.row[item.Id] === '' ? '' : scope.row[item.Id] ? scope.row[item.Id].split('|').length : '' }}
            </span>
            <span v-else-if="item.Type === 'number'">
              {{ scope.row[item.Id] ? parseFloat(scope.row[item.Id]).toFixed(digitPlaces) : null }}
            </span>
            <span v-else-if="item.Type === 'select' && item.OptionTypeEnum === 1">
              {{ scope.row[item.Id] && Array.isArray(scope.row[item.Id]) ?
                scope.row[item.Id].join(',') : scope.row[item.Id] }}
            </span>
            <span v-else>
              {{ scope.row[item.Id] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('common:action:action')" show-overflow-tooltip width="100px" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="openAddTableCol(question, scope.$index)">
              {{ question.IsPreinstall ?
                $t('CustomizeQuestionFormItem:button:assessment') : readingTaskState >= 2 ? $t('common:button:view') :
                  $t('common:button:edit') }}
            </el-button>
            <el-button type="text" size="mini" :disabled="addOrEdit.visible"
              v-if="readingTaskState < 2 && (scope.row.IsCurrentTaskAdd === 'True' || !question.IsCopyLesions || isBaseline) && !question.IsPreinstall && (question.AddDeleteTypeEnum === 0 || (isBaseline && question.AddDeleteTypeEnum === 1) || (!isBaseline && question.AddDeleteTypeEnum === 2))"
              @click="deleteTableCol(question, scope.$index)">
              {{ $t('common:button:delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-if="addOrEdit.visible" v-dialogDrag :title="addOrEdit.title" :visible.sync="addOrEdit.visible"
        :close-on-click-modal="false" :close-on-press-escape="false" width="400px" :modal="false"
        :before-close="beforeClose">
        <div>
          <el-form ref="tableQsForm" :model="QuestionsForm" v-loading="loading" size="small">
            <QuestionTableFormItem v-for="(item) in QuestionsList" :key="item.Id" :question="item"
              :parentQsId="parentQsId" :isBaseline="isBaseline" :reading-task-state="readingTaskState"
              :question-form="QuestionsForm" :visit-task-id="visitTaskId" :criterion-id="criterionId"
              :type="addOrEdit.type" :calculationList="calculationList" :questionsMarkStatus="questionsMarkStatus"
              :questionsSegmentMarkStatus="questionsSegmentMarkStatus"
              @formItemTableNumberChange="formItemTableNumberChange" @resetFormItemData="resetTableFormItemData"
              @setFormItemData="setFormTableItemData" @operateImageMarker="operateImageMarker" @save="save"
              @handleReadingChart="handleReadingChart" />
          </el-form>
        </div>
        <div slot="footer" v-if="readingTaskState < 2">
          <el-button size="small" @click="handleCancel">
            {{ $t('common:button:cancel') }}
          </el-button>
          <!-- 保存 -->
          <el-button size="small" class="my_upload_btn" @click="handleSave">
            {{ $t('common:button:save') }}
          </el-button>
        </div>
      </el-dialog>
    </div>
    <template v-else>
      <el-form-item
        v-if="(question.ShowQuestion === 1 && question.ParentTriggerValueList.includes(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.includes(isNaN(parseFloat(questionForm[question.RelevanceId])) ? questionForm[question.RelevanceId] : questionForm[question.RelevanceId].toString())))) && question.Type !== 'group' && question.Type !== 'summary',
            message: $t('common:ruleMessage:specify'), 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 || readingTaskState === 2" />
        <!-- 多行文本输入框 -->
        <el-input v-if="question.Type === 'textarea'" v-model="questionForm[question.Id]" type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }" :disabled="readingTaskState === 2" />
        <!-- 下拉框 -->
        <el-select v-if="question.Type === 'select'" v-model="questionForm[question.Id]" clearable
          :multiple="question.OptionTypeEnum === 1"
          :disabled="(question.TableQuestionType === 2 || question.QuestionGenre === 2) && !!question.DictionaryCode || 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.trim()" :label="val.trim()"
              :value="val.trim()" />
          </template>

        </el-select>
        <!-- 单选 -->
        <el-radio-group v-if="question.Type === 'radio'" v-model="questionForm[question.Id]"
          @change="((val) => { formItemChange(val, question) })" :disabled="readingTaskState === 2">
          <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'" v-model="questionForm[question.Id]"
          :disabled="readingTaskState === 2">
          <el-checkbox v-for="val in question.TypeValue.split('|')" :key="val" :label="val.trim()">
            {{ val.trim() }}
          </el-checkbox>
        </el-checkbox-group>
        <!-- 自动分类 -->
        <el-input v-if="question.Type === 'class' && question.ClassifyShowType === 1"
          v-model="questionForm[question.Id]" :disabled="!question.ClassifyEditType || readingTaskState === 2" />
        <el-select v-if="question.Type === 'class' && question.ClassifyShowType === 2"
          v-model="questionForm[question.Id]" :disabled="!question.ClassifyEditType || 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 || 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-input v-if="question.Type === 'class' && question.ClassifyShowType === 4" type="number"
          :disabled="!question.ClassifyEditType || readingTaskState === 2" v-model="questionForm[question.Id]"
          @change="(val) => { formItemNumberChange(val, question) }" />
        <!-- 自动计算 -->
        <!-- :precision="2" :step="0.1" :max="10" -->
        <div style="display: flex;justify-content: space-between;" v-if="question.Type === 'calculation'">
          <el-input v-model="questionForm[question.Id]"
            @input="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: {
                QuestionId: question.Id,
                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[question.Id] ? () => { } : handleMarkedQsBlur(questionForm[question.Id], questionForm, question.Id, question)"
              v-model="questionForm[question.Id]"
              :title="questionsSegmentMarkStatus[question.Id] ? `${questionsSegmentMarkStatus[question.Id].SegmentationName}\n${questionsSegmentMarkStatus[question.Id].SegmentName}\n${questionForm[question.Id]}` : question.Remark"
              :disabled="(questionsSegmentMarkStatus[question.Id] && question.ImageMarkEnum === 2) || question.ImageMarkEnum === 1 || 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: {
                  QuestionId: question.Id,
                  QuestionName: question.QuestionName
                }
              })" />
            <!-- 绑定 -->
            <el-button v-if="readingTaskState < 2 && (!questionsSegmentMarkStatus[question.Id])" size="mini" type="text"
              @click="operateImageMarker({ operateStateEnum: 21, question })">
              {{ $t('dicom3D:CustomizeQuestionFormItem:button:bind') }}
            </el-button>
            <!-- 查看 -->
            <el-button v-if="questionsSegmentMarkStatus[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[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[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[question.Id] ? questionsMarkStatus[question.Id].OrderMarkName : question.Remark"
              :disabled="(questionsMarkStatus[question.Id] && questionsMarkStatus[question.Id].isMarked && question.ImageMarkEnum === 2) || question.ImageMarkEnum === 1 || 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: {
                  QuestionId: question.Id,
                  QuestionName: question.QuestionName
                }
              })" />
            <!-- 测量 -->
            <el-button
              v-if="readingTaskState < 2 && (!questionsMarkStatus[question.Id] || (questionsMarkStatus[question.Id] && !questionsMarkStatus[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[question.Id] || (questionsMarkStatus[question.Id] && !questionsMarkStatus[question.Id].isMarked))"
              size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 0, question })">
              {{ $t('dicom3D:CustomizeQuestionFormItem:button:bind') }}
            </el-button>
            <!-- 查看 -->
            <el-button v-if="questionsMarkStatus[question.Id] && questionsMarkStatus[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[question.Id] && questionsMarkStatus[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[question.Id] && questionsMarkStatus[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[question.Id] && !questionsMarkStatus[question.Id].isSaved)"
              size="mini" type="text" @click="operateImageMarker({ operateStateEnum: 5, question })">
              <el-tooltip v-if="questionsMarkStatus[question.Id] && !questionsMarkStatus[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) => { formItemNumberChange(val, question) }" :disabled="readingTaskState === 2">
              <el-option v-for="val in question.TypeValue.split('|')" :key="val" :label="val.trim()"
                :value="val.trim()" />
              <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" @change="(val) => { formItemNumberChange(val, question) }"
              v-else-if="question.Type === 'number' && !question.TypeValue && question.DataSource !== 1"
              @input="numberInput(question.Id)" @blur="handleBlur(questionForm[question.Id], questionForm, question.Id)"
              v-model="questionForm[question.Id]" :disabled="readingTaskState === 2">
              <!-- <template slot="append">1</template> -->
              <template slot="append" v-if="question.Unit !== 0">{{ question.Unit !== 4 ? $fd('ValueUnit',
                question.Unit)
                :
                question.CustomUnit }}</template>
              <template slot="append" v-else-if="question.ValueType === 2">%</template>
            </el-input>
            <el-input type="text" @input="numberInput(question.Id)"
              v-else-if="question.Type === 'number' && !question.TypeValue && question.DataSource === 1"
              @blur="handleBlur(questionForm[question.Id], questionForm, question.Id)"
              :disabled="question.DataSource === 1 || readingTaskState === 2" v-model="questionForm[question.Id]">
              <!-- <template slot="append">2</template> -->
              <template slot="append" v-if="question.Unit !== 0">{{ question.Unit !== 4 ? $fd('ValueUnit',
                question.Unit)
                :
                question.CustomUnit }}</template>
              <template slot="append" v-else-if="question.ValueType === 2">%</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: {
                  QuestionId: question.Id,
                  QuestionName: question.QuestionName
                }
              })" />
          </div>
        </template>
        <!-- 上传图像 -->
        <el-upload v-if="question.Type === 'upload' || question.Type === 'screenshot'"
          :disabled="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>
    </template>

    <template
      v-if="question.Childrens && question.Childrens.length > 0 && question.Type !== 'table' && question.Type !== 'basicTable'">
      <QuestionFormItem v-for="(item) in question.Childrens" :key="item.Id" :question="item" :isBaseline="isBaseline"
        :isNoneDicom="isNoneDicom" :reading-task-state="readingTaskState" :question-form="questionForm"
        :visit-task-id="visitTaskId" :criterion-id="criterionId" :calculationList="calculationList"
        :questionMarkInfoList="questionMarkInfoList" :questionsMarkStatus="questionsMarkStatus"
        :questionsSegmentMarkStatus="questionsSegmentMarkStatus" @formItemNumberChange="formItemNumberChange"
        @setFormItemData="setFormItemData" @resetFormItemData="resetFormItemData" @getQuestions="getQuestions"
        @operateImageMarker="operateImageMarker" @unBindAnnotationToQuestion="unBindAnnotationToQuestion"
        @handleReadingChart="handleReadingChart" @saveSegmentBindingAndAnswer="saveSegmentBindingAndAnswer" />
    </template>

    <!-- <base-model :config="addOrEdit"
      class="my_dialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="400px"
      :modal="false"
      v-dialogDrag
    >
      
    </base-model> -->
    <!-- 预览文件 -->
    <!-- <el-dialog v-if="previewVisible" :visible.sync="previewVisible" :title="$t('common:button:preview')"
      :fullscreen="true" append-to-body custom-class="base-dialog-wrapper">
      <div class="base-modal-body" style="border: 2px solid #ccc; padding: 10px">
        <PreviewFile v-if="previewVisible" :file-path="currentPath" :file-type="currentType" />
      </div>
    </el-dialog> -->
  </div>
</template>
<script>
import { deleteReadingRowAnswer, getQuestionCalculateRelation, submitTableQuestion, deleteCustomTag } from '@/api/trials'
import QuestionTableFormItem from './QuestionTableFormItem'
import BaseModel from '@/components/BaseModel'
// import PreviewFile from '@/components/PreviewFile/index'
import { mapGetters } from 'vuex'
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
import {
  utilities as csUtils
  // getEnabledElementByIds
} from '@cornerstonejs/core'
export default {
  name: 'QuestionFormItem',
  components: {
    QuestionTableFormItem,
    BaseModel,
    // PreviewFile
  },
  props: {
    isBaseline: {
      type: Boolean,
      required: true
    },
    questionForm: {
      type: Object,
      default() {
        return {}
      }
    },
    question: {
      type: Object,
      default() {
        return {}
      }
    },
    criterionId: {
      type: String,
      required: true
    },
    readingTaskState: {
      type: Number,
      required: true
    },
    visitTaskId: {
      type: String,
      default: ''
    },
    calculationList: {
      type: Array,
      default: []
    },
    questionMarkInfoList: {
      type: Array,
      default: []
    },
    questionsMarkStatus: {
      type: Object,
      default() {
        return {}
      }
    },
    questionsSegmentMarkStatus: {
      type: Object,
      default() {
        return {}
      }
    },
    isNoneDicom: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      addOrEdit: { visible: false, title: '', width: '400px' },
      fileList: [],
      accept: '.png,.jpg,.jpeg',
      imgVisible: false,
      imageUrl: '',
      urls: [],
      organList: [],
      QuestionsList: [],
      QuestionsForm: {},
      AnswersList: [],
      loading: false,
      RowIndex: 0,
      RowId: null,
      digitPlaces: 2,
      CalculationTabelList: [],
      classArr: [],
      // previewVisible: false,
      // currentPath: '',
      // currentType: '',
      markTableQuestions: [],
      parentQsId: '',
      taskInfo: {}
    }
  },
  computed: {
    ...mapGetters(['operateInfo'])
  },
  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)
        try {
          if (!v || !v[this.question.Id] || !oldv || !oldv[this.question.Id])
            return
        } catch (e) {
          console.log(e, v)
        }
        if (this.question.Type === 'class') {
          this.$emit("setFormItemData", { key: this.question.Id, val: v[this.question.Id], question: v })
        }
      }
    },
    readingTaskState: {
      deep: true,
      immediate: true,
      handler(v, oldv) {
        // console.log(v)
      }
    },
    operateInfo: {
      immediate: true,
      handler(v) {

        let i = v.findIndex(i => i.QuestionId === this.question.Id)

        if (i === -1) return
        // const { parentQsId, rowId } = v
        // if (this.question.Id !== parentQsId) return

        if (this.addOrEdit.visible) {
          // 如果不是当前窗口绑定的标记如何处理？
          this.setAnswerToQuestion(v)
        } else {
          console.log(v)
          if (v.length === 1) {
            const { parentQsId, rowId } = v[0]
            if (!parentQsId && !rowId) return
            let arr = this.questionForm[parentQsId]
            if (!arr || !Array.isArray(arr)) return
            let i = arr.findIndex(i => i.RowId === rowId)
            if (i === -1) return
            this.openAddTableCol(this.question, i)
          }

        }
      }
    },
    'addOrEdit.visible': {
      handler() {
        DicomEvent.$emit('opentableCol', { visible: this.addOrEdit.visible })
      }
    }
  },

  mounted() {
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.taskInfo = JSON.parse(sessionStorage.getItem('taskInfo'))
    // if (this.question.Type === 'class') {
    //   this.ClassifyAlgorithmsList = JSON.parse(this.question.ClassifyAlgorithms)
    // }
    // setInterval(()=> {
    //   if (this.question.Type === 'class') {
    //     let o = this.ClassifyAlgorithmsList.find(v => {
    //       return this.questionForm[this.question.ClassifyQuestionId] >= v.gt && this.questionForm[this.question.ClassifyQuestionId] < v.lt
    //     })
    //     if (this.questionForm[this.question.ClassifyQuestionId]) {
    //       this.questionForm[this.question.Id] = o ? o.label : null
    //     } else {
    //       this.questionForm[this.question.Id] = null
    //     }
    //   }
    // }, 300)
    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}` })
        })
      }
    }
    if (this.question.Type === 'table' || this.question.Type === 'baiscTable') {
      this.getQuestionCalculateRelation()
      if (this.questionForm[this.question.Id]) {
        this.QuestionsForm = {}
        this.question.TableQuestions.Questions.forEach(v => {
          if (v.Type === 'number') {
            this.$set(this.QuestionsForm, v.Id, 0)
          } else {
            this.$set(this.QuestionsForm, v.Id, '')
          }
        })
      }
    }

    DicomEvent.$on('openAddTableCol', (data) => {
      let { RowId } = data
      if (this.questionForm[this.question.Id] && Array.isArray(this.questionForm[this.question.Id]) && this.questionForm[this.question.Id].length > 0) {
        let index = this.questionForm[this.question.Id].findIndex(item => item.RowId === RowId)
        if (!!~index) {
          this.openAddTableCol(this.question, index)
        }
      }
    })
    DicomEvent.$on('closeAddTableCol', (data) => {
      this.handleCancel()
    })
    DicomEvent.$on('operateImageMarker', (data) => {
      let { operateStateEnum, QuestionId, picturePath, visitTaskId } = data
      if (this.question.Id === QuestionId && visitTaskId === this.visitTaskId) {
        this.operateImageMarker({ operateStateEnum, question: this.question, picturePath })
      }
    })
    DicomEvent.$on('setTableQuestionAnswer', async (DATA) => {
      let { id, answer, ParentQsId, data } = DATA
      // console.log(ParentQsId, this.question.Id)
      if (this.question.Id === ParentQsId) {
        this.QuestionsForm[id] = answer
        if (data.RowId) {
          let i = this.AnswersList.findIndex(i => i.RowId === this.QuestionsForm.RowId)
          this.AnswersList[i][id] = this.QuestionsForm[id]
          this.$emit('setFormItemData', { key: this.question.Id, val: this.AnswersList, question: this.question })
          this.formItemNumberChange(this.question.Id, true)
          this.$emit('saveSegmentBindingAndAnswer', [data])
        } else {
          try {
            // loading = this.$loading({ fullscreen: true })
            let answers = []
            let reg = new RegExp(/^[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}$/)
            for (const k in this.QuestionsForm) {
              if (reg.test(k)) {
                if (answers.findIndex(i => i.tableQuestionId === k) === -1) {
                  answers.push({ tableQuestionId: k, answer: this.QuestionsForm[k] })
                }
              }
            }
            this.QuestionsList.forEach(k => {
              if (reg.test(k.Id)) {
                if (answers.findIndex(i => i.tableQuestionId === k.Id) === -1) {
                  answers.push({ tableQuestionId: k.Id, answer: '' })
                }
              }
            })
            let params = {
              questionId: this.question.Id,
              RowIndex: this.questionForm[this.question.Id].length + 1,
              RowId: this.QuestionsForm.RowId ? this.QuestionsForm.RowId : '',
              visitTaskId: this.visitTaskId,
              trialId: this.$route.query.trialId,
              answerList: answers
            }
            let res = await submitTableQuestion(params)
            if (res.IsSuccess) {
              this.QuestionsForm.RowId = res.Result.RowId
              // obj.rowId = res.Result.RowId 
              data.RowId = res.Result.RowId
              this.AnswersList.push(this.QuestionsForm)
              this.$emit('setFormItemData', { key: this.question.Id, val: this.AnswersList, question: this.question })
              this.formItemNumberChange(this.question.Id, true)
              this.$emit('saveSegmentBindingAndAnswer', [data])
            }
          } catch (e) {
            console.log(e)
          }
        }
      }
    })
  },
  methods: {
    saveSegmentBindingAndAnswer(list) {
      this.$emit('saveSegmentBindingAndAnswer', list)
    },
    handleReadingChart(row) {
      this.$emit('handleReadingChart', row)
    },
    numberInput(id) {
      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 === '') {
        callback();
      } else {
        if (!reg.test(value)) {
          callback(new Error(this.$t('trials:reading:ruleMessage:validatorNumberInput')));
        } else {
          callback();
        }
      }
    },
    limitInput(value, a, b) {
      if (value.indexOf('.') > -1) {
        if (value.split('.')[1].length >= this.digitPlaces) {
          this.$set(a, b, parseFloat(value).toFixed(this.digitPlaces))
        }
      }
    },
    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)
      this.$emit('operateImageMarker', { operateStateEnum: 6, question })
    },
    async deleteTableCol(row, index) {
      let data = row.TableQuestions.Answers[index]
      let hasMark = Object.keys(data).some(key => this.questionsMarkStatus[`${data.RowId}_${key}`] && this.questionsMarkStatus[`${data.RowId}_${key}`].isMarked)
      if (hasMark) return this.$alert(this.$t('dicom3D:ReadPage:alert:QuestionToMarkNoDel'))
      let loading = null
      try {
        let confirm = await this.$confirm(this.$t('trials:uploadNonDicoms:message:msg1'))
        if (confirm !== 'confirm') return
        loading = this.$loading({ fullscreen: true })
        let param = {
          visitTaskId: this.visitTaskId,
          questionId: row.Id,
          rowId: this.questionForm[row.Id][index].RowId
        }
        let res = await deleteReadingRowAnswer(param)
        if (res.IsSuccess) {
          // 判断是否有标记，存在则删除
          // let deleteAnnotationIds = []
          // let arr = this.questionMarkInfoList.filter(i=>i.RowId === this.questionForm[row.Id][index].RowId)
          // for(let i = 0; i < arr.length; i++) {
          //   if (arr[i].Id && arr[i].MeasureData) {
          //     let measureData = arr[i].MeasureData
          //     deleteAnnotationIds.push(measureData.annotationUID)
          //     await deleteCustomTag(arr[i].Id)
          //   }
          // }
          // store.dispatch('dicom3d/setDeleteAnnotationIds', deleteAnnotationIds)
          // 标记与问题解除绑定
          this.$message.success(this.$t('common:message:deletedSuccessfully'))
          this.$emit('getQuestions')
        }
        loading.close()
      } catch (e) {
        loading ? loading.close() : ''
        console.log(e)
      }

    },
    setFormTableItemData(obj) {
      this.$set(this.QuestionsForm, obj.key, obj.val)
      this.classArr.map(i => {
        if (i.triggerId === obj.key) {
          let answer = null
          let list = JSON.parse(i.classifyAlgorithms)
          if (i.classifyType === 0) {
            let o = list.find(v => {
              return (
                parseFloat(obj.val) >= parseFloat(v.gt) &&
                parseFloat(obj.val) < parseFloat(v.lt)
              )
            })
            answer = o ? o.label : 'NE'
          } else if (i.classifyType === 1) {
            let o = list.find(v => {
              return v.val.includes(obj.val)
            })
            answer = o ? o.label : null
          }
          this.$set(this.QuestionsForm, i.classId, answer)
        }
      })
      // if (this.classArr.length > 0) {
      //   let qs = this.classArr.find(i=>i.triggerId === obj.key)
      //   if (!qs) return
      //   let answer = null
      //   let list = JSON.parse(qs.classifyAlgorithms)
      //   if (qs.classifyType === 0) {
      //     let o = list.find(v => {
      //       return (
      //         parseFloat(obj.val) >= parseFloat(v.gt) &&
      //         parseFloat(obj.val) < parseFloat(v.lt)
      //       )
      //     })
      //     answer = o ? o.label : null 
      //   } else if (qs.classifyType === 1) {
      //     let o = list.find(v => {
      //       return v.val.includes(obj.val)
      //     })
      //     answer = o ? o.label : null 
      //   }
      //   if (answer !== null) {
      //     this.$set(this.QuestionsForm, qs.classId, answer)
      //   }
      // }
    },
    resetTableFormItemData(obj) {
      this.$set(this.QuestionsForm, obj.key, null)
    },
    getQuestions() {
      this.$emit('getQuestions')
    },
    async handleSave() {
      let loading = null
      try {
        let valid = await this.$refs.tableQsForm.validate().catch(() => false)
        if (!valid) return
        // 判断是否有标记未保存
        let isExistUnSaved = false
        for (let i = 0; i < this.markTableQuestions.length; i++) {
          let keyId = this.QuestionsForm.RowId ? `${this.QuestionsForm.RowId}_${this.markTableQuestions[i]}` : this.markTableQuestions[i]
          if (this.questionsMarkStatus[keyId] && !this.questionsMarkStatus[keyId].isSaved) {
            isExistUnSaved = true
            break
          }
        }
        if (isExistUnSaved) {
          //存在标记信息未保存！
          this.$alert(this.$t('dicom3D:CustomizeQuestionFormItem:alert:markNoSave'))
          return
        }
        loading = this.$loading({ fullscreen: true })
        let answers = []
        let reg = new RegExp(/^[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}$/)
        for (const k in this.QuestionsForm) {
          if (reg.test(k)) {
            if (answers.findIndex(i => i.tableQuestionId === k) === -1) {
              answers.push({ tableQuestionId: k, answer: Array.isArray(this.QuestionsForm[k]) ? JSON.stringify(this.QuestionsForm[k]) : this.QuestionsForm[k] })
            }
          }
        }
        let params = null
        if (this.addOrEdit.type === 'edit' || this.QuestionsForm.RowId) {
          this.addOrEdit.type = 'edit'
          params = {
            questionId: this.question.Id,
            RowIndex: parseInt(this.QuestionsForm.RowIndex),
            RowId: this.QuestionsForm.RowId,
            visitTaskId: this.visitTaskId,
            trialId: this.$route.query.trialId,
            answerList: answers,
          }
        } else {
          params = {
            questionId: this.question.Id,
            RowIndex: this.questionForm[this.question.Id].length + 1,
            RowId: this.QuestionsForm.RowId ? this.QuestionsForm.RowId : '',
            visitTaskId: this.visitTaskId,
            trialId: this.$route.query.trialId,
            answerList: answers
          }
          this.QuestionsForm.RowIndex = this.questionForm[this.question.Id].length + 1
        }
        let res = await submitTableQuestion(params)
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.QuestionsForm.RowId = res.Result.RowId
          // this.$emit('getQuestions')
          this.save()
        }
        loading.close()
      } catch (e) {
        loading ? loading.close() : ''
        console.log(e)
      }
    },
    saveRowInfo() {

    },
    renderHeader(h, obj) {
      let span = document.createElement('span')
      span.style.fontSize = '14px'
      span.innerText = obj.column.label
      document.body.appendChild(span)
      obj.column.realWidth = span.getBoundingClientRect().width + 40
      document.body.removeChild(span)
      return h('span', obj.column.label)
    },
    getQuestionCalculateRelation() {
      getQuestionCalculateRelation({
        ReadingQuestionId: this.question.Id
      }).then(res => {
        this.CalculationTabelList = res.Result
      })
    },
    save() {
      this.$refs['tableQsForm'].validate((valid) => {
        if (!valid) return
        if (this.addOrEdit.type === 'add') {
          this.AnswersList.push(this.QuestionsForm)
        } else {
          var index = this.AnswersList.findIndex(v => v.RowId === this.QuestionsForm.RowId)
          this.AnswersList.splice(index, 1, this.QuestionsForm)
        }
        this.$emit('setFormItemData', { key: this.question.Id, val: this.AnswersList, question: this.question })
        this.formItemNumberChange(this.question.Id, true)
        this.addOrEdit.visible = false
      })
    },
    async handleCancel() {
      // 判断是否有标记未保存
      let isExistUnSaved = false
      for (let i = 0; i < this.markTableQuestions.length; i++) {
        let keyId = this.QuestionsForm.RowId ? `${this.QuestionsForm.RowId}_${this.markTableQuestions[i]}` : this.markTableQuestions[i]
        if (this.questionsMarkStatus[keyId] && !this.questionsMarkStatus[keyId].isSaved) {
          isExistUnSaved = true
          break
        }
      }
      if (isExistUnSaved) {
        if (this.addOrEdit.type === 'add') {
          // 标记未保存是否确认关闭？ 
          const confirm = await this.$confirm(this.$t("dicom3D:CustomizeQuestionFormItem:confirm:markNoSaveAndclose"), {
            type: 'warning',
            distinguishCancelAndClose: true
          })
          if (confirm !== 'confirm') return
          // 清除绑定关系
          let obj = {}
          if (!this.QuestionsForm.RowId) {
            obj.markTableQuestions = this.markTableQuestions
            obj.questionId = this.question.Id
            this.$emit('unBindAnnotationToQuestion', obj)
          }

          return this.addOrEdit.visible = false
        }
        // 标记未保存无法关闭？ 
        return this.$alert(this.$t('dicom3D:CustomizeQuestionFormItem:alert:markNoSaveNoclose'))

      } else {
        this.addOrEdit.visible = false
      }
    },
    logic(rules, num = 0) {
      let isNE = false, isNAN = false
      try {
        if (rules.CalculateQuestionList.length === 0) {
          return false
        }
        let dataArr = []
        rules.CalculateQuestionList.forEach((o, i) => {
          if (i === 0) {
            if (rules.CustomCalculateMark > 4 && rules.CustomCalculateMark < 10) {
              switch (rules.CustomCalculateMark) {
                case 5:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      if (qi === 0) {
                        num = parseFloat(q[o.TableQuestionId])
                      } else {
                        num *= parseFloat(q[o.TableQuestionId])
                      }
                    } else {
                      isNAN = true
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  break;
                case 6:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      if (qi === 0) {
                        num = parseFloat(q[o.TableQuestionId])
                      } else {
                        num += parseFloat(q[o.TableQuestionId])
                      }
                    } else {
                      isNAN = true
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  break;
                case 7:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      if (qi === 0) {
                        num = parseFloat(q[o.TableQuestionId])
                      } else {
                        num += parseFloat(q[o.TableQuestionId])
                      }
                    } else {
                      isNAN = true
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  num = this.questionForm[o.QuestionId].length === 0 ? 0 : num / this.questionForm[o.QuestionId].length
                  break;
                case 8:
                  var arr = []
                  this.questionForm[o.QuestionId].forEach(q => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      arr.push(q[o.TableQuestionId])
                    } else {
                      isNAN = true
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  num = arr.length === 0 ? 0 : Math.max(...arr)
                  break;
                case 9:
                  var arr = []
                  this.questionForm[o.QuestionId].forEach(q => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      arr.push(q[o.TableQuestionId])
                    } else {
                      isNAN = true
                    }
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  num = arr.length === 0 ? 0 : Math.min(...arr)
                  break;
              }
            } else {
              switch (rules.CustomCalculateMark) {
                case 15:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    num = Math.abs(this.questionForm[o.TableQuestionId])
                  }
                  else {
                    isNAN = true
                  }
                  if (this.questionForm[o.TableQuestionId] === 'NE') {
                    isNE = true
                  }
                  break;
                default:
                  if (this.questionForm[o.TableQuestionId] === 'NE') {
                    isNE = true
                  }
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    num = parseFloat(this.questionForm[o.TableQuestionId])
                  } else {
                    isNAN = true
                  }
                  if (!isNaN(num)) {
                    dataArr.push(num)
                  }
                  break;
              }

            }
          } else {
            if (this.questionForm[o.TableQuestionId] === 'NE') {
              isNE = true
            }
            switch (rules.CustomCalculateMark) {
              case 1:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num += parseFloat(this.questionForm[o.TableQuestionId])
                } else {
                  isNAN = true
                }

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

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

                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])
                  }
                } else {
                  isNAN = true
                }

                break;
              case 10:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                } else {
                  isNAN = true
                }
                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]))
                } else {
                  isNAN = true
                }
                num = Math.max(...dataArr);
                break;
              case 12:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                } else {
                  isNAN = true
                }
                num = Math.min(...dataArr);
                break;
              case 13:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                } else {
                  isNAN = true
                }
                num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => acc && curr) ? 1 : 0
                break;
              case 14:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                } else {
                  isNAN = true
                }
                num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => acc || curr, 0) ? 1 : 0;
                break;
              case 15:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num = Math.abs(this.questionForm[o.TableQuestionId])
                }
                else {
                  isNAN = true
                }
                break;
            }
          }
        })
      } catch (e) {
        console.log(e)
      }
      if (isNE) {
        return 'NE'
      }
      if (isNAN) {
        return null
      }
      if (rules.ValueType === 2) {
        num = num * 100
      }
      if (rules.CustomCalculateMark === 13 || rules.CustomCalculateMark === 14) {
        return num
      } else {
        return num.toFixed(this.digitPlaces)
      }

    },
    formItemNumberChange(questionId, isTable) {
      if (typeof isTable === 'object') {
        this.$emit("setFormItemData", { key: isTable.Id, val: questionId, question: isTable });
      } else {
        if (isTable) {
          this.calculationList.forEach((v, i) => {
            var find = v.CalculateQuestionList.filter(o => {
              return o.QuestionId === questionId
            })
            // find的自动计算值number
            if (find) {
              var num = this.logic(v)
              if (num !== false) {
                this.$emit('setFormItemData', { key: v.QuestionId, val: num, question: v })
              }
            }
          })
        } else {
          this.calculationList.forEach(v => {
            var find = v.CalculateQuestionList.filter(o => {
              return o.TableQuestionId === questionId
            })
            // find的自动计算值number
            if (find) {
              var num = this.logic(v)
              if (num !== false) {
                this.$emit('setFormItemData', { key: v.QuestionId, val: num, question: v })
              }
            }
          })
        }

      }
      // this.$emit('formItemNumberChange')
    },
    formItemTableNumberChange() {
      this.question.TableQuestions.Questions.forEach((v) => {
        if (v.Type === "number" && v.DataSource === 1) {
          var CalculateQuestions = JSON.parse(v.CalculateQuestions);
          var num,
            arr = [];
          let isNE = false, isNAN = false
          CalculateQuestions.forEach((o, i) => {
            if (this.QuestionsForm[o.TableQuestionId] === 'NE') {
              isNE = true
            }
            if (i === 0) {
              if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                num = parseFloat(this.QuestionsForm[o.TableQuestionId]);
                arr = [num];
              } else {
                isNAN = true
              }

            } else {
              switch (v.CustomCalculateMark) {
                case 1:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    num += parseFloat(this.QuestionsForm[o.TableQuestionId]);
                  } else {
                    isNAN = true
                  }

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

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

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

                  break;
                case 7:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    arr.push(parseFloat(this.QuestionsForm[o.TableQuestionId]));
                  }

                  else {
                    isNAN = true
                  }
                  num =
                    arr.length === 0
                      ? 0
                      : arr.reduce((acc, curr) => {
                        return acc + (typeof curr === "number" ? curr : 0);
                      }, 0) / arr.length;
                  break;
                case 8:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    arr.push(parseFloat(this.QuestionsForm[o.TableQuestionId]));
                  } else {
                    isNAN = true
                  }

                  num = arr.length === 0 ? 0 : Math.max(...arr);
                  break;
                case 9:
                  if (!isNaN(parseFloat(this.QuestionsForm[o.TableQuestionId]))) {
                    arr.push(parseFloat(this.QuestionsForm[o.TableQuestionId]));
                  } else {
                    isNAN = true
                  }

                  num = arr.length === 0 ? 0 : Math.min(...arr);
                  // console.log('min', this.questionForm[o.QuestionId], arr, num)
                  break;
              }
            }
          });
          if (isNE) {
            num = 'NE'
          }
          if (isNAN) {
            num = ''
          }
          if (!isNaN(parseFloat(num))) {
            num = Number(num).toFixed(this.digitPlaces)
          }
          this.$set(this.QuestionsForm, v.Id, num.toString());
        }
      });
    },
    openAddTableCol(row, index) {
      if (this.addOrEdit.visible) return
      this.parentQsId = row.Id
      this.addOrEdit.visible = true
      this.addOrEdit.title = row.QuestionName + this.$t('trials:readingUnit:qsList:title:tableQs')
      this.QuestionsList = row.TableQuestions.Questions
      this.markTableQuestions = []
      row.TableQuestions.Questions.map(v => {
        if (v.Type === 'class') {
          this.classArr.push({ triggerId: v.ClassifyTableQuestionId, classId: v.Id, classifyAlgorithms: v.ClassifyAlgorithms, classifyType: v.ClassifyType })
        }
        if (v.ImageMarkEnum === 1 || v.ImageMarkEnum == 2) {
          this.markTableQuestions.push(v.Id)
        }
      })
      this.AnswersList = row.TableQuestions.Answers
      if (!index && index !== 0) {
        this.addOrEdit.type = 'add'
        this.QuestionsForm = {}
        this.$set(this.QuestionsForm, 'RowIndex', this.questionForm[this.question.Id].length + 1)
        this.$set(this.QuestionsForm, 'RowId', '')
      } else {
        this.addOrEdit.type = 'edit'
        this.QuestionsForm = Object.assign({}, this.questionForm[row.Id][index])
      }
    },
    formNumberItemChange(v) {
      this.$emit('setFormItemData', { key: v.QuestionId, val: num, question: v })
    },
    formItemChange(v, question) {
      if (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 })
      }
    },
    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) {
    //   if (obj.question.IsTableQuestion && obj.operateStateEnum === 4) {
    //     // 移除表格问题标记
    //     this.$set(this.QuestionsForm, obj.question.Id, null)
    //   } else if (obj.question.IsTableQuestion && obj.operateStateEnum === 7 && obj.rowId) {

    //     this.$set(this.QuestionsForm, 'RowId', obj.rowId)
    //   }
    //   this.$emit('operateImageMarker', obj)
    // },
    async operateImageMarker(obj) {
      // if (obj.question.IsTableQuestion && this.question.Id !== obj.question.ParentQsId) return
      if (obj.operateStateEnum === 5 && this.questionForm[obj.question.Id] && isNaN(parseFloat(this.questionForm[obj.question.Id])) && this.questionForm[obj.question.Id] !== 'NE') return false
      if (obj.operateStateEnum === 4) {
        // 移除问题标记值
        this.$set(this.questionForm, obj.question.Id, null)
      }
      if (obj.question.IsTableQuestion && (obj.operateStateEnum === 4 || obj.operateStateEnum === 24)) {
        // 移除表格问题标记
        this.$set(this.QuestionsForm, obj.question.Id, null)
      } else if (obj.question.IsTableQuestion && obj.operateStateEnum === 7 && this.question.Id === obj.question.ParentQsId) {
        if (!this.QuestionsForm.RowId) {
          // 保存表格问题
          let loading = null
          try {
            loading = this.$loading({ fullscreen: true })
            let answers = []
            let reg = new RegExp(/^[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}$/)
            for (const k in this.QuestionsForm) {
              if (reg.test(k)) {
                if (answers.findIndex(i => i.tableQuestionId === k) === -1) {
                  answers.push({ tableQuestionId: k, answer: this.QuestionsForm[k] })
                }
              }
            }
            this.QuestionsList.forEach(k => {
              if (reg.test(k.Id)) {
                if (answers.findIndex(i => i.tableQuestionId === k.Id) === -1) {
                  answers.push({ tableQuestionId: k.Id, answer: '' })
                }
              }
            })
            let params = {
              questionId: this.question.Id,
              RowIndex: this.questionForm[this.question.Id].length + 1,
              RowId: this.QuestionsForm.RowId ? this.QuestionsForm.RowId : '',
              visitTaskId: this.visitTaskId,
              trialId: this.$route.query.trialId,
              answerList: answers
            }
            let res = await submitTableQuestion(params)
            if (res.IsSuccess) {
              this.QuestionsForm.RowId = res.Result.RowId
              obj.rowId = res.Result.RowId
              this.AnswersList.push(this.QuestionsForm)
              this.$emit('setFormItemData', { key: this.question.Id, val: this.AnswersList, question: this.question })
              this.formItemNumberChange(this.question.Id, true)
            }
            loading.close()
          } catch (e) {
            console.log(e)
            loading.close()
          }
        } else {
          let i = this.AnswersList.findIndex(i => i.RowId === this.QuestionsForm.RowId)
          this.AnswersList[i][obj.question.Id] = this.QuestionsForm[obj.question.Id]
          this.$emit('setFormItemData', { key: this.question.Id, val: this.AnswersList, question: this.question })
          this.formItemNumberChange(this.question.Id, true)
        }

      }
      this.$emit('operateImageMarker', obj)
    },

    unBindAnnotationToQuestion(obj) {
      this.$emit('unBindAnnotationToQuestion', obj)
    },
    setAnswerToQuestion(arr) {
      if (!Array.isArray(arr)) return
      const tableQuestions = this.question.TableQuestions.Questions || []

      arr.forEach(item => {
        if (!item.TableQuestionId || !item.MeasureData) return
        if (!item.ImageToolAttribute) {
          const targetQuestion = tableQuestions.find(q => q.Id === item.TableQuestionId)
          if (targetQuestion) {
            item.ImageToolAttribute = targetQuestion.ImageToolAttribute
          }
        }
        const val = this.getAnnotationProp(item.MeasureData, item.ImageToolAttribute)
        this.setFormTableItemData({ key: item.TableQuestionId, val })
        // this.$set(this.QuestionsForm, item.TableQuestionId, val)
        this.formItemTableNumberChange()
      })
    },
    getAnnotationProp(annotation, prop) {
      if (!annotation) return
      let referencedImageId = null
      if (annotation.from || annotation.metadata.volumeId) {
        referencedImageId = `${annotation?.metadata?.volumeId}?sliceIndex=${annotation?.metadata?.sliceIndex}&viewPlaneNormal=${annotation?.metadata?.viewPlaneNormal.map(i => i == 0 ? Number(0).toFixed(3) : Number(i).toFixed(3)).join(',')}`
      } else {
        referencedImageId = annotation?.metadata?.referencedImageId
      }
      if (!referencedImageId) return null
      const cacheKey = annotation.from || annotation.metadata.volumeId ? `volumeId:${referencedImageId}` : `imageId:${referencedImageId}`
      const points = ['x', 'y', 'z'];
      const cachedStats = annotation.markTool === "ArrowAnnotate"
        ? annotation.data?.handles?.points[0]
        : this.getAnnotationCachedStats(annotation, cacheKey, prop)
      const hasProp = cachedStats
        && (Object.prototype.hasOwnProperty.call(cachedStats, prop) || cachedStats[points.indexOf(prop)])
      if (!hasProp) return null
      let value = annotation.markTool === "ArrowAnnotate" ? cachedStats[points.indexOf(prop)] : cachedStats[prop]
      if (this.isNoneDicom && annotation.ps && value !== null) {
        let ps = annotation.ps
        if (prop === 'area') {
          value = this.reRound(csUtils.roundNumber(value * ps * ps), this.digitPlaces)
        } else if (prop === 'length' || prop === 'perimeter' || prop === 'width') {
          value = this.reRound(csUtils.roundNumber(value * ps), this.digitPlaces)
        } else {
          value = this.reRound(csUtils.roundNumber(value), this.digitPlaces)
        }
      } else if (this.isNoneDicom && value !== null) {
        value = this.reRound(csUtils.roundNumber(value), this.digitPlaces)
      }
      if (prop === 'total' && value !== null) {
        return this.formatStatSum(value)
      }
      return value !== null
        ? parseFloat(value).toFixed(this.digitPlaces)
        : value
    },
    getAnnotationCachedStats(annotation, cacheKey, prop) {
      const cachedStatsMap = annotation?.data?.cachedStats || {}
      const matchedStats = cachedStatsMap[cacheKey]
      if (prop !== 'total') return matchedStats
      const nmStats = Object.values(cachedStatsMap).find(item => item?.Modality === 'NM' && item.total !== undefined && item.total !== null)
      return nmStats || matchedStats
    },
    formatStatSum(value) {
      const num = Number(value)
      if (!Number.isFinite(num)) return value

      if (Math.abs(num - Math.round(num)) < 1e-6) {
        return String(Math.round(num))
      }

      return this.reRound(num, this.digitPlaces)
    },
    reRound(result, finalPrecision) {
      if (typeof result === 'string' && result.includes(', ')) {
        const numStrs = result.split(', ')
        const processed = numStrs.map(str => this.processSingle(str, finalPrecision))
        return processed.join(', ')
      }
      return this.processSingle(result, finalPrecision)
    },
    processSingle(str, precision) {
      const num = parseFloat(str)
      if (isNaN(num)) return 'NaN'

      // 保留原极小值处理逻辑
      if (Math.abs(num) < 0.0001) return str
      const factor = 10 ** precision
      return (Math.round(num * factor + 0.0000001) / factor).toFixed(precision)
    },
    async beforeClose(done) {
      try {
        // 判断是否有标记未保存
        let isExistUnSaved = false
        for (let i = 0; i < this.markTableQuestions.length; i++) {
          let keyId = this.QuestionsForm.RowId ? `${this.QuestionsForm.RowId}_${this.markTableQuestions[i]}` : this.markTableQuestions[i]
          if (this.questionsMarkStatus[keyId] && !this.questionsMarkStatus[keyId].isSaved) {
            isExistUnSaved = true
            break
          }
        }
        if (isExistUnSaved) {
          if (this.addOrEdit.type === 'add') {
            //标记未保存是否确认关闭？ 
            const confirm = await this.$confirm(this.$t("dicom3D:CustomizeQuestionFormItem:confirm:markNoSaveAndclose"), {
              type: 'warning',
              distinguishCancelAndClose: true
            })
            if (confirm !== 'confirm') return
            // 清除绑定关系
            let obj = {}
            if (!this.QuestionsForm.RowId) {
              obj.markTableQuestions = this.markTableQuestions
              obj.questionId = this.question.Id
              this.$emit('unBindAnnotationToQuestion', obj)
            }

            return done()
          }
          // 标记未保存无法关闭？ 
          return this.$alert(this.$t('dicom3D:CustomizeQuestionFormItem:alert:markNoSaveNoclose'))
          // this.$alert('存在标记信息未保存！')
        } else {
          done()
        }
      } catch (e) {

      }
    },
    async uploadScreenshot(param) {
      if (!this.visitTaskId) return
      const loading = this.$loading({
        target: document.querySelector('.ecrf-wrapper'),
        fullscreen: false,
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      })
      try {
        var fileName = param.file.name
        var index = fileName.lastIndexOf('.')
        var suffix = fileName.substring(index + 1, fileName.length)
        let 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 })
        this.$set(this.QuestionsForm, this.question.Id, this.urls.length > 0 ? this.urls.join('|') : '')
      } catch (err) {
        console.log(err)
      }
      loading.close()
      // uploadReadingAnswerImage(this.$route.query.trialId, this.visitTaskId, formData).then(res => {
      //   if (res.IsSuccess) {
      //     this.fileList.push({ url: `/api/${res.Result.Path}` })
      //     this.urls.push(res.Result.Path)
      //     this.$emit('setFormItemData', { key: this.question.Id, val: this.urls.length > 0 ? this.urls.join('|') : '' })
      //   }
      //   loading.close()
      // }).catch(() => {
      //   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 })
        this.$set(this.QuestionsForm, this.question.Id, this.urls.length > 0 ? this.urls.join('|') : '')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.criterion-form-item {

  // 弹窗层元素不可穿透点击事件（不影响弹窗层元素的点击事件）
  ::v-deep .el-dialog {
    pointer-events: auto;
    margin-right: 15px !important;
    margin-top: 30vh !important;
  }

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

  ::v-deep .el-dialog__wrapper {
    pointer-events: none;
  }

  // .custom-dialog .el-dialog__wrapper {
  //   pointer-events:none;
  // }

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

  ::v-deep .el-radio__label {
    color: #c3c3c3;
  }

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

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

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

.criterion-form-item {
  ::v-deep .criterion-form-item .el-form-item {
    display: block;

    .el-form-item__label {
      display: block;
      color: #c8c8c8;
      float: none;
      text-align: left;
    }
  }

  .el-form-item {
    display: flex;
    flex-direction: row;
    align-items: flex-start;
  }

  .el-input {
    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-table__body-wrapper::-webkit-scrollbar {
    height: 10px !important;
  }

  ::v-deep .el-table__fixed-right::before {
    display: none;
  }

  ::v-deep .el-upload-list__item-name {
    color: #0a84ff;

    .el-icon-document {
      color: #0a84ff;
    }
  }
}
</style>
