<template>
  <div class="logincal-config-form">
    <!-- 配置信息表单 -->
    <el-form ref="logicalConfigForm" v-loading="loading" :model="form" label-width="280px" style="width: 800px"
      :rules="rules" size="small">
      <!-- 筛选号规则提醒 -->
      <el-form-item :label="$t('trials:logincCfg:form:subjectNumberRule')" prop="IsNoticeSubjectCodeRule">
        <el-radio-group v-model="form.IsNoticeSubjectCodeRule" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit"
          @change="subjectCodeRuleChange">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsNoticeSubjectCodeRule${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 筛选号格式 -->
      <el-form-item v-if="form.IsNoticeSubjectCodeRule" :label="$t('trials:logincCfg:form:subjectNumFormat')"
        prop="SubjectCodeRule">
        <el-input v-model="form.SubjectCodeRule" style="min-height: 90px"
          :disabled="form.IsTrialBasicLogicConfirmed && !isEdit" type="textarea" :autosize="{ minRows: 4, maxRows: 6 }"
          maxlength="250" show-word-limit />
      </el-form-item>
      <!-- 受试者第二编号 -->
      <el-form-item :label="$t('trials:logincCfg:form:subjectNum2')" prop="IsSubjectSecondCodeView" v-if="showMore">
        <el-radio-group v-model="form.IsSubjectSecondCodeView" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsSubjectSecondCodeView${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 扫描日期校验 -->
      <el-form-item :label="$t('trials:logincCfg:form:scanDateVerify')" prop="IsVerifyVisitImageDate">
        <el-radio-group v-model="form.IsVerifyVisitImageDate" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsVerifyVisitImageDate${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 访视基准日期 -->
      <el-form-item :label="$t('trials:logincCfg:form:visitBaseDate')" prop="IsHaveFirstGiveMedicineDate">
        <el-radio-group v-model="form.IsHaveFirstGiveMedicineDate"
          :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsHaveFirstGiveMedicineDate${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 受试者年龄 -->
      <el-form-item :label="$t('trials:logincCfg:form:subjectAge')" prop="IsHaveSubjectAge" v-if="showMore">
        <el-radio-group v-model="form.IsHaveSubjectAge" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsHaveSubjectAge${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 受试者性别 -->
      <el-form-item :label="$t('trials:logincCfg:form:subjectGender')" prop="IsSubjectSexView" v-if="showMore">
        <el-radio-group v-model="form.IsSubjectSexView" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsSubjectSexView${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 计划外的末次访视名称 -->
      <el-form-item :label="$t('trials:logincCfg:form:lastVisitName')" prop="OutEnrollmentVisitName">
        <el-input v-model="form.OutEnrollmentVisitName" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit"
          maxlength="250" show-word-limit />
      </el-form-item>

      <!-- 影像跨项目复制 -->
      <el-form-item :label="$t('trials:logincCfg:form:imageCopy')" prop="IsImageReplicationAcrossTrial" v-if="showMore">
        <el-radio-group v-model="form.IsImageReplicationAcrossTrial"
          :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsImageReplicationAcrossTrial${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 检查部位 -->
      <el-form-item :label="$t('trials:logincCfg:form:bodypart')" prop="BodyPartTypes">
        <el-input v-model="form.BodyPartTypes" type="textarea" :autosize="{ minRows: 2, maxRows: 8 }" style="width: 80%"
          disabled />
        <el-button :disabled="form.IsTrialBasicLogicConfirmed && !isEdit" icon="el-icon-plus" circle
          @click="handleSetBodyPart" />
      </el-form-item>
      <el-form-item :label="$t('trials:logincCfg:form:modality')" prop="ModalityListStr">
        <el-input v-model="form.ModalityListStr" type="textarea" :autosize="{ minRows: 1, maxRows: 3 }"
          style="width: 80%" disabled />
        <el-button :disabled="form.IsTrialBasicLogicConfirmed && !isEdit" icon="el-icon-plus" circle
          @click="handleSetModality" />
      </el-form-item>
      <!--展示检查名称-->
      <el-form-item :label="$t('trials:logincCfg:form:IsShowStudyName ')" prop="IsShowStudyName" v-if="showMore">
        <el-radio-group v-model="form.IsShowStudyName" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit"
          @input="IsShowStudyNameChange">
          <el-radio :label="item.value" v-for="item in $d.YesOrNo" :key="item.id">{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 检查名称 -->
      <el-form-item :label="$t('trials:logincCfg:form:StudyNameList')" prop="StudyNameTypes"
        v-if="form.IsShowStudyName && showMore">
        <el-input v-model="form.StudyNameTypes" type="textarea" :autosize="{ minRows: 2, maxRows: 8 }"
          style="width: 80%" disabled />
        <el-button :disabled="form.IsTrialBasicLogicConfirmed && !isEdit" icon="el-icon-plus" circle
          @click="handleSetStudyName" />
      </el-form-item>
      <!-- 影像质疑超限天数 -->
      <el-form-item :label="$t('trials:logincCfg:form:exceededDays')" prop="ChangeDefalutDays">
        <el-input-number v-model="form.ChangeDefalutDays" controls-position="right" :min="0"
          :disabled="form.IsTrialBasicLogicConfirmed && !isEdit" />
      </el-form-item>
      <!-- 自动跳转下一个任务 -->
      <el-form-item :label="$t('trials:logincCfg:form:IsIQCAutoNextTask')" prop="IsIQCAutoNextTask" v-if="showMore">
        <el-radio-group v-model="form.IsIQCAutoNextTask" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit"
          @input="handleIsIQCAutoNextTaskChange">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsIQCAutoNextTask${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 自动任务是否区分类型 -->
      <el-form-item :label="$t('trials:logincCfg:form:IsIQCAutoTaskDistinguishType')"
        prop="IsIQCAutoTaskDistinguishType" v-if="form.IsIQCAutoNextTask && showMore">
        <el-radio-group v-model="form.IsIQCAutoTaskDistinguishType"
          :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsIQCAutoTaskDistinguishType${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- QC质控下载 -->
      <el-form-item :label="$t('trials:logincCfg:form:IsSupportQCDownloadImage')" prop="IsSupportQCDownloadImage"
        v-if="showMore">
        <el-radio-group v-model="form.IsSupportQCDownloadImage" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsSupportQCDownloadImage${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!--影像质控风险控制-->
      <el-form-item :label="$t('trials:processCfg:form:IsImageQualityControl')" prop="IsImageQualityControl">
        <el-radio-group v-model="form.IsImageQualityControl" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <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:logincCfg:form:IsOpenLostVistRead')" prop="IsOpenLostVistRead " v-if="showMore">
        <el-radio-group v-model="form.IsOpenLostVistRead" :disabled="form.IsTrialBasicLogicConfirmed && !isEdit">
          <el-radio v-for="item of $d.YesOrNo" :key="`IsOpenLostVistRead ${item.value}`" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <div :class="{ showMore: true, isCheck: showMore }" @click.stop="showMore = !showMore">
          <i class="el-icon-arrow-down"></i>
          <span>{{
            showMore
              ? $t('trials:logincCfg:button:packUp')
              : $t('trials:logincCfg:button:more')
          }}</span>
        </div>
      </el-form-item>
      <el-form-item>
        <!-- 保存 -->
        <el-button v-if="
          form.IsTrialBasicLogicConfirmed === false &&
          hasPermi(['trials:trials-panel:setting:trial-config:save'])
        " type="primary" @click="handleSave">
          {{ $t('common:button:save') }}
        </el-button>
        <!-- 配置确认 -->
        <el-button v-if="
          form.IsTrialBasicLogicConfirmed === 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.IsTrialBasicLogicConfirmed === true &&
          !isEdit &&
          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.IsTrialBasicLogicConfirmed === 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.IsTrialBasicLogicConfirmed === true &&
          isEdit &&
          hasPermi(['trials:trials-panel:setting:trial-config:save'])
        " type="primary" @click="confirmCancel">
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button @click="openTerminology" v-if="
          (form.IsTrialBasicLogicConfirmed === false ||
            (form.IsTrialBasicLogicConfirmed === true && isEdit)) &&
          hasPermi(['trials:trials-panel:setting:trial-config:save']) &&
          showMore
        ">
          {{ $t('common:button:terminology') }}
        </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="clinicalDataVisible" :visible.sync="clinicalDataVisible" :close-on-click-modal="false"
      title="临床数据配置" width="1200px" custom-class="base-dialog-wrapper">
      <div v-loading="listLoading" class="base-dialog-body">
        <div style="text-align: right">
          <el-button 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"
          @selection-change="handleSelectChange">
          <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="临床数据名称" width="180" />
          <el-table-column prop="UploadRole" :label="$t('trials:studyList:table:uploader')" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ $fd('ClinicalDataUploadRole', scope.row.UploadRole) }}
            </template>
          </el-table-column>
          <el-table-column prop="ClinicalDataLevel" label="数据级别" width="180">
            <template slot-scope="scope">
              {{ $fd('ClinicalLevel', scope.row.ClinicalDataLevel) }}
            </template>
          </el-table-column>
          <el-table-column prop="ClinicalUploadType" label="传输方式">
            <template slot-scope="scope">
              {{ $fd('ClinicalUploadType', scope.row.ClinicalUploadType) }}
            </template>
          </el-table-column>
          <el-table-column prop="FileName" label="模板名称" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.FileName }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="250" fixed="right">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" :disabled="!scope.row.FileName"
                @click="handleDownloadTpl(scope.row)">
                下载
              </el-button>
              <el-button type="primary" size="mini" :disabled="scope.row.IsUsed"
                @click="handleEditClinicalData(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" size="mini" :disabled="scope.row.IsUsed ||
                form.ClinicalDataSetNames.indexOf(
                  scope.row.ClinicalDataSetName
                ) > -1
                " @click="handleDeleteClinicalData(scope.row)">
                删除
              </el-button>
            </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" :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="bodyPartListVisible" :visible.sync="bodyPartListVisible" :close-on-click-modal="false"
      :title="$t('trials:logincCfg:form:bodypart')" custom-class="base-dialog-wrapper" width="400px">
      <div class="base-dialog-body" style="position: relative">
        <el-button size="small" type="primary" @click="addBodyPart_model.visible = true"
          style="position: absolute; top: 10px; right: 10px; z-index: 9">
          {{ $t('common:button:add') }}
        </el-button>
        <el-table ref="bodyPartTable" v-loading="listLoading" :data="trialBodyPartList" stripe height="400"
          row-key="Code" @selection-change="handleBodyPartSelectionChange">
          <el-table-column type="selection" align="left" width="45" :reserve-selection="true"
            :selectable="selectableBodyPart" />
          <el-table-column prop="Name" :label="$t('trials:logincCfg:form:bodypart')">
            <template slot-scope="scope">
              <div class="bodyPartName">
                <span :title="scope.row.Name">{{ scope.row.Name }}</span>
                <el-button v-if="scope.row.IsHandAdd" circle icon="el-icon-edit-outline"
                  :title="$t('trials:logincCfg:form:bodypart:edit')" :disabled="scope.row.IsStudyUse"
                  @click.stop="handleEditBodyPart(scope.row)" />
              </div>
            </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" :disabled="listLoading" @click="bodyPartListVisible = false">
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button size="small" type="primary" :disabled="listLoading" @click="handleConfirmBodyParts">
          {{ $t('common:button:confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <!--选择检查技术-->
    <el-dialog v-if="modalityListVisible" :visible.sync="modalityListVisible" :close-on-click-modal="false"
      :title="$t('trials:logincCfg:form:modality')" custom-class="base-dialog-wrapper" width="400px">
      <div class="base-dialog-body">
        <!-- <el-transfer
          filterable
          :filter-method="filterMethod"
          filter-placeholder=""
          v-model="selectedList"
          :data="$d.Modality"
          :titles="[
            $t('trials:logincCfg:transfer:notCheck'),
            $t('trials:logincCfg:transfer:check'),
          ]"
          :props="{
            key: 'value',
            label: 'value',
          }"
          :render-content="renderFunc"
        >
        </el-transfer> -->
        <el-table ref="multipleTable" :data="$d.Modality" stripe height="450" row-key="id" class="criterion-table"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="left" width="45" :reserve-selection="true"
            :selectable="selectableModality" />
          <el-table-column prop="value" :label="$t('trials:logincCfg:form:modality')" />
        </el-table>
      </div>
      <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
        <el-button size="small" type="primary" :disabled="listLoading" @click="modalityListVisible = false">
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button size="small" type="primary" :disabled="listLoading" @click="handleConfirmModality">
          {{ $t('common:button:confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <!--新增检查部位-->
    <base-model v-if="addBodyPart_model.visible" :config="addBodyPart_model">
      <template slot="dialog-body">
        <el-form ref="addBodyPartForm" :inline="true" :model="addBodyPartForm" class="demo-form-inline"
          :rules="addBodyPartrules">
          <el-form-item :label="$t('trials:setting:form:bodyPart')" prop="bodyPartStr" label-width="150px">
            <el-input v-model.trim="addBodyPartForm.bodyPartStr" clearable type="textarea" :rows="2"
              @focus="errMessage = null"></el-input>
            <span class="errTip" v-if="errMessage">{{ errMessage }}</span>
          </el-form-item>
          <el-form-item :label="$t('trials:setting:form:bodyPart')" style="display: none" prop="bodyPartStr"
            label-width="150px">
            <el-input clearable :maxlength="50"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template slot="dialog-footer">
        <el-button type="primary" @click="addOrUpdateTrialBodyPart">
          {{ $t('common:button:confirm') }}
        </el-button>
        <el-button @click="
            ; (addBodyPart_model.visible = false),
          (addBodyPartForm.bodyPartStr = null)
          ">
          {{ $t('common:button:cancel') }}
        </el-button>
      </template>
    </base-model>
    <!---术语配置--->
    <terminology :visible.sync="terminologyVisible" :DATA.sync="form.TrialObjectNameList" />
    <el-dialog v-if="studyNameListVisible" :visible.sync="studyNameListVisible" :close-on-click-modal="false"
      :title="$t('trials:logincCfg:form:studyName')" custom-class="base-dialog-wrapper" width="400px">
      <div class="base-dialog-body" style="position: relative">
        <el-button size="small" type="primary" @click="addStudyName_model.visible = true"
          style="position: absolute; top: 10px; right: 10px; z-index: 9">
          {{ $t('common:button:add') }}
        </el-button>
        <el-table ref="studyNameTable" v-loading="listLoading" :data="trialStudyNameList" stripe height="400"
          row-key="Name" @selection-change="handleStudyNameSelectionChange">
          <el-table-column type="selection" align="left" width="45" :reserve-selection="true"
            :selectable="selectableStudyName" />
          <el-table-column prop="Name" :label="$t('trials:logincCfg:form:studyName')">
            <template slot-scope="scope">
              <div class="bodyPartName">
                <span :title="isEN ? scope.row.EnName : scope.row.Name">{{
                  isEN ? scope.row.EnName : scope.row.Name
                }}</span>
                <el-button circle icon="el-icon-delete" :title="$t('trials:logincCfg:form:StudyName:del')"
                  :disabled="form.StudyUseStudyNameList.includes(scope.row.Name) || form.StudyUseStudyNameList.includes(scope.row.EnName)"
                  @click.stop="handleDelStudyName(scope.row)" />
              </div>
            </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" :disabled="listLoading" @click="studyNameListVisible = false">
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button size="small" type="primary" :disabled="listLoading" @click="handleConfirmStudyName">
          {{ $t('common:button:confirm') }}
        </el-button>
      </div>
    </el-dialog>
    <!--新增检查名称-->
    <base-model v-if="addStudyName_model.visible" :config="addStudyName_model">
      <template slot="dialog-body">
        <el-form ref="addStudyNameForm" :inline="true" :model="addStudyNameForm" class="demo-form-inline"
          :rules="addStudyNamerules">
          <el-form-item :label="$t('trials:setting:form:studyName')" prop="Name" label-width="150px">
            <el-input v-model.trim="addStudyNameForm.Name" clearable type="textarea" :rows="2"></el-input>
          </el-form-item>
          <el-form-item :label="$t('trials:setting:form:bodyPart')" style="display: none" prop="bodyPartStr"
            label-width="150px">
            <el-input clearable :maxlength="50"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template slot="dialog-footer">
        <el-button type="primary" @click="addOrUpdateTrialStudyName" :loading="studyNameLoading">
          {{ $t('common:button:confirm') }}
        </el-button>
        <el-button @click="
            ; (addStudyName_model.visible = false),
          (addStudyNameForm.Name = null)
          ">
          {{ $t('common:button:cancel') }}
        </el-button>
      </template>
    </base-model>
  </div>
</template>
<script>
import {
  configTrialBasicInfo,
  getTrialClinicalDataTrialSetList,
  deleteClinicalTrialSetData,
  DownloadTrialClinicalFile,
} from '@/api/trials'
import {
  ConfigTrialBasicInfoConfirm,
  getTrialBodyPartList,
  addOrUpdateTrialBodyPart,
  updateTrialStudyNameList,
} from '@/api/trials/setting'
import SignForm from '@/views/trials/components/newSignForm'
import ClinicalDataForm from './clinicalDataForm'
import terminology from './terminology'
import const_ from '@/const/sign-code'
import BaseModel from '@/components/BaseModel'
export default {
  name: 'LogicalConfig',
  components: { SignForm, ClinicalDataForm, BaseModel, terminology },
  data() {
    return {
      showMore: false,
      form: {
        TrialId: '',
        IsNoticeSubjectCodeRule: false,
        SubjectCodeRule: '',
        IsSubjectSecondCodeView: false,
        IsVerifyVisitImageDate: false,
        IsHaveFirstGiveMedicineDate: true,
        IsHaveSubjectAge: false,
        IsSubjectSexView: false,
        OutEnrollmentVisitName: 'EOT',
        // ClinicalInformationTransmissionEnum: 1,
        IsImageReplicationAcrossTrial: false,
        BodyPartTypes: '',
        StudyNameTypes: '',
        IsShowStudyName: null,
        StudyNameList: [],
        BodyPartTypeList: [],
        Modalitys: '',
        ModalityList: [],
        ModalityListStr: '',
        ChangeDefalutDays: 5,
        IsTrialBasicLogicConfirmed: false,
        TrialObjectNameList: [],
        TrialObjectNameConfigStr: '',
        StudyUseModalityList: [],
        StudyUseStudyNameList: [],
        IsIQCAutoNextTask: false,
        IsSupportQCDownloadImage: false,
        IsImageQualityControl: false,
        IsOpenLostVistRead: false,
        IsIQCAutoTaskDistinguishType: false
        // ClinicalDataSetNames: [],
        // ClinicalDataTrialSetIds: [],
        // ClinicalDataSetNamesStr: ''
      },
      rules: {
        IsNoticeSubjectCodeRule: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: 'blur',
          },
        ],
        SubjectCodeRule: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
          {
            max: 250,
            message: `${this.$t('common:ruleMessage:maxLength')} 250`,
          },
        ],
        IsSubjectSecondCodeView: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: 'blur',
          },
        ],
        IsVerifyVisitImageDate: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: 'blur',
          },
        ],
        IsHaveFirstGiveMedicineDate: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: 'blur',
          },
        ],
        OutEnrollmentVisitName: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
          {
            max: 250,
            message: `${this.$t('common:ruleMessage:maxLength')} 50`,
          },
        ],
        BodyPartTypes: [
          {
            required: true,
            message: this.$t('trials:trialCfg:formRule:bodyPart'),
            trigger: 'blur',
          },
        ],
        StudyNameTypes: [
          {
            required: true,
            message: this.$t('trials:trialCfg:formRule:bodyPart'),
            trigger: 'blur',
          },
        ],
        // Modalitys: [
        //   { required: true, message: this.$t('trials:trialCfg:formRule:modality'), trigger: 'blur' },
        //   { max: 500, message: `${this.$t('common:ruleMessage:maxLength')} 500` }
        // ],
        ModalityListStr: [
          {
            required: true,
            message: this.$t('trials:trialCfg:formRule:modality'),
            trigger: 'blur',
          },
        ],
        // ClinicalDataSetNamesStr: [
        //   { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' }
        // ],
        // ClinicalInformationTransmissionEnum: [
        //   { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        // ]
      },
      terminologyVisible: false,
      confirmVisible: false,
      updateVisible: false,
      signVisible: false,
      btnLoading: false,
      confirmData: [],
      loading: false,
      signText: '',
      signCode: '',
      currentUser: zzSessionStorage.getItem('userName'),
      initialForm: {},
      isEdit: false,
      clinicalDataList: [],
      clinicalDataVisible: false,
      addOrEditCD: { visible: false, title: '' },
      currentRow: {},
      selectClinicalDataArr: [],
      selectedCD: [],
      listLoading: false,
      modalityListVisible: false,
      bodyPartListVisible: false,
      studyNameListVisible: false,
      selectedList: [],
      selectedBodyParts: [],
      trialBodyPartList: [],
      trialStudyNameList: [],
      addBodyPart_model: {
        visible: false,
        title: this.$t('trials:setting:button:add'),
        width: '500px',
        appendToBody: true,
      },
      addStudyName_model: {
        visible: false,
        title: this.$t('trials:setting:button:add'),
        width: '500px',
        appendToBody: true,
      },
      studyNameLoading: false,
      addBodyPartForm: {
        bodyPartStr: null,
        Id: null,
      },
      addStudyNameForm: {
        Name: null,
        EnName: null,
        IeChoose: false,
      },
      addBodyPartrules: {
        bodyPartStr: [
          {
            required: true,
            message: this.$t('trials:setting:format:notBodyPart'),
            trigger: ['blur', 'change'],
          },
          {
            validator: (rule, value, callback) => {
              let flag = this.trialBodyPartList.some(
                (item) => item.Name === value
              )
              if (flag) {
                callback(
                  new Error(this.$t('trials:setting:format:hasBodyPart'))
                )
              } else {
                callback()
              }
            },
            message: this.$t('trials:setting:format:hasBodyPart'),
            trigger: ['blur', 'change'],
          },
        ],
      },
      addStudyNamerules: {
        Name: [
          {
            required: true,
            message: this.$t('trials:setting:format:notStudyName'),
            trigger: ['blur', 'change'],
          },
          {
            validator: (rule, value, callback) => {
              let flag = this.trialStudyNameList.some(
                (item) => item.Name === value
              )
              if (flag) {
                callback(
                  new Error(this.$t('trials:setting:format:hasStudyName'))
                )
              } else {
                callback()
              }
            },
            message: this.$t('trials:setting:format:hasStudyName'),
            trigger: ['blur', 'change'],
          },
        ],
      },
      errMessage: null,

      renderFunc(h, option) {
        return (
          <span title={`${option.label} - ${option.raw.Description}`}>
            {option.label} <span style="color:#ddd">-</span>{' '}
            <span style="color:#999">{option.raw.Description}</span>
          </span>
        )
      },
    }
  },
  // created() {
  //   this.getTrialBodyPartList();
  // },
  computed: {
    isEN() {
      return this.$i18n.locale !== 'zh'
    },
  },
  methods: {
    handleIsIQCAutoNextTaskChange(val) {
      if (!val) this.form.IsIQCAutoTaskDistinguishType = false
    },
    selectableStudyName(row) {
      let select = this.trialStudyNameList.filter((item) => item.IsChoose)
      return (!this.form.StudyUseStudyNameList.includes(row.Name) && !this.form.StudyUseStudyNameList.includes(row.EnName)) || (!select.includes(row) && (this.form.StudyUseStudyNameList.includes(row.EnName) || this.form.StudyUseStudyNameList.includes(row.Name)))
    },
    selectableModality(row) {
      var a = this.$d.Modality.filter((v) => {
        return !!this.form.ModalityList.find((v1) => {
          return v1 === v.value
        })
      })
      return !this.form.StudyUseModalityList.includes(row.value) || (!a.includes(row) && this.form.StudyUseModalityList.includes(row.value))
    },
    selectableBodyPart(row) {
      return !row.IsStudyUse
    },
    openTerminology() {
      this.terminologyVisible = true
    },
    // 取消配置更新
    confirmCancel() {
      this.isEdit = false
      this.form = { ...this.initialForm }
    },
    handleConfirmModality() {
      this.form.ModalityList = Object.assign(
        [],
        // this.selectedList.map((v) => v)
        this.selectedList.map((v) => v.value)
      )
      let Modalitys = this.form.ModalityList.map((item) => {
        return this.$fd('Modality', item.trim())
      })
      this.form.ModalityListStr = Modalitys.toString().replaceAll(',', ' | ')
      this.modalityListVisible = false
    },
    handleSelectionChange(val) {
      this.selectedList = val
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    filterMethod(query, item) {
      return item.value.toLowerCase().indexOf(query.toLowerCase()) > -1
    },
    handleSetModality() {
      this.modalityListVisible = true
      this.$nextTick(() => {
        var a = this.$d.Modality.filter((v) => {
          return !!this.form.ModalityList.find((v1) => {
            return v1 === v.value
          })
        })
        this.toggleSelection(a)
      })
      // var a = this.$d.Modality.filter((v) => {
      //   return !!this.form.ModalityList.find((v1) => {
      //     return v1 === v.value
      //   })
      // })
      // this.selectedList = a.map((item) => item.value)
    },
    handleBodyPartSelectionChange(val) {
      this.selectedBodyParts = val
    },
    IsShowStudyNameChange(val) {
      // if (!val) {
      //   if (this.form.StudyNameList && this.form.StudyNameList.length > 0) {
      //     this.form.StudyNameList.forEach((item) => {
      //       item.IsChoose = false
      //     })
      //   } else {
      //     this.form.StudyNameList = []
      //   }
      //   thiss.form.StudyNameTypes = null
      // }
    },
    handleStudyNameSelectionChange(val) {
      let data = []
      if (val) {
        data = val.map((item) => item.Name)
      }
      this.trialStudyNameList.forEach((item) => {
        item.IsChoose = false
        if (data.includes(item.Name)) {
          item.IsChoose = true
        }
      })
    },
    // 获取检查部位
    async getTrialBodyPartList(data) {
      try {
        let params = {
          TrialId: this.$route.query.trialId,
        }
        let res = await getTrialBodyPartList(params)
        if (res.IsSuccess) {
          this.trialBodyPartList = res.Result
          if (data) {
            if (this.$refs.bodyPartTable) {
              this.$nextTick(() => {
                let obj = this.trialBodyPartList.filter(
                  (item) => item.Code === data.Code
                )
                if (obj[0]) {
                  this.$refs.bodyPartTable.toggleRowSelection(obj[0])
                }
              })
              var bodyPartTypes = this.form.BodyPartTypeList.map((i) => {
                return this.changeBodyPart(i.trim())
              })
              this.form.BodyPartTypes = bodyPartTypes
                .toString()
                .replaceAll(',', ' | ')
            }
          }
          return true
        }
        return false
      } catch (err) {
        console.log(err)
        return false
      }
    },
    // 添加检查部位
    async addOrUpdateTrialBodyPart() {
      try {
        this.errMessage = null
        let validate = await this.$refs.addBodyPartForm.validate()
        if (!validate) return
        let str = this.addBodyPartForm.bodyPartStr
        let data = {
          Code: str,
          Name: str,
          NameCN: str,
          TrialId: this.$route.query.trialId,
        }
        if (this.addBodyPartForm.Id) {
          data.Id = this.addBodyPartForm.Id
          data.Code = this.addBodyPartForm.Code
        }
        let res = await addOrUpdateTrialBodyPart(data)
        if (res.IsSuccess) {
          this.getTrialBodyPartList(data)
          this.$message.success(
            this.$t('trials:seeting:message:addBodyPartSuccess')
          )
          this.addBodyPart_model.visible = false
          this.addBodyPartForm.bodyPartStr = null
          this.addBodyPartForm.Id = null
        }
      } catch (err) {
        console.log(err)
        if (err.Code === 5) {
          this.getTrialBodyPartList()
          this.errMessage = err.ErrorMessage
        }
      }
    },
    async addOrUpdateTrialStudyName() {
      let validate = await this.$refs.addStudyNameForm.validate()
      if (!validate) return
      this.addStudyNameForm.EnName = this.addStudyNameForm.Name
      let data = { ...this.addStudyNameForm }
      let arr = []
      this.trialStudyNameList.forEach((item) => {
        let obj = {
          EnName: item.EnName,
          Name: item.EnName,
          IsChoose: false,
        }
        arr.push(obj)
      })
      arr.push(data)

      this.studyNameLoading = true
      let res = await this.updateStudyNameList(arr)
      this.studyNameLoading = false
      if (!res)
        return this.$message.warning(
          this.$t('trials:seeting:message:addStudyNameFail')
        )
      this.$message.success(
        this.$t('trials:seeting:message:addStudyNameSucccess')
      )
      this.addStudyNameForm = {
        EnName: null,
        Name: null,
        IsChoose: false,
      }
      this.addStudyName_model.visible = false
      // this.getStudyNameList()
      this.trialStudyNameList.push(data)
    },
    async updateStudyNameList(StudyNameList) {
      try {
        let data = {
          TrialId: this.$route.query.trialId,
          StudyNameList,
        }
        let res = await updateTrialStudyNameList(data)
        if (res.IsSuccess) {
          return true
        }
        return false
      } catch (err) {
        console.log(err)
        return false
      }
    },
    // 编辑检查部位
    handleEditBodyPart(item) {
      this.addBodyPartForm.bodyPartStr = item.Name
      this.addBodyPartForm.Code = item.Code
      this.addBodyPartForm.Id = item.Id
      this.addBodyPart_model.title = this.$t('trials:setting:button:edit')
      this.addBodyPart_model.visible = true
    },
    async handleDelStudyName(item) {
      let index = this.trialStudyNameList.findIndex(
        (data) => item.Name === data.Name
      )
      let arr = []
      this.trialStudyNameList.forEach((item, i) => {
        if (index !== i) {
          let obj = {
            EnName: item.EnName,
            Name: item.EnName,
            IsChoose: false,
          }
          arr.push(obj)
        }
      })
      this.listLoading = true
      let res = await this.updateStudyNameList(arr)
      this.listLoading = false
      if (!res)
        return this.$message.warning(
          this.$t('trials:seeting:message:delStudyNameFail')
        )
      this.$message.success(
        this.$t('trials:seeting:message:delStudyNameSucccess')
      )
      this.trialStudyNameList.splice(index, 1)
      // this.getStudyNameList()
    },
    handleSetBodyPart() {
      this.bodyPartListVisible = true
      this.$nextTick(() => {
        var a = this.trialBodyPartList.filter((v) => {
          return !!this.form.BodyPartTypeList.find((v1) => {
            return v1 === v.Code
          })
        })
        this.toggleBodyPartSelection(a)
      })
    },
    handleSetStudyName() {
      this.studyNameListVisible = true
      this.trialStudyNameList = []
      this.form.StudyNameList.forEach((item) => {
        this.trialStudyNameList.push({
          ...item,
        })
      })
      this.$nextTick(() => {
        let select = this.trialStudyNameList.filter((item) => item.IsChoose)
        this.toggleStudyNameSelection(select)
      })
    },
    toggleBodyPartSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.bodyPartTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.bodyPartTable.clearSelection()
      }
    },
    toggleStudyNameSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.studyNameTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.studyNameTable.clearSelection()
      }
    },
    handleConfirmBodyParts() {
      this.form.BodyPartTypeList = Object.assign(
        [],
        this.selectedBodyParts.map((v) => v.Code)
      )
      var bodyPartTypes = this.form.BodyPartTypeList.map((i) => {
        return this.changeBodyPart(i.trim())
      })
      this.form.BodyPartTypes = bodyPartTypes.join(' | ')
      this.bodyPartListVisible = false
    },
    handleConfirmStudyName() {
      var studyNameTypes = this.trialStudyNameList.filter((i) => i.IsChoose)
      this.form.StudyNameTypes = this.isEN
        ? studyNameTypes.map((item) => item.EnName).join(', ')
        : studyNameTypes.map((item) => item.Name).join(', ')
      this.form.StudyNameList = this.trialStudyNameList
      this.studyNameListVisible = false
    },
    // 配置信息保存
    handleSave() {
      this.$refs['logicalConfigForm'].validate((valid) => {
        if (!valid) return
        this.loading = true
        // 保存配置信息
        var params = Object.assign({}, this.form)
        params.BodyPartTypes = this.form.BodyPartTypeList.toString().replaceAll(
          ',',
          '|'
        )

        configTrialBasicInfo(params)
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              this.$message.success(this.$t('common:message:savedSuccessfully'))
              this.initialForm = { ...this.form }
            }
          })
          .catch((_) => {
            this.loading = false
          })
      })
    },

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

    // 打开配置信息更新框
    handleUpdate() {
      this.$refs['logicalConfigForm'].validate((valid) => {
        if (!valid) return
        this.getConfigArr()
        this.updateVisible = true
      })
    },
    // 配置确认签名
    handleConfirmConfigData() {
      const { LogicalConfigConfirmation } = const_.processSignature
      this.signCode = LogicalConfigConfirmation
      // this.confirmConfigData()
      this.initialForm = { ...this.form }
      this.signVisible = true
    },
    // 配置更新签名
    handleUpdateConfigData() {
      const { LogicalConfigUpdates } = const_.processSignature
      this.signCode = LogicalConfigUpdates
      this.initialForm = { ...this.form }
      this.signVisible = true
    },

    // 配置确认（废除）
    confirmConfigData() {
      this.$refs['logicalConfigForm'].validate((valid) => {
        if (!valid) return
        this.btnLoading = true
        // 保存配置信息
        var params = Object.assign({}, this.form)
        params.BodyPartTypes = this.form.BodyPartTypeList.toString().replaceAll(
          ',',
          ' | '
        )
        configTrialBasicInfo(params)
          .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
      }
    },
    // 签名并确认
    signConfirm(signInfo) {
      this.loading = true
      var obj = Object.assign({}, this.form)
      obj.BodyPartTypes = this.form.BodyPartTypeList.toString().replaceAll(
        ',',
        '|'
      )
      const params = {
        data: obj,
        signInfo: signInfo,
      }
      // 保存并签名确认
      ConfigTrialBasicInfoConfirm(params)
        .then((res) => {
          this.loading = false
          if (res.IsSuccess) {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.form.IsTrialBasicLogicConfirmed = true
            this.isEdit = false
            this.$refs['signForm'].btnLoading = false
            this.signVisible = false
            this.updateVisible = false
            this.confirmVisible = false
            this.$emit('refresh')
          }
        })
        .catch((_) => {
          this.loading = false
          this.$refs['signForm'].btnLoading = false
        })
    },
    // 配置信息数组结构
    getConfigArr() {
      this.confirmData = [
        {
          Name: this.$t('trials:logincCfg:form:subjectNumberRule'),
          NewVal: this.$fd('YesOrNo', this.form.IsNoticeSubjectCodeRule),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsNoticeSubjectCodeRule),
        },
        {
          Name: this.$t('trials:logincCfg:form:subjectNumFormat'),
          NewVal: this.form.SubjectCodeRule,
          OldVal: this.initialForm.SubjectCodeRule,
        },
        {
          Name: this.$t('trials:logincCfg:form:subjectNum2'),
          NewVal: this.$fd('YesOrNo', this.initialForm.IsSubjectSecondCodeView),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsSubjectSecondCodeView),
        },
        {
          Name: this.$t('trials:logincCfg:form:scanDateVerify'),
          NewVal: this.$fd('YesOrNo', this.form.IsVerifyVisitImageDate),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsVerifyVisitImageDate),
        },
        {
          Name: this.$t('trials:logincCfg:form:visitBaseDate'),
          NewVal: this.$fd('YesOrNo', this.form.IsHaveFirstGiveMedicineDate),
          OldVal: this.$fd(
            'YesOrNo',
            this.initialForm.IsHaveFirstGiveMedicineDate
          ),
        },
        {
          Name: this.$t('trials:logincCfg:form:subjectAge'),
          NewVal: this.$fd('YesOrNo', this.form.IsHaveSubjectAge),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsHaveSubjectAge),
        },
        {
          Name: this.$t('trials:logincCfg:form:subjectGender'),
          NewVal: this.$fd('YesOrNo', this.form.IsSubjectSexView),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsSubjectSexView),
        },
        {
          Name: this.$t('trials:logincCfg:form:lastVisitName'),
          NewVal: this.form.OutEnrollmentVisitName,
          OldVal: this.initialForm.OutEnrollmentVisitName,
        },
        // {
        //   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:imageCopy'),
          NewVal: this.$fd('YesOrNo', this.form.IsImageReplicationAcrossTrial),
          OldVal: this.$fd(
            'YesOrNo',
            this.initialForm.IsImageReplicationAcrossTrial
          ),
        },
        {
          Name: this.$t('trials:logincCfg:form:bodypart'),
          NewVal: this.form.BodyPartTypes,
          OldVal: this.initialForm.BodyPartTypes,
        },
        {
          Name: this.$t('trials:logincCfg:form:modality'),
          NewVal: this.form.ModalityListStr,
          OldVal: this.initialForm.ModalityListStr,
        },
        {
          Name: this.$t('trials:logincCfg:form:IsShowStudyName '),
          NewVal: this.$fd('YesOrNo', this.form.IsShowStudyName),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsShowStudyName),
        },
        {
          Name: this.$t('trials:logincCfg:form:StudyNameList'),
          NewVal: this.form.StudyNameTypes,
          OldVal: this.initialForm.StudyNameTypes,
        },
        {
          Name: this.$t('trials:logincCfg:form:exceededDays'),
          NewVal: this.form.ChangeDefalutDays,
          OldVal: this.initialForm.ChangeDefalutDays,
        },
        {
          Name: this.$t('trials:logincCfg:form:IsIQCAutoNextTask'),
          NewVal: this.$fd('YesOrNo', this.form.IsIQCAutoNextTask),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsIQCAutoNextTask),
        },
        {
          Name: this.$t('trials:logincCfg:form:IsSupportQCDownloadImage'),
          NewVal: this.$fd('YesOrNo', this.form.IsSupportQCDownloadImage),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsSupportQCDownloadImage),
        },
        {
          Name: this.$t('trials:processCfg:form:IsImageQualityControl'), // 影像质控风险控制
          NewVal: this.$fd('YesOrNo', this.form.IsImageQualityControl),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsImageQualityControl),
        },
        {
          Name: this.$t('trials:logincCfg:form:IsOpenLostVistRead'),
          NewVal: this.$fd('YesOrNo', this.form.IsOpenLostVistRead),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsOpenLostVistRead),
        },
        {
          Name: this.$t('trials:logincCfg:form:IsIQCAutoTaskDistinguishType'),
          NewVal: this.$fd('YesOrNo', this.form.IsIQCAutoTaskDistinguishType),
          OldVal: this.$fd('YesOrNo', this.initialForm.IsIQCAutoTaskDistinguishType),
        },
        // {
        //   Name: '临床数据',
        //   NewVal: this.form.ClinicalDataSetNames.join(', '),
        //   OldVal: this.initialForm.ClinicalDataSetNames.join(', ')
        // }
      ]
      this.form.TrialObjectNameList.forEach((item) => {
        let old =
          this.initialForm.TrialObjectNameList.find(
            (d) => d.Name === item.Name
          ) || {}
        let obj = {
          Name: item.Name,
          NewVal: item.TrialName,
          OldVal: old.TrialName, 
        }
        this.confirmData.push(obj)
      })
    },
    // 筛选号规则提醒
    subjectCodeRuleChange(val) {
      if (!val) {
        this.form.SubjectCodeRule = ''
      }
    },
    // 初始化表单
    async initForm(res) {
      this.form.TrialId = res.TrialId
      this.loading = true
      for (const k in this.form) {
        if (res.hasOwnProperty(k)) {
          this.form[k] = res[k]
        }
      }
      let Modalitys = this.form.ModalityList.map((item) => {
        return this.$fd('Modality', item.trim())
      })
      this.form.ModalityListStr = Modalitys.toString().replaceAll(',', ' | ')
      // this.form.ModalityListStr = this.form.ModalityList.toString().replaceAll(
      //   ",",
      //   " | "
      // );
      let BodyPartTypes = res.BodyPartTypes
      this.form.BodyPartTypes = ''
      this.form.BodyPartTypeList = BodyPartTypes.split('|')
      let StudyNameTypes = this.form.StudyNameList.filter(
        (item) => item.IsChoose
      )
      this.form.StudyNameTypes = ''
      if (StudyNameTypes && StudyNameTypes.length > 0) {
        this.form.StudyNameTypes = this.isEN
          ? StudyNameTypes.map((item) => item.EnName).join(', ')
          : StudyNameTypes.map((item) => item.Name).join(', ')
      }

      let r = await this.getTrialBodyPartList()
      if (r) {
        var bodyPartTypes = this.form.BodyPartTypeList.map((i) => {
          return this.changeBodyPart(i.trim())
        })
        this.form.BodyPartTypes = bodyPartTypes
          .toString()
          .replaceAll(',', ' | ')
        // this.form.ClinicalDataSetNamesStr = this.form.ClinicalDataSetNames.join(', ')
        this.initialForm = { ...this.form }
        this.initialForm.TrialObjectNameList =
          JSON.parse(JSON.stringify(this.form.TrialObjectNameList)) || []
        if (
          !this.form.TrialObjectNameList ||
          (Array.isArray(this.form.TrialObjectNameList) &&
            this.form.TrialObjectNameList.length <= 0)
        ) {
          this.form.TrialObjectNameList = this.$d.Terminology.map((item) => {
            return {
              Name: item.label,
              TrialName: item.label,
              IsDefault: true,
            }
          })
        } else if (
          Array.isArray(this.form.TrialObjectNameList) &&
          this.form.TrialObjectNameList.length > 0
        ) {
          this.$d.Terminology.forEach((item) => {
            if (
              !this.form.TrialObjectNameList.find((d) => d.Name === item.label)
            ) {
              this.form.TrialObjectNameList.push({
                Name: item.label,
                TrialName: item.label,
                IsDefault: true,
              })
            }
          })
        }
        this.loading = false
      }
    },
    // bodyPart中英文转换
    changeBodyPart(code) {
      let arr = this.trialBodyPartList.filter((item) => item.Code === code)
      if (arr[0]) {
        return arr[0].Name
      } else {
        return null
      }
    },
    // 获取临床数据模板信息
    getClinicalDataList(isSelect = false) {
      return new Promise((resolve, reject) => {
        this.listLoading = true
        getTrialClinicalDataTrialSetList({ trialId: this.form.TrialId })
          .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()
          })
      })
    },
    // 获取勾选行数据
    handleSelectChange(val) {
      const arr = []
      this.selectedCD = []
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index].Id)
        this.selectedCD.push(val[index].ClinicalDataSetName)
      }
      this.selectClinicalDataArr = arr
    },
    handleConfirmClinicalData() {
      this.form.ClinicalDataSetNames = this.selectedCD
      this.form.ClinicalDataTrialSetIds = this.selectClinicalDataArr
      this.form.ClinicalDataSetNamesStr =
        this.form.ClinicalDataSetNames.join(', ')
      this.clinicalDataVisible = false
    },
    handleSetCD() {
      this.clinicalDataVisible = true
      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.addOrEditCD.visible = true
    },
    handleEditClinicalData(row) {
      this.currentRow = { ...row }
      this.addOrEditCD.title = '编辑'
      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) {
      this.listLoading = true
      DownloadTrialClinicalFile(row.Id)
        .then((data) => {
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    handleSelectable(row) {
      if (!row.IsUsed) {
        return true
      } else {
        return false
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.bodyPartName {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;

  span {
    display: inline-block;
    max-width: 80%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
  }
}

.logincal-config-form {
  .fontColor {
    color: red;
  }
}

.errTip {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
}

::v-deep .el-transfer-panel__body {
  height: calc(100% - 50px);

  .el-transfer-panel__list.is-filterable {
    height: calc(100% - 55px);
  }
}

::v-deep .el-transfer {
  height: 100%;
  text-align: left;
}

::v-deep .el-transfer-panel {
  height: 100%;
  width: calc(50% - 60px);
}

::v-deep .el-transfer__buttons {
  button {
    display: block;
  }

  .el-button+.el-button {
    margin: 0;
  }
}

.showMore {
  cursor: pointer;
  color: #409eff;

  i {
    transition: 0.3s;
  }
}

.showMore.isCheck {
  i {
    transform: rotate(180deg);
  }
}
</style>
