<template>
  <div class="reading-rule-config-form">
    <!-- 配置信息表单 -->
    <el-form ref="readingRulesForm" v-loading="loading" :model="form" style="width: 800px" :rules="rules"
      label-width="340px" size="small">
      <!-- 阅片平台 -->
      <el-form-item :label="$t('trials:processCfg:form:imagePlatform')" prop="ImagePlatform">
        <el-radio-group v-model="form.ImagePlatform" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <template v-if="isUSA">
            <el-radio v-for="item of $d.ImagePlatformUSA" :key="item.id" :label="item.value">
              {{ item.label }}
            </el-radio>
          </template>
          <template v-else>
            <el-radio v-for="item of $d.ImagePlatform" :key="item.id" :label="item.value">
              {{ item.label }}
            </el-radio>
          </template>
        </el-radio-group>
      </el-form-item>
      <!-- 阅片工具 -->
      <el-form-item v-if="form.ImagePlatform === 3" :label="$t('trials:readingUnit:readingRules:title:readingTool')"
        prop="ReadingTool">
        <el-radio-group v-model="form.ReadingTool" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])" @input="handleReadingToolInput">
          <el-radio v-for="item of $d.ReadingTool" :key="item.id" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 测量工具  && (form.ReadingTool === 0 || form.ReadingTool === 1 || form.ReadingTool === 2)-->
      <el-form-item v-if="CriterionType === 0 && form.ReadingVersionEnum === 1"
        :label="$t('trials:readingUnit:readingRules:title:measureTool')">
        <el-checkbox-group v-model="form.ReadingToolList" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])" @change="handleReadingToolListChange">
          <el-checkbox v-for="tool in tools" :key="tool.toolName" :label="tool.toolName" name="ReadingToolList">
            {{ $t(`${tool.i18nKey}`) }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 定圆工具半径 -->
      <el-form-item v-if="form.ReadingToolList.includes('FixedRadiusCircleROI')"
        :label="$t('trials:readingUnit:readingRules:title:circleRadius')" prop="CircleRadius">
        <el-input v-model="form.CircleRadius" @input="(val) => handleNumberInput(val, 'CircleRadius')" clearable
          :disabled="isConfirm ||
            !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
            ">
          <template slot="append">mm</template>
        </el-input>
      </el-form-item>
      <!--分割工具  && (form.ReadingTool === 0 || form.ReadingTool === 1 || form.ReadingTool === 2)-->
      <el-form-item v-if="CriterionType === 0 && form.ReadingVersionEnum === 1 && form.ReadingTool === 3"
        :label="$t('trials:readingUnit:readingRules:title:segmentTool')">
        <el-checkbox-group v-model="form.SegmentToolList" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-checkbox v-for="tool in segmentTools" :key="tool.toolName" :label="tool.toolName" name="SegmentToolList">
            {{ $t(`${tool.i18nKey}`) }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <!-- 分割组名 -->
      <el-form-item v-if="CriterionType === 0 && form.ReadingVersionEnum === 1 && form.ReadingTool === 3"
        :label="$t('trials:readingUnit:readingRules:title:segmentations')" prop="DefaultSegmentName.SegmentationName">
        <el-input v-model="form.DefaultSegmentName.SegmentationName" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])" style="width: 80%">
        </el-input>
      </el-form-item>
      <!-- 分割片段 -->
      <el-form-item v-if="CriterionType === 0 && form.ReadingVersionEnum === 1 && form.ReadingTool === 3"
        :label="$t('trials:readingUnit:readingRules:title:segment')" prop="DefaultSegmentName.SegmentNameList">
        <el-input v-model="form.SegmentNameListStr" style="width: 80%" disabled>
        </el-input>
        <el-button :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          " icon="el-icon-plus" circle @click="segmentVisible = true" />
      </el-form-item>
      <!--检查类型筛选-->
      <el-form-item :label="$t('trials:processCfg:form:IsImageFilter')" prop="IsImageFilter">
        <el-radio-group v-model="form.IsImageFilter" @input="IsImageFilterChange" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-radio :label="item.value" v-for="item in $d.YesOrNoModality" :key="item.id">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 影像模态 -->
      <el-form-item :label="$t('trials:readingUnit:readingRules:title:CriterionModalitys')" prop="CriterionModalitys"
        style="position: relative" v-if="form.IsImageFilter">
        <el-checkbox-group v-model="CriterionModalitys" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-checkbox v-for="item in modalityList" :label="item" :key="item">{{
            item
          }}</el-checkbox>
        </el-checkbox-group>
        <el-button v-if="
          !isConfirm &&
          hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
        " size="mini" style="position: absolute; top: 0; right: -40px" @click.stop="handleCheckAllChange"
          type="success">{{
            CriterionModalitys.length === modalityList.length
              ? $t(
                'trials:readingUnit:readingRules:title:CriterionModalitysCancel'
              )
              : $t(
                'trials:readingUnit:readingRules:title:CriterionModalitysAll'
              )
          }}</el-button>
      </el-form-item>
      <el-form-item :label="$t('trials:consistencyAnalysis:table:isUrgent')" prop="DigitPlaces">
        <el-radio-group v-model="form.IsUrgent" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-radio v-for="item of $d.YesOrNo" :key="item.id" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 存在附加评估 -->
      <el-form-item :label="$t('trials:processCfg:form:IsAdditionalAssessment')" prop="IsAdditionalAssessment"
        v-if="CriterionType === 1">
        <el-radio-group v-model="form.IsAdditionalAssessment" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsAdditionalAssessment${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 阅片任务生成方式 -->
      <el-form-item :label="$t('trials:processCfg:form:IsAutoCreate')" prop="IsAutoCreate">
        <el-radio-group v-model="form.IsAutoCreate" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-radio v-for="item of $d.YesOrNoAuto" :key="`IsAutoCreate${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!--阅片模式-->
      <el-form-item :label="$t('trials:processCfg:form:readingType')" prop="ReadingType">
        <el-radio-group v-model="form.ReadingType" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          " @change="
            () => {
              form.IsArbitrationReading = false
            }
          ">
          <el-radio v-for="item of $d.ReadingMethod" :key="item.id" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!--仲裁阅片-->
      <el-form-item :label="$t('trials:processCfg:form:ad')" prop="IsArbitrationReading">
        <el-radio-group v-model="form.IsArbitrationReading" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit']) ||
          form.ReadingType !== 2
          ">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsArbitrationReading${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 是否阅片期 -->
      <el-form-item :label="$t('trials:readingUnit:readingRules:title:isReadingPeriod')" prop="IsReadingPeriod">
        <el-radio-group v-model="form.IsReadingPeriod" :disabled="isConfirm ||
          IsMustGlobalReading ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit']) || ((form.IsReadingTaskViewInOrder === 0 || form.IsReadingTaskViewInOrder === 2) && CriterionType !== 10)
          " @change="
            (v) => {
              if (!v) {
                form.IsGlobalReading = v
                form.IsOncologyReading = v
              }
            }
          ">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsReadingPeriod${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('trials:processCfg:form:global')" prop="IsGlobalReading">
        <el-radio-group v-model="form.IsGlobalReading" :disabled="!form.IsReadingPeriod ||
          IsMustGlobalReading ||
          isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit']) || ((form.IsReadingTaskViewInOrder === 0 || form.IsReadingTaskViewInOrder === 2) && CriterionType !== 10)
          ">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsGlobalReading${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('trials:processCfg:form:clinical')" prop="IsOncologyReading">
        <el-radio-group v-model="form.IsOncologyReading" :disabled="!form.IsReadingPeriod ||
          !form.IsSystemSetOncology ||
          isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit']) || ((form.IsReadingTaskViewInOrder === 0 || form.IsReadingTaskViewInOrder === 2) && CriterionType !== 10)
          ">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsOncologyReading${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 任务展示方式 -->
      <el-form-item :label="$t('trials:readingUnit:readingRules:title:readingTaskViewInOrder')
        " prop="IsReadingTaskViewInOrder">
        <el-radio-group v-model="form.IsReadingTaskViewInOrder" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit']) || CriterionType === 10
          " @change="
            (v) => {
              form.ImageDownloadEnum = 0
              form.ImageUploadEnum = 0
              if (v) {
                form.IsReadingShowSubjectInfo = true
                form.IsReadingShowPreviousResults = true
                form.ReadingTaskViewEnum = 0
                form.IseCRFShowInDicomReading = false
              } else {
                form.ReadingTaskViewEnum = 2
                form.IsReadingShowSubjectInfo = false
                form.IsReadingShowPreviousResults = false
                form.IseCRFShowInDicomReading = true
              }
              if (CriterionType !== 10 && (v === 0 || v === 2)) {
                form.IsReadingPeriod = false
                form.IsOncologyReading = false
                form.IsGlobalReading = false
              }
            }
          ">
          <el-radio v-for="item of $d.IsReadingTaskViewInOrder" :key="'IsReadingTaskViewInOrder' + item.value"
            :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 任务组织级别 -->
      <el-form-item :label="$t('trials:readingUnit:readingRules:title:readingTaskViewEnum')" prop="ReadingTaskViewEnum">
        <el-radio-group v-model="form.ReadingTaskViewEnum" :disabled="isConfirm ||
          !!!isReadingTaskViewInOrder ||
          !!isReadingTaskViewInOrder ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-radio v-for="item of $d.ReadingTaskViewEnum" :key="item.id" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!--支持影像下载v-if="CriterionType === 0"-->
      <el-form-item :label="$t('trials:processCfg:form:ImageDownloadEnum')" prop="ImageDownloadEnum">
        <el-radio-group v-model="form.ImageDownloadEnum" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-radio v-for="item of $d.ImageDownloadEnum" :key="item.id" :label="item.value" :disabled="(form.IsReadingTaskViewInOrder === 1 ||
            form.IsReadingTaskViewInOrder === 0) &&
            item.value === 1
            ">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!--支持上传DICOM影像-->
      <el-form-item :label="$t('trials:processCfg:form:ImageUploadEnum')" prop="ImageUploadEnum">
        <el-radio-group v-model="form.ImageUploadEnum" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-radio v-for="item of $d.ImageUploadEnum" :key="item.id" :label="item.value" :disabled="(form.IsReadingTaskViewInOrder === 1 ||
            form.IsReadingTaskViewInOrder === 0) &&
            item.value === 1
            ">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- IR阅片页面是否显示受试者信息 -->
      <el-form-item :label="$t('trials:readingUnit:readingRules:title:isReadingShowSubjectInfo')
        " prop="IsReadingShowSubjectInfo">
        <el-radio-group v-model="form.IsReadingShowSubjectInfo" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit']) ||
          form.IsReadingTaskViewInOrder >= 0
          ">
          <el-radio v-for="item of $d.YesOrNo" :key="'IsReadingShowSubjectInfo' + item.value" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- IR阅片页面是否可以查看既往任务结果 -->
      <el-form-item :label="$t(
        'trials:readingUnit:readingRules:title:isReadingShowPreviousResults'
      )
        " prop="IsReadingShowPreviousResults">
        <el-radio-group v-model="form.IsReadingShowPreviousResults" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit']) ||
          form.IsReadingTaskViewInOrder >= 0
          " @change="
            (v) => {
              if (!v) {
                form.IseCRFShowInDicomReading = true
              }
            }
          ">
          <el-radio v-for="item of $d.YesOrNo" :key="'IsReadingShowPreviousResults' + item.value" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- eCRF是否显示在影像阅片页面 -->
      <el-form-item :label="$t('trials:readingUnit:readingRules:title:isECRFShowInDicomReading')
        " prop="IseCRFShowInDicomReading">
        <el-radio-group v-model="form.IseCRFShowInDicomReading" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit']) ||
          !form.IsReadingShowPreviousResults
          ">
          <el-radio v-for="item of $d.YesOrNo" :key="item.label" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 修约小数位数 -->
      <el-form-item :label="$t('trials:processCfg:form:digitPlaces')" prop="DigitPlaces">
        <el-radio-group v-model="form.DigitPlaces" :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          ">
          <el-radio v-for="item of $d.DigitPlaces" :key="item.id" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 阅片关键点 -->
      <el-form-item :label="$t('trials:readingUnit:readingRules:title:keyDoc')
        " prop="KeyFileList">
        <el-input v-model="form.KeyFileListStr" type="textarea" :autosize="{ minRows: 1, maxRows: 3 }"
          style="width: 80%" disabled />
        <el-button :disabled="isConfirm ||
          !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
          " icon="el-icon-plus" circle @click="handleSetKeyFileList" />
        <el-button :disabled="form.KeyFileList.length <= 0" icon="el-icon-view" circle @click="viewManual" />
      </el-form-item>
      <el-form-item :label="$t(
        'trials:trials-panel:setting:reading-unit:TrialCriterionAdditionalAssessmentTypeList'
      )
        " v-if="
          form.IsAdditionalAssessment &&
          form.TrialCriterionAdditionalAssessmentTypeList &&
          form.TrialCriterionAdditionalAssessmentTypeList.length > 0
        ">
      </el-form-item>
      <template v-for="item of form.TrialCriterionAdditionalAssessmentTypeList">
        <el-form-item :key="item.Id" :prop="`AdditionalAssessmentType${item.Id}`" :rules="[
          {
            required: true,
            message: $t('common:ruleMessage:select'),
            trigger: ['blur'],
          },
        ]" :label="$fd('AdditionalAssessmentType', item.AdditionalAssessmentType)
          " v-if="
            form.IsAdditionalAssessment &&
            form.TrialCriterionAdditionalAssessmentTypeList
          ">
          <el-radio-group v-model="item.IsSelected" :disabled="isConfirm ||
            !hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
            " @change="
              (v) => {
                $set(form, 'AdditionalAssessmentType' + item.Id, v)
              }
            ">
            <el-radio v-for="item of $d.YesOrNo" :key="`AdditionalAssessmentType${item.value}`" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
      <el-form-item v-if="
        !isConfirm &&
        hasPermi(['trials:trials-panel:setting:reading-unit:edit'])
      ">
        <!-- 保存 -->
        <el-button type="primary" @click="handleSave(true)">
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 配置信息确认框 -->
    <el-dialog v-if="keyDocVisible" :visible.sync="keyDocVisible" :close-on-click-modal="false" width="600px"
      :title="$t('trials:reading-unit:dialogTitle:keyDoc')" custom-class="base-dialog-wrapper">
      <div class="base-dialog-body">
        <div class="upload">
          <input directory accept=".pdf" type="file" name="uploadFolder" class="select-file" title=""
            @change="beginScanFiles($event)" />
          <div class="btn-select">
            {{ $t('dictionary:template:basicData:button:selectFile') }}
          </div>
        </div>
        <div class="drag" ref="drag" @dragover="handleDragover" @drop="handleDrop">
          <el-table :data="confirmData" border style="width: 100%" size="small">
            <el-table-column prop="FileName" :label="$t('trials:reading-unit:table:FileName')" show-overflow-tooltip />
            <el-table-column :label="$t('common:action:action')" align="left" fixed="right">
              <template slot-scope="scope">
                <el-button circle icon="el-icon-view" :title="$t('dictionary:template:keyDocList:button:view')"
                  @click.stop="view(scope.row)" />
                <el-button circle icon="el-icon-delete" :title="$t('dictionary:template:keyDocList:button:del')"
                  @click.stop="del(scope.$index)" />
              </template>
            </el-table-column>
          </el-table>
        </div>

      </div>
      <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
        <!-- 确认 -->
        <el-button size="small" type="primary" @click="handleConfirm">
          {{ $t('trials:reading-unit:button:confirmCfg') }}
        </el-button>
      </div>
    </el-dialog>
    <attachmentPreview :visible.sync="perview_visible" :isView="true" :isExternal="true" :ExternalList="ExternalList"
      v-if="perview_visible" />
    <!-- 分割段编辑 -->
    <el-dialog v-if="segmentVisible" :visible.sync="segmentVisible" :close-on-click-modal="false" width="600px"
      :title="$t('trials:trialCfg:dialogTitle:addSegment')" custom-class="base-dialog-wrapper">
      <div class="base-dialog-body">
        <el-button @click.stop="addSegment" style="margin-bottom: 5px;" type="primary" size="small">{{
          $t('common:button:new') }}</el-button>
        <el-table :data="SegmentNameList" border style="width: 100%" size="small">
          <el-table-column type="index" width="50" />
          <el-table-column prop="name" :label="$t('trials:trialCfg:table:segmentName')" show-overflow-tooltip />
          <el-table-column :label="$t('common:action:action')" align="left" fixed="right">
            <template slot-scope="scope">
              <el-button circle icon="el-icon-top" :title="$t('dictionary:template:keyDocList:button:up')"
                @click.stop="sortSegment(scope, 'up')" :disabled="scope.$index === 0" />
              <el-button circle icon="el-icon-bottom" :title="$t('dictionary:template:keyDocList:button:down')"
                @click.stop="sortSegment(scope, 'down')" :disabled="scope.$index === SegmentNameList.length - 1" />
              <el-button circle icon="el-icon-edit-outline" :title="$t('dictionary:template:keyDocList:button:update')"
                @click.stop="updateSegment(scope)" />
              <el-button circle icon="el-icon-delete" :title="$t('dictionary:template:keyDocList:button:del')"
                @click.stop="delSegment(scope)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
        <el-button size="small" type="primary" @click="segmentVisible = false">
          {{ $t('trials:trialCfg:button:confirmCfg') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getCriterionReadingInfo, setCriterionReadingInfo } from '@/api/trials'
import { config } from '@/views/trials/trials-panel/reading/dicoms3D/components/toolConfig'
import { readEntry } from '@/utils/index'
import attachmentPreview from '@/views/dictionary/attachment/components/SignatureTemplate/attachmentPreview'
export default {
  name: 'ReadingRules',
  components: { attachmentPreview },
  props: {
    trialReadingCriterionId: {
      type: String,
      default() {
        return ''
      },
    },
    CriterionType: {
      type: Number,
      default: 0,
    },
    TrialReadingCriterionName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      segmentVisible: false,
      perview_visible: false,
      ExternalList: [],
      keyDocVisible: false,
      confirmData: [],
      additionalAssessmentOptionList: [],
      form: {
        TrialId: '',
        ImagePlatform: null,
        ReadingTool: 0,
        ReadingVersionEnum: null,
        ReadingToolList: [],
        SegmentToolList: [],
        DefaultSegmentName: {
          SegmentationName: null,
          SegmentNameList: []
        },
        SegmentNameListStr: null,
        ReadingTaskViewEnum: null,
        IsImageLabeled: null,
        IsReadingShowSubjectInfo: null,
        IsReadingShowPreviousResults: null,
        ReadingType: 1,
        IsGlobalReading: false,
        IsArbitrationReading: false,
        IsOncologyReading: 0,
        IsReadingTaskViewInOrder: false,
        IsReadingPeriod: false,
        IsSystemSetOncology: false,
        // IsReadingTaskViewInOrder: null,
        ArbitrationRule: null,
        GlobalUpdateType: null,
        IsSystemCriterion: true,
        DigitPlaces: null,
        IseCRFShowInDicomReading: false,
        IsAutoCreate: null,
        IsAdditionalAssessment: null,
        CriterionType: null,
        AdditionalAssessmentType: null,
        IsUrgent: false,
        TrialCriterionAdditionalAssessmentTypeList: [],
        CriterionModalitys: null,
        ImageDownloadEnum: null,
        ImageUploadEnum: null,
        IsImageFilter: false,
        KeyFileListStr: '',
        KeyFileList: [],
        CircleRadius: 10
      },
      rules: {
        IsAutoCreate: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsAdditionalAssessment: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        ImagePlatform: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        ReadingTool: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        ImageDownloadEnum: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        ImageUploadEnum: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsImageFilter: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        ReadingTaskViewEnum: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsImageLabeled: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsReadingShowSubjectInfo: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsReadingShowPreviousResults: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        ReadingType: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsReadingTaskViewInOrder: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsGlobalReading: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsArbitrationReading: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsOncologyReading: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        DigitPlaces: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IseCRFShowInDicomReading: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsReadingPeriod: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        'DefaultSegmentName.SegmentationName': [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
        'DefaultSegmentName.SegmentNameList': [
          {
            required: true,
            type: 'array',
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        CriterionModalitys: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
          {
            validator: (rule, value, callback) => {
              if (value && Array.isArray(value) && value.length < 0) {
                callback(new Error(this.$t('common:ruleMessage:select')))
              } else {
                callback()
              }
            },
            trigger: ['blur', 'change'],
          },
        ],
        CircleRadius: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur', 'change'], },
          { pattern: /^(0|[1-9]\d*)(\.\d{1,2})?$/, message: '请输入正确的数值格式，最多两位小数', trigger: 'blur' }
        ]
        // IsReadingTaskViewInOrder: [
        //   { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        // ]
      },
      loading: false,
      readingInfo: {},
      isConfirm: true,
      isReadingTaskViewInOrder: null,
      IsMustGlobalReading: false,
      IsNotReadingShowSubjectInfoChange: false,

      modalityList: [],
      CriterionModalitys: [],
      modalityIsCheck: false, // 是否允许影像筛选
      tools: [],
      segmentTools: []
    }
  },
  mounted() {
    if (this.CriterionType === 0) {
      this.tools = [...config.customizeStandards]
    }

    this.initPage()
  },
  computed: {
    isUSA() {
      return process.env.NODE_ENV === 'usa'
    },
    SegmentNameList() {
      let arr = []
      this.form.DefaultSegmentName.SegmentNameList.forEach(item => {
        let obj = {
          name: item
        }
        arr.push(obj)
      })
      return arr
    }
  },
  watch: {
    CriterionModalitys: {
      handler() {
        this.form.CriterionModalitys = this.CriterionModalitys.join('|')
      },
      deep: true,
    },
  },
  methods: {
    sortSegment(row, key) {
      let index = row.$index
      let name = row.row.name
      this.form.DefaultSegmentName.SegmentNameList.splice(index, 1)
      if (key === 'up') {


        this.form.DefaultSegmentName.SegmentNameList.splice(index - 1, 0, name)
      } else {
        this.form.DefaultSegmentName.SegmentNameList.splice(index + 1, 0, name)
      }
    },
    async updateSegment(row) {
      let name = await this.customPrompt(row.row.name)
      if (!name) return false
      let index = row.$index
      this.form.DefaultSegmentName.SegmentNameList.splice(index, 1, name)
      this.form.SegmentNameListStr = this.form.DefaultSegmentName.SegmentNameList.join("|")
    },
    delSegment(row) {
      console.log(row)
      let index = row.$index
      this.form.DefaultSegmentName.SegmentNameList.splice(index, 1)
      this.form.SegmentNameListStr = this.form.DefaultSegmentName.SegmentNameList.join("|")
    },
    async addSegment() {
      let name = await this.customPrompt()
      if (!name) return false
      this.form.DefaultSegmentName.SegmentNameList.push(name)
      this.form.SegmentNameListStr = this.form.DefaultSegmentName.SegmentNameList.join("|")
    },
    async customPrompt(name = null) {
      try {
        const that = this
        // 请输入标记名称
        let message = !name ? this.$t('trials:reading:Segmentations:message:add') : this.$t('trials:reading:Segmentations:message:upate')
        const { value } = await this.$prompt(message, '', {
          showClose: false,
          cancelButtonText: this.$t('common:button:cancel'),
          confirmButtonText: this.$t('common:button:save'),
          showCancelButton: true,
          closeOnClickModal: false,
          closeOnPressEscape: false,
          inputValue: name,
          inputValidator: (value) => {
            if (!value) {
              return that.$t("trials:reading:Segmentations:message:notName")
            } else if (value === name) {
              return true
            } else if (that.form.DefaultSegmentName.SegmentNameList.includes(value)) {
              return that.$t("trials:reading:Segmentations:message:nameIsHas")
            } else {
              return true
            }
          },
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              // const value = instance.inputValue
              done()
            } else {
              done()
            }
          }
        })
        return value
      } catch (err) {
        console.log(err)
        return null
      }
    },
    async viewManual() {
      try {
        if (this.form.KeyFileList.length <= 0) return this.$message.warning(this.$t("trials:researchRecord:ImageManual:message:noImageManual"))
        this.ExternalList = []
        this.form.KeyFileList.forEach(item => {
          let obj = {
            FilePath: item.FilePath,
            FileFormat: 'pdf',
            Name: item.FileName
          }
          this.ExternalList.push(obj)
        });
        this.perview_visible = true
      } catch (err) {
        console.log(err)
      }
    },
    handleDragover(e) {
      e.stopPropagation();
      e.preventDefault();
    },
    handleDrop(e) {
      e.stopPropagation();
      e.preventDefault();
      this.beginScanFiles(e, true)
    },
    view(row) {
      this.$preview({
        path: row.FilePath,
        type: 'pdf',
        title: row.FileName,
      })
    },
    del(index) {
      this.confirmData.splice(index, 1)
    },
    handleSetKeyFileList() {
      this.confirmData = [...this.form.KeyFileList]
      this.keyDocVisible = true
    },
    handleConfirm() {
      this.form.KeyFileList = [...this.confirmData]
      this.form.KeyFileListStr = this.form.KeyFileList.map(item => item.FileName).join(',')
      this.keyDocVisible = false
    },
    async beginScanFiles(e, isDrop = false) {
      try {
        let files = []
        if (isDrop) {
          const items = e.dataTransfer.items;
          const allFiles = []; // 用于存储所有找到的文件

          // 遍历拖拽项
          for (const item of items) {
            const entry = item.webkitGetAsEntry(); // 获取文件系统入口
            if (entry) {
              const files = await readEntry(entry); // 递归读取入口内容
              allFiles.push(...files);
            }
          }
          files = allFiles
        } else {
          files = [...e.target.files]
        }
        for (let i = 0; i < files.length; i++) {
          let file = files[i]
          let name = file.name
          if (!this.checkFileSuffix(name)) continue
          file = await this.fileToBlob(file)
          let scope = this
          let res = await this.OSSclient.put(
            `/${this.$route.query.trialId}/ReadingModule/${this.TrialReadingCriterionName}/${scope.getGuid(Date.now() + '_' + name.split('.')[0])}.pdf`,
            file
          )
          let data = {
            FilePath: this.$getObjectName(res.url),
            FileName: name
          }
          this.confirmData.push(data)
        }
      } catch (err) {
        console.log(err)
        this.loading = false;
      }
    },
    checkFileSuffix(fileName) {
      var index = fileName.lastIndexOf('.')
      var suffix = fileName.substring(index + 1, fileName.length)
      if ('.pdf'.toLocaleLowerCase().search(suffix.toLocaleLowerCase()) === -1) {
        return false
      } else {
        return true
      }
    },
    // 阅片工具选择
    handleReadingToolInput(val) {
      this.form.ReadingToolList = []
      this.form.SegmentToolList = []
      if (this.CriterionType !== 0) {
        this.segmentTools = []
        return this.tools = []
      }
      if (val === 0 || val === 2 || val === 3) {
        this.tools = [...config.customizeStandards]
      }
      if (val === 1) {
        this.tools = [...config.customizeStandardsNoneDicom]
      }
      if (val === 3) {
        this.segmentTools = [...config.customizeStandardsSegmentDicom]
      }
    },
    // 检查类型筛选值变更
    IsImageFilterChange(data) {
      if (data) {
        this.CriterionModalitys = this.modalityList
      } else {
        this.CriterionModalitys = []
      }
    },
    // 影像模态全选
    handleCheckAllChange() {
      this.CriterionModalitys =
        this.CriterionModalitys.length <= 0 ? this.modalityList : []
    },
    initPage() {
      this.loading = true
      const trialId = this.$route.query.trialId
      // getTrialCriterionAdditionalAssessmentOptionList(this.trialReadingCriterionId).then(res => {
      //   this.additionalAssessmentOptionList = res.Result
      //   if (this.additionalAssessmentOptionList.length > 0) {
      //     this.additionalAssessmentOptionList.forEach(v => {
      //       this.$set(this.form, 'AdditionalAssessmentType'+v.Id, v.IsSelected)
      //     })
      //   }
      getCriterionReadingInfo({
        trialId,
        TrialReadingCriterionId: this.trialReadingCriterionId,
      })
        .then((res) => {
          this.loading = false
          this.modalityList = res.Result.TrialModalitys.split('|').filter(
            (item) => item && item.trim()
          )
          for (const k in this.form) {
            if (res.Result.hasOwnProperty(k)) {
              this.form[k] = res.Result[k]
            }
          }
          if (Array.isArray(this.form.KeyFileList) && this.form.KeyFileList.length > 0) {
            this.form.KeyFileListStr = this.form.KeyFileList.map(item => item.FileName).join(',')
          }
          if (this.CriterionType === 0) {
            if (this.form.ReadingTool === 0 || this.form.ReadingTool === 2 || this.form.ReadingTool === 3) {
              this.tools = [...config.customizeStandards]
            }
            if (this.form.ReadingTool === 1) {
              this.tools = [...config.customizeStandardsNoneDicom]
            }
            if (this.form.ReadingTool === 3) {
              this.segmentTools = [...config.customizeStandardsSegmentDicom]
            }
            this.form.SegmentNameListStr = res.Result.DefaultSegmentName.SegmentNameList.join(",")
          }
          this.CriterionModalitys = this.form.CriterionModalitys
            ? this.form.CriterionModalitys.split('|')
            : []
          this.form.TrialCriterionAdditionalAssessmentTypeList.forEach((v) => {
            this.$set(v, 'IsSelected', v.IsSelected || false)
            this.$set(
              this.form,
              'AdditionalAssessmentType' + v.Id,
              v.IsSelected
            )
          })
          this.isReadingTaskViewInOrder = res.Result.IsReadingTaskViewInOrder
          this.isConfirm = res.Result.IsSign
          this.IsMustGlobalReading = res.Result.IsMustGlobalReading
          this.$emit('setConfirm', res.Result.IsSign)
          this.$emit('setArbitrationReading', res.Result.IsArbitrationReading)
          this.$emit(
            'setAdditionalAssessment',
            this.form.IsAdditionalAssessment
          )
          this.$emit('setIsClinicalReading', res.Result.IsClinicalReading)
          this.$emit('setGlobalReading', res.Result.IsGlobalReading)
          this.$emit('setOncologyReading', res.Result.IsOncologyReading)
          this.$emit('setDigitPlaces', res.Result.DigitPlaces)
          this.$emit('setReadingTools', { readingTools: res.Result.ReadingToolList, readingSegmentTools: res.Result.SegmentToolList, ReadingTool: this.form.ReadingTool })

          if (res.Result.ReadingType === 1) {
            this.$emit('setArbitrationReading', false)
          }
        })
        .catch(() => {
          this.loading = false
        })
      // }).catch(() => {
      //   this.loading = false
      // })
    },
    // 配置信息保存
    handleSave(isPrompt = true) {
      return new Promise((resolve, reject) => {
        this.$refs['readingRulesForm'].validate((valid) => {
          if (!valid) {
            resolve(false)
          } else {
            this.loading = true
            if (this.form.ReadingType === 1) {
              this.form.IsArbitrationReading = false
            }
            // 保存配置信息
            this.form.TrialReadingCriterionId = this.trialReadingCriterionId
            setCriterionReadingInfo(this.form)
              .then((res) => {
                this.loading = false
                this.$emit('reloadArbitrationRules')
                this.$emit(
                  'setArbitrationReading',
                  this.form.IsArbitrationReading
                )
                this.$emit(
                  'setAdditionalAssessment',
                  this.form.IsAdditionalAssessment
                )
                this.$emit('setIsClinicalReading', this.form.IsClinicalReading)
                this.$emit('setGlobalReading', this.form.IsGlobalReading)
                this.$emit('setOncologyReading', this.form.IsOncologyReading)
                this.$emit('setDigitPlaces', this.form.DigitPlaces)
                this.$emit('setReadingTools', { readingTools: this.form.ReadingToolList, readingSegmentTools: this.form.SegmentToolList, ReadingTool: this.form.ReadingTool })
                if (this.form.ReadingType === 1) {
                  this.$emit('setArbitrationReading', false)
                }
                if (res.IsSuccess && isPrompt) {
                  this.$message.success(
                    this.$t('common:message:savedSuccessfully')
                  )
                }
                resolve(true)
              })
              .catch((_) => {
                this.loading = false
                resolve(false)
              })
          }
        })
      })
    },
    handleReadingToolListChange(v) {
      if (!v.includes('FixedRadiusCircleROI')) {
        this.form.CircleRadius = 10
      }
    },
    handleNumberInput(value, field) {
      if (!value) {
        this.form[field] = ''
        return
      }

      let val = value.toString()

      // 1. 清除“数字”和“.”以外的字符
      val = val.replace(/[^\d.]/g, '')
      // 2. 保证第一个字符不能是“.”
      val = val.replace(/^\./g, '')
      // 3. 保证不能连续输入多个“.”，只保留第一个
      val = val.replace(/\.{2,}/g, '.')
      val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      // 4. 限制只能输入两位小数
      val = val.replace(/^(\-)*(\d+)\.(\d{2}).*$/, '$1$2.$3')
      // 5. 处理前导零（例如输入 01 自动变成 1）
      if (val.length > 1 && val[0] === '0' && val[1] !== '.') {
        val = val.replace(/^0+/, '')
        if (val === '') val = '0'
      }
      this.$nextTick(() => {
        this.ruleForm[field] = val
      });
    },
  },
}
</script>
<style lang="scss" scoped>
.reading-rule-config-form {
  .fontColor {
    color: red;
  }
}

.upload {
  display: inline-block;
  height: 30px;
  width: 90px;
  padding: 2px 10px;
  line-height: 23px;
  position: relative;
  text-decoration: none;
  border-radius: 3px;
  overflow: hidden;
  text-align: center;
  background: #428bca;
  border-color: #428bca;
  color: #fff;

  .select-file {
    height: 30px;
    width: 90px;
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 0;
    opacity: 0;
    font-size: 0;
  }

  .btn-select {
    //给显示在页面上的按钮写样式
    width: 90px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
    border-radius: 24px;
    overflow: hidden;
    position: absolute;
    top: 0;
    left: 0;
    pointer-events: none; //pointer-events:none用来控制该标签的点击穿透事件
  }
}
</style>
