<template>
  <div class="process-config-form">
    <!-- 配置信息表单 -->
    <el-form
      ref="processConfigForm"
      v-loading="loading"
      :model="form"
      label-width="300px"
      style="width: 800px"
      :rules="rules"
      size="small"
    >
      <!-- 阅片方式 -->
      <el-form-item
        :label="$t('trials:processCfg:form:readingMode')"
        prop="ReadingMode"
      >
        <el-radio-group
          v-model="form.ReadingMode"
          :disabled="form.IsTrialProcessConfirmed && !isEdit"
        >
          <el-radio
            v-for="item of $d.ReadingMode"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="$t('trials:processCfg:form:criterion')"
        prop="TrialCriterionNamesStr"
      >
        <el-input
          v-model="form.TrialCriterionNamesStr"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 3 }"
          style="width: 80%"
          disabled
        />
        <el-button
          v-if="TrialStatusStr === 'Initializing'"
          :disabled="!isEdit"
          icon="el-icon-plus"
          circle
          @click="handleSetCriterion"
        />
      </el-form-item>
      <!-- 临床信息传输 -->
      <el-form-item
        :label="$t('trials:logincCfg:form:clinicalInforTransfer')"
        prop="ClinicalInformationTransmissionEnum"
      >
        <el-radio-group
          v-model="form.ClinicalInformationTransmissionEnum"
          :disabled="form.IsTrialProcessConfirmed && !isEdit"
        >
          <el-radio
            v-for="item of $d.ClinicalInformationTransmissionEnum"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 临床数据配置 -->
      <el-form-item
        v-if="form.ClinicalInformationTransmissionEnum === 1"
        :label="$t('trials:logincCfg:form:clinicalConfig')"
        prop="ClinicalDataSetNamesStr"
      >
        <el-input
          v-model="form.ClinicalDataSetNamesStr"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 3 }"
          style="width: 80%"
          disabled
        />
        <el-button
          v-if="form.TrialCriterionNamesStr"
          icon="el-icon-plus"
          circle
          @click="handleSetCD"
        />
      </el-form-item>
      <!-- 影像质控流程 -->
      <el-form-item
        :label="$t('trials:processCfg:form:qcProcess')"
        prop="QCProcessEnum"
      >
        <el-radio-group
          v-model="form.QCProcessEnum"
          :disabled="form.IsTrialProcessConfirmed && !isEdit"
        >
          <el-radio
            v-for="item of $d.QCProcessEnum"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 一致性核查流程 -->
      <el-form-item
        :label="$t('trials:processCfg:form:conProcess')"
        prop="IsImageConsistencyVerification"
      >
        <el-radio-group
          v-model="form.IsImageConsistencyVerification"
          :disabled="form.IsTrialProcessConfirmed && !isEdit"
        >
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="`IsImageConsistencyVerification${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 采集影像 -->
      <el-form-item
        :label="$t('trials:processCfg:form:CollectImagesEnum')"
        prop="CollectImagesEnum"
      >
        <el-radio-group
          v-model="form.CollectImagesEnum"
          :disabled="form.IsTrialProcessConfirmed && !isEdit"
        >
          <el-radio
            v-for="item of $d.CollectImagesType"
            :key="item.id"
            :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="form.IsTrialProcessConfirmed && !isEdit"
        >
          <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:processCfg:form:readingType')"
        prop="ReadingType"
      >
        <el-radio-group
          v-model="form.ReadingType"
          :disabled="form.IsTrialProcessConfirmed && !isEdit"
          @change="handleReadingTypeChange"
        >
          <el-radio
            v-for="item of $d.ReadingMethod"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      &lt;!&ndash; 任务展示方式 &ndash;&gt;
      <el-form-item
        label="任务展示方式"
        prop="IsReadingTaskViewInOrder"
      >
        <el-radio-group
          v-model="form.IsReadingTaskViewInOrder"
          :disabled="form.IsTrialProcessConfirmed && !isEdit"
          @change="handleIsReadingTaskViewInOrderChange"
        >
          <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>
      &lt;!&ndash; 全局阅片 &ndash;&gt;
      <el-form-item
        :label="$t('trials:processCfg:form:global')"
        prop="IsGlobalReading"
      >
        <el-radio-group
          v-model="form.IsGlobalReading"
          :disabled="(form.IsTrialProcessConfirmed && !isEdit) || !form.IsReadingTaskViewInOrder"
        >
          <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>
      &lt;!&ndash; 仲裁阅片 &ndash;&gt;
      <el-form-item
        :label="$t('trials:processCfg:form:ad')"
        prop="IsArbitrationReading"
      >
        <el-radio-group
          v-model="form.IsArbitrationReading"
          :disabled="form.ReadingType!== 3 || (form.IsTrialProcessConfirmed && !isEdit)"
        >
          <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>
      &lt;!&ndash; 临床阅片 &ndash;&gt;
      <el-form-item
        :label="$t('trials:processCfg:form:clinical')"
        prop="IsClinicalReading"
      >
        <el-radio-group
          v-model="form.IsClinicalReading"
          :disabled="(form.IsTrialProcessConfirmed && !isEdit) || !form.IsReadingTaskViewInOrder"
        >
          <el-radio
            v-for="item of $d.YesOrNo"
            :key="`IsClinicalReading${item.value}`"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>-->
      <!-- 仲裁规则 -->
      <!-- <el-form-item
        :label="$t('trials:processCfg:form:adRules')"
        prop="ArbitrationRule"
      >
        <el-radio-group
          v-model="form.ArbitrationRule"
          :disabled="form.ReadingType === 1 || (form.IsTrialProcessConfirmed && !isEdit)"
        >
          <el-radio
            v-for="item of $d.ArbitrationRule"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item> -->
      <el-form-item>
        <!-- 保存 -->
        <el-button
          v-if="
            form.IsTrialProcessConfirmed === false &&
            hasPermi(['trials:trials-panel:setting:trial-config:save'])
          "
          type="primary"
          @click="handleSave"
        >
          {{ $t('common:button:save') }}
        </el-button>
        <!-- 配置确认 -->
        <el-button
          v-if="
            form.IsTrialProcessConfirmed === false &&
            hasPermi(['trials:trials-panel:setting:trial-config:save'])
          "
          type="primary"
          @click="handleConfirm"
        >
          {{ $t('trials:trialCfg:button:confirm') }}
        </el-button>
        <!-- 配置更新 -->
        <el-button
          v-if="
            form.IsTrialProcessConfirmed === true &&
            !isEdit &&
            TrialStatusStr === 'Initializing' &&
            hasPermi(['trials:trials-panel:setting:trial-config:save'])
          "
          type="primary"
          @click="isEdit = true"
        >
          {{ $t('trials:trialCfg:button:update') }}
        </el-button>
        <!-- 配置更新确认 -->
        <el-button
          v-if="
            form.IsTrialProcessConfirmed === true &&
            isEdit &&
            hasPermi(['trials:trials-panel:setting:trial-config:save'])
          "
          type="primary"
          @click="handleUpdate"
        >
          {{ $t('trials:trialCfg:button:updateAndConfirm') }}
        </el-button>
        <!-- 取消 -->
        <el-button
          v-if="
            form.IsTrialProcessConfirmed === true &&
            isEdit &&
            hasPermi(['trials:trials-panel:setting:trial-config:save'])
          "
          type="primary"
          @click="isEdit = false"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 配置信息确认框 -->
    <el-dialog
      v-if="confirmVisible"
      :visible.sync="confirmVisible"
      :close-on-click-modal="false"
      width="600px"
      :title="$t('trials:trialCfg:dialogTitle:cfgConfirm')"
      custom-class="base-dialog-wrapper"
    >
      <div class="base-dialog-body">
        <el-table :data="confirmData" border style="width: 100%" size="small">
          <!-- 配置项 -->
          <el-table-column
            prop="Name"
            :label="$t('trials:trialCfg:table:cfgItem')"
            show-overflow-tooltip
          />
          <!-- 配置值 -->
          <el-table-column
            prop="NewVal"
            :label="$t('trials:trialCfg:table:cfgVal')"
            show-overflow-tooltip
          />
        </el-table>
      </div>
      <div
        class="base-dialog-footer"
        style="text-align: right; margin-top: 10px"
      >
        <!-- 确认 -->
        <el-button
          size="small"
          type="primary"
          :loading="btnLoading"
          @click="handleConfirmConfigData"
        >
          {{ $t('trials:trialCfg:button:confirmCfg') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 配置信息更新框 -->
    <el-dialog
      v-if="updateVisible"
      :visible.sync="updateVisible"
      :close-on-click-modal="false"
      width="600px"
      :title="$t('trials:trialCfg:dialogTitle:cfgConfirm')"
      custom-class="base-dialog-wrapper"
    >
      <div class="base-dialog-body">
        <el-table :data="confirmData" border style="width: 100%" size="small">
          <!-- 配置项 -->
          <el-table-column
            prop="Name"
            :label="$t('trials:trialCfg:table:cfgItem')"
            show-overflow-tooltip
          />
          <!-- 配置值（更改前） -->
          <el-table-column
            prop="OldVal"
            :label="`${$t('trials:trialCfg:table:cfgVal')} （${$t(
              'trials:trialCfg:table:beforeChange'
            )}）`"
            show-overflow-tooltip
          />
          <!-- 配置值（更改后） -->
          <el-table-column
            prop="NewVal"
            :label="`${$t('trials:trialCfg:table:cfgVal')} （${$t(
              'trials:trialCfg:table:updated'
            )}）`"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span
                :class="{ fontColor: scope.row.NewVal !== scope.row.OldVal }"
                >{{ scope.row.NewVal }}</span
              >
            </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"
          :loading="btnLoading"
          @click="handleUpdateConfigData"
        >
          {{ $t('trials:trialCfg:button:confirmCfg') }}
        </el-button>
      </div>
    </el-dialog>

    <!-- 配置信息签名框 -->
    <el-dialog
      v-if="signVisible"
      :visible.sync="signVisible"
      :close-on-click-modal="false"
      width="600px"
      custom-class="base-dialog-wrapper"
    >
      <div slot="title">
        <span style="font-size: 18px">{{ $t('common:dialogTitle:sign') }}</span>
        <span style="font-size: 12px; margin-left: 5px">{{
          `(${$t('common:label:sign')}${currentUser})`
        }}</span>
      </div>
      <SignForm
        ref="signForm"
        :sign-code-enum="signCode"
        @closeDialog="closeSignDialog"
      />
    </el-dialog>

    <!-- 配置阅片标准模板选项 -->
    <el-dialog
      v-if="criterionListVisible"
      :visible.sync="criterionListVisible"
      :close-on-click-modal="false"
      :title="$t('trials:processCfg:title:criterion')"
      custom-class="base-dialog-wrapper"
      width="1000px"
    >
      <div v-loading="listLoading" class="base-dialog-body">
        <div
          class="search-form"
          style="display: flex; justify-content: space-between"
        >
          <el-form :inline="true" size="mini" class="base-search-form">
            <!-- 阅片标准 -->
            <el-form-item :label="$t('trials:processCfg:title:criterion')">
              <el-input
                v-model="criterionSearchForm.CriterionName"
                clearable
                style="width: 120px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearchCriterion">
                {{ $t('common:button:search') }}
              </el-button>
              <el-button type="primary" @click="handleResetCriterion">
                {{ $t('common:button:reset') }}
              </el-button>
            </el-form-item>
          </el-form>
          <div>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-plus"
              @click="handleAddCriterion"
            >
              {{ $t('common:button:new') }}
            </el-button>
          </div>
        </div>
        <el-table
          ref="criterionList"
          :data="criterionList"
          stripe
          height="450"
          row-key="Id"
          class="criterion-table"
          @select="selectCriterion"
        >
          <el-table-column
            type="selection"
            align="left"
            width="45"
            :reserve-selection="true"
          />
          <el-table-column type="index" width="40" />
          <el-table-column
            prop="CriterionName"
            :label="$t('trials:processCfg:title:criterion')"
          />
          <el-table-column
            prop="CriterionType"
            :label="$t('trials:processCfg:title:criterionType')"
          >
            <template slot-scope="scope">
              <span>{{ $fd('CriterionType', scope.row.CriterionType) }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="IsCompleteConfig"
            label="是否配置完成"
          >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.IsCompleteConfig"
                :disabled="scope.row.IsBeUsed || scope.row.IsSystemData"
                @change="changeCriterionStatus($event, scope.row)"
              />
            </template>
          </el-table-column> -->
          <el-table-column :label="$t('common:action:action')">
            <template slot-scope="scope">
              <!-- <el-button
                type="primary"
                size="mini"
                :disabled="scope.row.IsBeUsed"
                @click="handleConfigCriterion(scope.row)"
              >
                eCRF
              </el-button> -->
              <el-button
                circle
                :title="$t('common:button:edit')"
                icon="el-icon-edit"
                :disabled="scope.row.IsSystemData"
                @click="handleEditCriterion(scope.row)"
              >
              </el-button>
              <el-button
                circle
                :title="$t('common:button:delete')"
                icon="el-icon-delete"
                :disabled="scope.row.IsSystemData"
                @click="handleDeleteCriterion(scope.row)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          style="text-align: right; margin-top: 10px"
          class="page"
          :total="criterionListTotal"
          :page.sync="criterionSearchForm.PageIndex"
          :limit.sync="criterionSearchForm.PageSize"
          @pagination="getCriterionList"
        />
      </div>
      <div
        class="base-dialog-footer"
        style="text-align: right; margin-top: 10px"
      >
        <el-button
          size="small"
          type="primary"
          :disabled="listLoading"
          @click="criterionListVisible = false"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="listLoading"
          @click="handleConfirmCriterion"
        >
          {{ $t('common:button:confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 自定义阅片标准 -->
    <el-dialog
      v-if="criterionFormDg.visible"
      :visible.sync="criterionFormDg.visible"
      :close-on-click-modal="false"
      :title="criterionFormDg.title"
      custom-class="base-dialog-wrapper"
      append-to-body
      width="500px"
    >
      <div class="base-dialog-body">
        <el-form
          ref="criterionForm"
          onsubmit="return false;"
          :model="criterionForm"
          label-width="210px"
        >
          <!-- 阅片标准名称 -->
          <el-form-item
            :label="this.$t('trials:processCfg:title:criterionName')"
            prop="CriterionName"
            :rules="[
              { required: true, message: $t('common:ruleMessage:specify') },
              { max: 50, message: `${$t('common:ruleMessage:maxLength')} 50` },
            ]"
          >
            <el-input v-model="criterionForm.CriterionName" />
          </el-form-item>
        </el-form>
      </div>
      <div
        class="base-dialog-footer"
        style="text-align: right; margin-top: 10px"
      >
        <el-button
          size="small"
          type="primary"
          :disabled="listLoading"
          @click="handleCancelSave"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="listLoading"
          @click="handleSaveCriterion"
        >
          {{ $t('common:button:confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <!-- 配置阅片标准问题 -->
    <el-dialog
      v-if="criterionQSVisible"
      :visible.sync="criterionQSVisible"
      :close-on-click-modal="false"
      title="eCRF模板"
      custom-class="base-dialog-wrapper"
      append-to-body
      width="1300px"
    >
      <div class="base-dialog-body">
        <CriterionConfig
          :data="currentCriterionRow"
          @getList="getCriterionList"
        />
      </div>
    </el-dialog>
    <!-- 配置临床信息模板选项 -->
    <el-dialog
      v-if="clinicalDataVisible"
      :visible.sync="clinicalDataVisible"
      :close-on-click-modal="false"
      :title="$t('trials:processCfg:title:clinicalDataCfg')"
      width="1250px"
      custom-class="base-dialog-wrapper"
    >
      <div v-loading="listLoading" class="base-dialog-body">
        <div style="text-align: right">
          <el-button
            v-if="isEdit"
            size="mini"
            type="primary"
            icon="el-icon-plus"
            @click="handleAddClinicalData"
          >
            {{ $t('common:button:new') }}
          </el-button>
        </div>
        <el-table
          ref="clinicalData"
          :data="clinicalDataList"
          stripe
          height="400"
          row-key="Id"
          class="criterion-table"
          @selection-change="handleCDSelectChange"
        >
          <!-- :selectable="handleSelectable" -->
          <el-table-column
            type="selection"
            align="left"
            width="45"
            :reserve-selection="true"
            :selectable="handleSelectable"
          />
          <el-table-column type="index" width="40" />
          <!-- 临床数据名称 -->
          <el-table-column
            prop="ClinicalDataSetName"
            :label="$t('trials:processCfg:title:clinicalDataName')"
            width="180"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{
                $i18n.locale === 'zh'
                  ? scope.row.ClinicalDataSetName
                  : scope.row.ClinicalDataSetEnName
              }}
            </template>
          </el-table-column>
          <!-- 上传人 -->
          <el-table-column
            prop="UploadRole"
            :label="$t('trials:processCfg:title:uploader')"
            width="120"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ $fd('ClinicalDataUploadRole', scope.row.UploadRole) }}
            </template>
          </el-table-column>
          <!-- 数据级别 -->
          <el-table-column
            prop="ClinicalDataLevel"
            :label="$t('trials:processCfg:title:dataLevel')"
            width="180"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ $fd('ClinicalLevel', scope.row.ClinicalDataLevel) }}
            </template>
          </el-table-column>
          <!-- 传输方式 -->
          <el-table-column
            prop="ClinicalUploadType"
            :label="$t('trials:processCfg:title:transferType')"
            width="180"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ $fd('ClinicalUploadType', scope.row.ClinicalUploadType) }}
            </template>
          </el-table-column>
          <!-- 阅片标准 -->
          <el-table-column
            prop="CriterionEnumList"
            :label="$t('trials:processCfg:table:criterion')"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ scope.row.TrialCriterionNameList.join(', ') }}
            </template>
          </el-table-column>
          <!-- 模板名称 -->
          <el-table-column
            :label="$t('common:action:action')"
            width="220"
            fixed="right"
            style="text-align: right"
          >
            <template slot-scope="scope">
              <!-- 下载 -->
              <el-button
                v-if="scope.row.FileName && scope.row.ClinicalUploadType"
                circle
                icon="el-icon-download"
                @click="handleDownloadTpl(scope.row)"
              >
              </el-button>
              <el-button
                v-if="scope.row.FileName && !scope.row.ClinicalUploadType"
                circle
                icon="el-icon-view"
                @click="handlePreviewTpl(scope.row)"
              >
              </el-button>
              <el-button
                v-if="scope.row.ClinicalUploadType === 2"
                circle
                icon="el-icon-view"
                @click="handlePreview(scope.row)"
              >
              </el-button>
              <el-button
                circle
                v-if="isEdit"
                :title="$t('trials:readingUnit:qsList:title:qsConfig')"
                icon="el-icon-set-up"
                :disabled="scope.row.ClinicalUploadType !== 2"
                @click="handleConfigQuestion(scope.row)"
              >
              </el-button>
              <!-- 编辑 -->
              <el-button
                circle
                v-if="isEdit"
                :title="$t('common:button:edit')"
                icon="el-icon-edit"
                :disabled="
                  TrialStatusStr !== 'Initializing' ||
                  !!scope.row.SystemClinicalDataSetId
                "
                @click="handleEditClinicalData(scope.row)"
              >
              </el-button>
              <!-- 删除 -->
              <el-button
                circle
                v-if="isEdit"
                :title="$t('common:button:delete')"
                icon="el-icon-delete"
                :disabled="
                  TrialStatusStr !== 'Initializing' ||
                  form.ClinicalDataSetNames.indexOf(
                    scope.row.ClinicalDataSetName
                  ) > -1 ||
                  !!scope.row.SystemClinicalDataSetId
                "
                @click="handleDeleteClinicalData(scope.row)"
              >
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div
        v-if="isEdit"
        class="base-dialog-footer"
        style="text-align: right; margin-top: 10px"
      >
        <el-button
          size="small"
          type="primary"
          :disabled="listLoading"
          @click="clinicalDataVisible = false"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button
          size="small"
          type="primary"
          :disabled="listLoading"
          @click="handleConfirmClinicalData"
        >
          {{ $t('common:button:confirm') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-if="addOrEditCD.visible"
      :visible.sync="addOrEditCD.visible"
      :close-on-click-modal="false"
      :title="addOrEditCD.title"
      width="500px"
      append-to-body
      custom-class="base-dialog-wrapper"
    >
      <ClinicalDataForm
        ref="addOrEditCD"
        :trial-id="form.TrialId"
        :data="currentRow"
        @close="addOrEditCD.visible = false"
        @getList="getClinicalDataList"
      />
    </el-dialog>
    <el-dialog
      v-if="previewTpl.visible"
      :visible.sync="previewTpl.visible"
      :close-on-click-modal="false"
      :title="previewTpl.title"
      width="800px"
      append-to-body
      custom-class="base-dialog-wrapper"
    >
      <div style="margin: 0 20px">
        <!-- 既往放疗史 -->
        <h4>{{ $t('trials:uploadClinicalData:title:pastTreatment') }}</h4>
        <el-table :data="[]" style="width: 100%">
          <el-table-column type="index" width="50" />
          <!-- 放疗部位 -->
          <el-table-column
            prop="Position"
            :label="$t('trials:uploadClinicalData:table:bodyPart')"
          />
          <!-- 开始日期 -->
          <el-table-column
            prop="StartTime"
            :label="$t('trials:uploadClinicalData:table:beginDate')"
          >
            <template slot-scope="scope">
              {{
                scope.row.StartTime
                  ? moment(scope.row.StartTime).format('YYYY-MM-DD')
                  : ''
              }}
            </template>
          </el-table-column>
          <!-- 结束日期 -->
          <el-table-column
            prop="EndTime"
            :label="$t('trials:uploadClinicalData:table:endDate')"
          >
            <template slot-scope="scope">
              {{
                scope.row.EndTime
                  ? moment(scope.row.EndTime).format('YYYY-MM-DD')
                  : ''
              }}
            </template>
          </el-table-column>
          <!-- 病灶是否PD -->
          <el-table-column
            prop="IsPD"
            :label="$t('trials:uploadClinicalData:table:isPD')"
          >
            <template slot-scope="scope">
              {{ $fd('IsPdEnum', scope.row.IsPD) }}
            </template>
          </el-table-column>
          <el-table-column
            v-if="
              hasPermi(['trials:trials-panel:visit:crc-upload:upload']) &&
              allowAddOrEdit
            "
            :label="$t('common:action:action')"
            min-width="120"
          >
            <template slot-scope="scope">
              <!-- 编辑 -->
              <el-button
                v-if="allowAddOrEdit"
                icon="el-icon-edit-outline"
                circle
                :title="$t('common:button:edit')"
                size="small"
                @click.native.prevent="editRow(scope.row, 1)"
              />
              <!-- 移除 -->
              <el-button
                v-if="
                  data.SubmitState * 1 < 2 ||
                  (data.SubmitState === 2 && data.IsQCConfirmedReupload)
                "
                v-hasPermi="['trials:trials-panel:visit:crc-upload:upload']"
                icon="el-icon-delete"
                circle
                :title="$t('common:button:delete')"
                size="small"
                @click.native.prevent="deletePreviousHistory(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
        <!-- 既往手术史 -->
        <h4>{{ $t('trials:uploadClinicalData:title:pastSurgery') }}</h4>
        <el-table :data="[]" style="width: 100%">
          <el-table-column type="index" width="50" />
          <!-- 手术名称 -->
          <el-table-column
            prop="OperationName"
            :label="$t('trials:uploadClinicalData:table:surgeryName')"
          />
          <!-- 手术日期 -->
          <el-table-column
            prop="OperationTime"
            :label="$t('trials:uploadClinicalData:table:surgeryDate')"
          >
            <template slot-scope="scope">
              {{
                scope.row.OperationTime
                  ? moment(scope.row.OperationTime).format('YYYY-MM-DD')
                  : ''
              }}
            </template>
          </el-table-column>

          <el-table-column
            v-if="
              hasPermi(['trials:trials-panel:visit:crc-upload:upload']) &&
              allowAddOrEdit
            "
            :label="$t('common:action:action')"
            min-width="200"
          >
            <template slot-scope="scope">
              <!-- 编辑 -->
              <el-button
                v-if="allowAddOrEdit"
                icon="el-icon-edit-outline"
                circle
                :title="$t('common:button:edit')"
                size="small"
                @click.native.prevent="editRow(scope.row, 2)"
              />
              <!-- 移除 -->
              <el-button
                v-if="
                  data.SubmitState * 1 < 2 ||
                  (data.SubmitState === 2 && data.IsQCConfirmedReupload)
                "
                v-hasPermi="['trials:trials-panel:visit:crc-upload:upload']"
                icon="el-icon-delete"
                circle
                :title="$t('common:button:delete')"
                size="small"
                @click.native.prevent="deletePreviousSurgery(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
        <!-- 既往其他治疗史 -->
        <h4>{{ $t('trials:uploadClinicalData:title:others') }}</h4>
        <el-table :data="[]" style="width: 100%">
          <el-table-column type="index" width="50" />
          <!-- 治疗类型 -->
          <el-table-column
            prop="TreatmentType"
            :label="$t('trials:uploadClinicalData:table:treatmentType')"
          />
          <!-- 开始日期 -->
          <el-table-column
            prop="StartTime"
            :label="$t('trials:uploadClinicalData:table:treatmentbeginDate')"
          >
            <template slot-scope="scope">
              {{
                scope.row.StartTime
                  ? moment(scope.row.StartTime).format('YYYY-MM-DD')
                  : ''
              }}
            </template>
          </el-table-column>
          <!-- 结束日期 -->
          <el-table-column
            prop="EndTime"
            :label="$t('trials:uploadClinicalData:table:treatmentendDate')"
          >
            <template slot-scope="scope">
              {{
                scope.row.EndTime
                  ? moment(scope.row.EndTime).format('YYYY-MM-DD')
                  : ''
              }}
            </template>
          </el-table-column>

          <el-table-column
            v-if="
              hasPermi(['trials:trials-panel:visit:crc-upload:upload']) &&
              allowAddOrEdit
            "
            :label="$t('common:action:action')"
            min-width="200"
          >
            <template slot-scope="scope">
              <!-- 编辑 -->
              <el-button
                v-if="allowAddOrEdit"
                icon="el-icon-edit-outline"
                circle
                :title="$t('common:button:edit')"
                size="small"
                @click.native.prevent="editRow(scope.row, 3)"
              />
              <!-- 移除 -->
              <el-button
                v-if="
                  data.SubmitState * 1 < 2 ||
                  (data.SubmitState === 2 && data.IsQCConfirmedReupload)
                "
                icon="el-icon-delete"
                circle
                :title="$t('common:button:delete')"
                size="small"
                @click.native.prevent="deletePreviousOther(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
    <el-dialog
      v-if="QuestionConfigVisible.visible"
      :visible.sync="QuestionConfigVisible.visible"
      :close-on-click-modal="false"
      :title="QuestionConfigVisible.title"
      width="1600px"
      append-to-body
      custom-class="base-dialog-wrapper"
    >
      <ClinicalQuestionConfig
        ref="QuestionConfigVisible"
        @handlePreview="handlePreview"
        :data="currentRow"
        @close="
          QuestionConfigVisible.visible = false
          getClinicalDataList()
        "
        @getList="getClinicalDataList"
      />
    </el-dialog>
    <el-dialog
      v-if="preview.visible"
      :visible.sync="preview.visible"
      :close-on-click-modal="false"
      :title="preview.title"
      :fullscreen="true"
    >
      <clinicalDataQuestions :data="rowData" :trial-clinical-id="rowData.Id" />
    </el-dialog>
  </div>
</template>
<script>
import {
  getTrialCriterionSelectList,
  configTrialProcessInfo,
  getTrialClinicalDataTrialSetList,
  deleteClinicalTrialSetData,
  DownloadTrialClinicalFile,
  getReadingQuestionCriterionTrialList,
  addOrUpdateReadingQuestionCriterionTrial,
  deleteReadingQuestionCriterionTrial,
  setTrialReadingQuestionCriterionIsIsCompleteConfig,
  configTrialProcessInfoVerification,
} from '@/api/trials'
import { ConfigTrialProcessInfoConfirm } from '@/api/trials/setting'
import SignForm from '@/views/trials/components/newSignForm'
import Pagination from '@/components/Pagination'
import ClinicalDataForm from './clinicalDataForm'
import ClinicalQuestionConfig from './ClinicalQuestionConfig'
import CriterionConfig from './criterionConfig'
import const_ from '@/const/sign-code'
import clinicalDataQuestions from '@/components/clinicalDataQuestions'

const criterionSearchDataDefault = () => {
  return {
    PageIndex: 1,
    PageSize: 20,
    CriterionName: '',
  }
}
export default {
  name: 'ProcessConfig',
  components: {
    SignForm,
    Pagination,
    CriterionConfig,
    ClinicalDataForm,
    ClinicalQuestionConfig,
    clinicalDataQuestions,
  },
  data() {
    // var validator = (rule, value, callback) => {
    //   if (value.length === 0) {
    //     callback(new Error(this.$t('common:ruleMessage:select')))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      VUE_IS_TEST: process.env.VUE_APP_IS_TEST,
      form: {
        TrialId: '',
        ClinicalInformationTransmissionEnum: 1,
        ClinicalDataSetNames: [],
        ClinicalDataTrialSetIds: [],
        ClinicalDataSetNamesStr: '',
        QCProcessEnum: null,
        CollectImagesEnum: null,
        IsImageConsistencyVerification: null,
        ReadingMode: null,
        // ImagePlatform: null,
        // DigitPlaces: null,
        ReadingType: null,
        IsReadingTaskViewInOrder: null,
        IsGlobalReading: null,
        IsArbitrationReading: null,
        IsClinicalReading: null,
        // ArbitrationRule: null,
        IsTrialProcessConfirmed: false,
        // CriterionIds: [],
        TrialCriterionNamesStr: '',
        TrialCriterionIds: [],
        TrialCriterionNames: [],
        TrialCriterionIdEnums: [],
      },
      rules: {
        ClinicalDataSetNamesStr: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
        ],
        ClinicalInformationTransmissionEnum: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: 'blur',
          },
        ],
        CollectImagesEnum: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        QCProcessEnum: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        IsImageConsistencyVerification: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        ReadingMode: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        // ImagePlatform: [
        //   { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        // ],
        // CriterionIds: [
        //   { required: true, validator: validator, trigger: ['blur', 'change'] }
        // ],
        TrialCriterionNamesStr: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur', 'change'],
          },
        ],
        // DigitPlaces: [
        //   { 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'] }
        // ],
        // IsClinicalReading: [
        //   { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        // ]
        // ArbitrationRule: [
        //   { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        // ]
      },
      confirmVisible: false,
      updateVisible: false,
      signVisible: false,
      btnLoading: false,
      confirmData: [],
      loading: false,
      signText: '',
      signCode: '',
      currentUser: zzSessionStorage.getItem('userName'),
      initialForm: {},
      isEdit: false,
      TrialStatusStr: '',
      criterionListVisible: false,
      criterionList: [],
      criterionListTotal: 0,
      criterionSearchForm: criterionSearchDataDefault(),
      listLoading: false,
      selectedCriterions: [],
      selectCriterionIds: [],
      criterionFormDg: { visible: false, title: '' },
      criterionForm: { Id: '', CriterionName: '' },
      criterionQSVisible: false,
      currentCriterionRow: {},
      clinicalDataList: [],
      clinicalDataVisible: false,
      addOrEditCD: { visible: false, title: '' },
      previewTpl: { visible: false, title: '' },
      currentRow: {},
      selectClinicalDataArr: [],
      selectedCD: [],
      QuestionConfigVisible: { visible: false, title: '' },
      preview: { visible: false, title: this.$t('common:button:preview') },
    }
  },
  mounted() {},
  methods: {
    handlePreview(row) {
      this.rowData = { ...row }
      this.preview.visible = true
    },
    handleConfigQuestion(row) {
      this.currentRow = { ...row }
      this.QuestionConfigVisible.visible = true
      this.QuestionConfigVisible.title = this.$t(
        'trials:readingUnit:qsList:title:qsConfig'
      )
    },
    handlePreviewTpl() {
      this.previewTpl.visible = true
      this.previewTpl.title = this.$t('common:button:preview')
    },
    // 配置信息保存
    handleSave() {
      this.$refs['processConfigForm'].validate(async (valid) => {
        if (!valid) return
        this.loading = true
        // 保存配置信息
        configTrialProcessInfo(this.form)
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              this.initialForm = { ...this.form }
              this.$message.success(this.$t('common:message:savedSuccessfully'))
            }
          })
          .catch((_) => {
            this.loading = false
          })
      })
    },

    // 打开配置信息确认框
    handleConfirm() {
      this.$refs['processConfigForm'].validate(async (valid) => {
        if (!valid) return
        this.getConfigArr()
        this.confirmVisible = true
      })
    },

    // 打开配置信息更新框
    handleUpdate() {
      this.$refs['processConfigForm'].validate(async (valid) => {
        if (!valid) return
        this.getConfigArr()
        this.updateVisible = true
      })
    },
    // 配置确认
    handleConfirmConfigData() {
      const { ProcessConfigConfirmation } = const_.processSignature
      this.signCode = ProcessConfigConfirmation
      // this.confirmConfigData()
      this.initialForm = { ...this.form }
      this.signVisible = true
    },
    // 配置更新
    handleUpdateConfigData() {
      const { ProcessConfigUpdates } = const_.processSignature
      this.signCode = ProcessConfigUpdates
      this.initialForm = { ...this.form }
      this.signVisible = true
    },
    // 配置确认签名
    confirmConfigData() {
      this.btnLoading = true
      // 保存配置信息
      configTrialProcessInfo(this.form)
        .then((res) => {
          this.btnLoading = false
          if (res.IsSuccess) {
            this.initialForm = { ...this.form }
            this.signVisible = true
          }
        })
        .catch((_) => {
          this.btnLoading = false
        })
    },
    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名并确认
    async signConfirm(signInfo) {
      this.loading = true
      var params = {
        data: this.form,
        signInfo: signInfo,
      }
      // 保存并签名确认
      ConfigTrialProcessInfoConfirm(params)
        .then((res) => {
          this.loading = false
          if (res.IsSuccess) {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.form.IsTrialProcessConfirmed = true
            this.isEdit = false
            this.$refs['signForm'].btnLoading = false
            this.signVisible = false
            this.confirmVisible = false
            this.updateVisible = false
            this.$emit('refresh')
          }
        })
        .catch((_) => {
          this.loading = false
          this.$refs['signForm'].btnLoading = false
        })
    },

    // 配置信息数组结构
    getConfigArr() {
      // var criterions = []
      // this.form.CriterionIds.map(id => {
      //   criterions.push(this.$fd('ReadingStandard', id, 'id'))
      // })
      // var initialCriterions = []
      // this.initialForm.CriterionIds.map(id => {
      //   initialCriterions.push(this.$fd('ReadingStandard', id, 'id'))
      // })
      this.confirmData = [
        {
          Name: this.$t('trials:processCfg:form:readingMode'), // 阅片方式
          NewVal: this.$fd('ReadingMode', this.form.ReadingMode),
          OldVal: this.$fd('ReadingMode', this.initialForm.ReadingMode),
        },
        // {
        //   Name: this.$t('trials:processCfg:form:imagePlatform'), // 阅片平台
        //   NewVal: this.$fd('ImagePlatform', this.form.ImagePlatform),
        //   OldVal: this.$fd('ImagePlatform', this.initialForm.ImagePlatform)
        // },
        {
          Name: this.$t('trials:processCfg:form:criterion'), // 阅片标准
          NewVal: this.form.TrialCriterionNames.join(', '),
          OldVal: this.initialForm.TrialCriterionNames.join(', '),
        },
        {
          Name: this.$t('trials:logincCfg:form:clinicalInforTransfer'),
          NewVal: this.$fd(
            'ClinicalInformationTransmissionEnum',
            this.form.ClinicalInformationTransmissionEnum
          ),
          OldVal: this.$fd(
            'ClinicalInformationTransmissionEnum',
            this.initialForm.ClinicalInformationTransmissionEnum
          ),
        },
        {
          Name: this.$t('trials:logincCfg:form:clinicalConfig'),
          NewVal: this.form.ClinicalDataSetNames.join(', '),
          OldVal: this.initialForm.ClinicalDataSetNames.join(', '),
        },
        {
          Name: this.$t('trials:processCfg:form:qcProcess'), // 影像质控流程
          NewVal: this.$fd('QCProcessEnum', this.form.QCProcessEnum),
          OldVal: this.$fd('QCProcessEnum', this.initialForm.QCProcessEnum),
        },
        {
          Name: this.$t('trials:processCfg:form:conProcess'), // 一致性核查流程
          NewVal: this.$fd('YesOrNo', this.form.IsImageConsistencyVerification),
          OldVal: this.$fd(
            'YesOrNo',
            this.initialForm.IsImageConsistencyVerification
          ),
        },
        {
          Name: this.$t('trials:processCfg:form:CollectImagesEnum'), // 采集影像
          NewVal: this.$fd('CollectImagesType', this.form.CollectImagesEnum),
          OldVal: this.$fd(
            'CollectImagesType',
            this.initialForm.CollectImagesEnum
          ),
        },
        // {
        //   Name: this.$t('trials:processCfg:form:criterion'), // 阅片标准
        //   NewVal: criterions.length > 0 ? criterions.join(', ') : '',
        //   OldVal: initialCriterions.length > 0 ? initialCriterions.join(', ') : ''
        // },
        // {
        //   Name: this.$t('trials:processCfg:form:digitPlaces'), // 修约小数位数
        //   NewVal: this.$fd('DigitPlaces', this.form.DigitPlaces),
        //   OldVal: this.$fd('DigitPlaces', this.initialForm.DigitPlaces)
        // },
        // {
        //   Name: this.$t('trials:processCfg:form:readingType'), // 阅片模式
        //   NewVal: this.$fd('ReadingMethod', this.form.ReadingType),
        //   OldVal: this.$fd('ReadingMethod', this.initialForm.ReadingType)
        // },
        // {
        //   Name: '任务展示方式', // 任务展示方式
        //   NewVal: this.$fd('IsReadingTaskViewInOrder', this.form.IsReadingTaskViewInOrder),
        //   OldVal: this.$fd('IsReadingTaskViewInOrder', this.initialForm.IsReadingTaskViewInOrder)
        // },
        // {
        //   Name: this.$t('trials:processCfg:form:global'), // 全局阅片
        //   NewVal: this.$fd('YesOrNo', this.form.IsGlobalReading),
        //   OldVal: this.$fd('YesOrNo', this.initialForm.IsGlobalReading)
        // },
        // {
        //   Name: this.$t('trials:processCfg:form:ad'), // 仲裁阅片
        //   NewVal: this.$fd('YesOrNo', this.form.IsArbitrationReading),
        //   OldVal: this.$fd('YesOrNo', this.initialForm.IsArbitrationReading)
        // },
        // {
        //   Name: this.$t('trials:processCfg:form:clinical'), // 临床阅片
        //   NewVal: this.$fd('YesOrNo', this.form.IsClinicalReading),
        //   OldVal: this.$fd('YesOrNo', this.initialForm.IsClinicalReading)
        // }
        // {
        //   Name: this.$t('trials:processCfg:form:adRules'), // 仲裁规则
        //   NewVal: this.$fd('ArbitrationRule', this.form.ArbitrationRule),
        //   OldVal: this.$fd('ArbitrationRule', this.initialForm.ArbitrationRule)
        // }
      ]
    },

    // 阅片模式change事件
    handleReadingTypeChange(val) {
      // 单重阅片时，仲裁阅片为否且不允许编辑，双重阅片时，仲裁阅片则为是且不允许编辑，定制时，不设默认值
      if (val === 1) {
        // 单重阅片
        this.form.IsArbitrationReading = false
        this.form.ArbitrationRule = 3
      } else if (val === 2) {
        // 双重阅片
        this.form.IsArbitrationReading = true
      } else {
        this.form.IsArbitrationReading = false
      }
    },

    // 初始化表单
    async initForm(res) {
      this.loading = true
      for (const k in this.form) {
        if (res.hasOwnProperty(k)) {
          this.form[k] = res[k]
        }
      }
      this.form.TrialCriterionNamesStr =
        this.form.TrialCriterionNames.join(', ')
      this.form.ClinicalDataSetNamesStr =
        this.form.ClinicalDataSetNames.join(', ')
      this.initialForm = { ...this.form }
      this.TrialStatusStr = res.TrialStatusStr
      this.getCriterionList()
      if (!this.form.IsTrialProcessConfirmed) {
        this.isEdit = true
      }
      this.loading = false
    },

    // 获取临床数据模板信息
    getClinicalDataList(isSelect = false) {
      return new Promise((resolve, reject) => {
        this.listLoading = true
        getTrialClinicalDataTrialSetList({
          trialId: this.form.TrialId,
          criterionIds: this.form.TrialCriterionIds,
        })
          .then((res) => {
            this.clinicalDataList = res.Result
            this.listLoading = false
            if (isSelect) {
              this.$nextTick(() => {
                for (
                  let i = 0;
                  i < this.form.ClinicalDataTrialSetIds.length;
                  i++
                ) {
                  var index = this.clinicalDataList.findIndex(
                    (item) => item.Id === this.form.ClinicalDataTrialSetIds[i]
                  )

                  if (index > -1) {
                    this.$refs['clinicalData'].toggleRowSelection(
                      this.clinicalDataList[index],
                      true
                    )
                  }
                }
              })
            }
            resolve()
          })
          .catch(() => {
            this.listLoading = false
            reject()
          })
      })
    },
    // 获取勾选行数据
    handleCDSelectChange(val) {
      const arr = []
      this.selectedCD = []
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index].Id)
        this.selectedCD.push(
          this.$i18n.locale === 'zh'
            ? val[index].ClinicalDataSetName
            : val[index].ClinicalDataSetEnName
        )
      }
      this.selectClinicalDataArr = arr
    },
    async handleConfirmClinicalData() {
      // 验证临床数据配置
      try {
        let params = {
          trialId: this.form.TrialId,
          trialCriterionIds: this.form.TrialCriterionIds,
          clinicalDataTrialSetIds: this.selectClinicalDataArr,
        }
        await configTrialProcessInfoVerification(params)

        this.form.ClinicalDataSetNames = this.selectedCD
        this.form.ClinicalDataTrialSetIds = this.selectClinicalDataArr
        this.form.ClinicalDataSetNamesStr =
          this.form.ClinicalDataSetNames.join(', ')
        this.clinicalDataVisible = false
      } catch (e) {
        console.log(e)
      }
    },
    async handleSetCD() {
      this.clinicalDataVisible = true
      await this.getClinicalDataList()

      this.$nextTick(() => {
        for (let i = 0; i < this.form.ClinicalDataTrialSetIds.length; i++) {
          var index = this.clinicalDataList.findIndex(
            (item) => item.Id === this.form.ClinicalDataTrialSetIds[i]
          )
          if (index > -1) {
            this.$refs['clinicalData'].toggleRowSelection(
              this.clinicalDataList[index],
              true
            )
          }
        }
      })
    },
    handleAddClinicalData() {
      this.currentRow = {}
      this.addOrEditCD.title = this.$t('common:button:new') // 新增
      this.addOrEditCD.visible = true
    },
    handleEditClinicalData(row) {
      this.currentRow = { ...row }
      this.addOrEditCD.title = this.$t('common:button:edit') // '编辑'
      this.addOrEditCD.visible = true
    },
    handleDeleteClinicalData(row) {
      this.$confirm(this.$t('trials:staffResearch:message:confirmDel'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        this.loading = true
        deleteClinicalTrialSetData(row.Id)
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              var cdNameIndex = this.selectedCD.indexOf(row.ClinicalDataSetName)
              if (cdNameIndex > -1) {
                this.selectedCD.splice(cdNameIndex, 1)
              }
              var cdIdIndex = this.selectClinicalDataArr.indexOf(row.Id)
              if (cdIdIndex > -1) {
                this.selectClinicalDataArr.splice(cdIdIndex, 1)
              }
              var index = this.form.ClinicalDataTrialSetIds.indexOf(row.Id)
              if (index > -1) {
                this.form.ClinicalDataTrialSetIds.splice(index, 1)
              }
              var i = this.form.ClinicalDataSetNames.indexOf(
                row.ClinicalDataSetName
              )
              if (i > -1) {
                this.form.ClinicalDataSetNames.splice(i, 1)
                this.form.ClinicalDataSetNamesStr =
                  this.form.ClinicalDataSetNames.join(', ')
              }
              this.getClinicalDataList(true)
              // '删除成功!'
              this.$message.success(
                this.$t('common:message:deletedSuccessfully')
              )
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    handleDownloadTpl(row) {
      window.open(this.OSSclientConfig.basePath + row.Path)
      // this.listLoading = true
      // DownloadTrialClinicalFile(row.Id).then(data => {
      //   this.listLoading = false
      // }).catch(() => { this.listLoading = false })
    },
    handleSelectable(row) {
      if (!row.IsApply) {
        return false
      }
      if (this.isEdit) {
        return true
      } else {
        return false
      }
    },
    getCriterionList(isSelect = false) {
      this.listLoading = true
      this.criterionSearchForm.TrialId = this.form.TrialId
      getReadingQuestionCriterionTrialList(this.criterionSearchForm)
        .then((res) => {
          this.criterionList = res.Result.CurrentPageData
          this.criterionListTotal = res.Result.TotalCount
          this.listLoading = false
          if (isSelect) {
            this.$nextTick(() => {
              for (let i = 0; i < this.form.TrialCriterionIds.length; i++) {
                var index = this.criterionList.findIndex(
                  (item) => item.Id === this.form.TrialCriterionIds[i]
                )
                if (index > -1) {
                  this.$refs['criterionList'].toggleRowSelection(
                    this.criterionList[index],
                    true
                  )
                }
              }
            })
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handleResetCriterion() {
      this.criterionSearchForm = criterionSearchDataDefault()
      this.getCriterionList()
    },
    handleSearchCriterion() {
      this.getCriterionList()
    },
    handleSetCriterion() {
      this.criterionListVisible = true
      this.selectedCriterions = []
      this.selectCriterionIds = []
      this.$nextTick(() => {
        for (let i = 0; i < this.form.TrialCriterionIds.length; i++) {
          var index = this.criterionList.findIndex(
            (item) => item.Id === this.form.TrialCriterionIds[i]
          )
          if (index > -1) {
            this.$refs['criterionList'].toggleRowSelection(
              this.criterionList[index],
              true
            )
            this.selectedCriterions.push(
              this.criterionList[index].CriterionName
            )
            this.selectCriterionIds.push(this.criterionList[index].Id)
          }
        }
      })
    },
    // 获取勾选行数据
    selectCriterion(selection, row) {
      // this.selectCriterionIds = selection.length > 0 ? [row.Id] : []
      // this.selectedCriterions = selection.length > 0 ? [row.CriterionName] : []
      console.log(selection)
      var a = Object.assign(
        [],
        selection.sort((a, b) => {
          return a.ShowOrder - b.ShowOrder
        })
      )
      this.selectedCriterions = a.map((v) => v.CriterionName)
      this.selectCriterionIds = a.map((v) => v.Id)
      // 清除 所有勾选项
      // this.$refs.criterionList.clearSelection()
      // 当表格数据都没有被勾选的时候 就返回
      // 主要用于将当前勾选的表格状态清除
      // if (selection.length === 0) return
      // this.$refs.criterionList.toggleRowSelection(row, true)
    },

    handleAddCriterion() {
      this.criterionForm.Id = ''
      this.criterionForm.CriterionName = ''
      this.criterionFormDg.title = this.$t('common:button:new') // 新增
      this.criterionFormDg.visible = true
    },
    handleEditCriterion(row) {
      for (const k in this.criterionForm) {
        if (row.hasOwnProperty(k)) {
          this.criterionForm[k] = row[k]
        }
      }
      this.criterionFormDg.title = this.$t('common:button:edit') // '编辑'
      this.criterionFormDg.visible = true
    },
    handleConfigCriterion(row) {
      this.currentCriterionRow = { ...row }
      this.criterionQSVisible = true
    },
    handleDeleteCriterion(row) {
      // '是否确认删除？'
      this.$confirm(this.$t('trials:processCfg:message:delete'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        this.listLoading = true
        deleteReadingQuestionCriterionTrial(row.Id)
          .then((res) => {
            this.listLoading = false
            if (res.IsSuccess) {
              var cNameIndex = this.selectedCriterions.indexOf(
                row.CriterionName
              )
              if (cNameIndex > -1) {
                this.selectedCriterions.splice(cNameIndex, 1)
              }
              var cIdIndex = this.selectCriterionIds.indexOf(row.Id)
              if (cIdIndex > -1) {
                this.selectCriterionIds.splice(cIdIndex, 1)
              }
              var index = this.form.TrialCriterionIds.indexOf(row.Id)
              if (index > -1) {
                this.form.TrialCriterionIds.splice(index, 1)
              }
              var i = this.form.TrialCriterionNames.indexOf(row.CriterionName)
              if (i > -1) {
                this.form.TrialCriterionNames.splice(i, 1)
                this.form.TrialCriterionNamesStr =
                  this.form.TrialCriterionNames.join(', ')
              }
              this.getCriterionList(true)
              // '删除成功！'
              this.$message.success(
                this.$t('common:message:deletedSuccessfully')
              )
            }
          })
          .catch(() => {
            this.listLoading = false
          })
      })
    },
    handleCancelSave() {
      this.$refs['criterionForm'].resetFields()
      this.criterionFormDg.visible = false
    },
    handleSaveCriterion() {
      this.$refs['criterionForm'].validate((valid) => {
        if (!valid) return
        this.listLoading = true
        this.criterionForm.TrialId = this.form.TrialId
        addOrUpdateReadingQuestionCriterionTrial(this.criterionForm)
          .then((res) => {
            this.listLoading = false
            // 保存成功
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.criterionFormDg.visible = false
            this.getCriterionList()
          })
          .catch(() => {
            this.listLoading = false
          })
      })
    },
    handleConfirmCriterion() {
      if (
        this.selectedCriterions.join(', ') !== this.form.TrialCriterionNamesStr
      ) {
        // 清空临床数据配置信息
        this.form.ClinicalDataSetNames = []
        this.form.ClinicalDataTrialSetIds = []
        this.form.ClinicalDataSetNamesStr = ''
      }
      this.form.TrialCriterionNames = this.selectedCriterions
      this.form.TrialCriterionIds = this.selectCriterionIds
      this.form.TrialCriterionNamesStr =
        this.form.TrialCriterionNames.join(', ')
      this.criterionListVisible = false
    },

    changeCriterionStatus(callback, row) {
      var message = ''
      if (callback) {
        message = this.$t('trials:processCfg:message:update') // '是否确认更改？'
        row.IsCompleteConfig = false
      } else {
        message = this.$t('trials:processCfg:message:update') // '是否确认更改？'
        row.IsCompleteConfig = true
      }
      this.$confirm(message, {
        distinguishCancelAndClose: true,
        type: 'warning',
      })
        .then(() => {
          this.listLoading = true
          var params = {
            id: row.Id,
            isCompleteConfig: !row.IsCompleteConfig,
          }
          setTrialReadingQuestionCriterionIsIsCompleteConfig(params)
            .then((res) => {
              this.listLoading = false
              if (res.IsSuccess) {
                this.$message.success(
                  this.$t('common:message:savedSuccessfully')
                ) // '保存成功！'
                this.getCriterionList()
              }
            })
            .catch(() => {
              this.listLoading = false
            })
        })
        .catch(() => {})
    },
    handleIsReadingTaskViewInOrderChange(val) {
      if (val === false) {
        // 无序
        this.form.IsGlobalReading = false
        this.form.IsClinicalReading = false
      }
    },
  },
}
</script>
<style lang="scss">
.process-config-form {
  .fontColor {
    color: red;
  }
  .criterion-table {
    thead {
      .el-table-column--selection {
        .cell {
          display: none;
        }
      }
    }
  }
}
</style>
