<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"
      >
        <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"
      >
        <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"
      >
        <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"
      >
        <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: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>
        <!-- 保存 -->
        <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="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="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"
          />
          <el-table-column
            prop="Name"
            :label="$t('trials:logincCfg:form:bodypart')"
          >
            <template slot-scope="scope">{{ scope.row.Name }}</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="800px"
    >
      <div class="base-dialog-body" style="height: 400px; text-align: center">
        <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"
          />
          <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="addBodyPartForm.bodyPartStr"
              clearable
              :maxlength="50"
              @focus="errMessage = null"
            ></el-input>
            <span class="errTip" v-if="errMessage">{{ errMessage }}</span>
          </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>
  </div>
</template>
<script>
import {
  configTrialBasicInfo,
  getTrialClinicalDataTrialSetList,
  deleteClinicalTrialSetData,
  DownloadTrialClinicalFile,
} from "@/api/trials";
import {
  ConfigTrialBasicInfoConfirm,
  getTrialBodyPartList,
  addOrUpdateTrialBodyPart,
} from "@/api/trials/setting";
import SignForm from "@/views/trials/components/newSignForm";
import ClinicalDataForm from "./clinicalDataForm";
import const_ from "@/const/sign-code";
import BaseModel from "@/components/BaseModel";
export default {
  name: "LogicalConfig",
  components: { SignForm, ClinicalDataForm, BaseModel },
  data() {
    return {
      form: {
        TrialId: "",
        IsNoticeSubjectCodeRule: false,
        SubjectCodeRule: "",
        IsSubjectSecondCodeView: false,
        IsVerifyVisitImageDate: false,
        IsHaveFirstGiveMedicineDate: true,
        IsHaveSubjectAge: false,
        IsSubjectSexView: false,
        OutEnrollmentVisitName: "EOT",
        // ClinicalInformationTransmissionEnum: 1,
        IsImageReplicationAcrossTrial: false,
        BodyPartTypes: "",
        BodyPartTypeList: [],
        Modalitys: "",
        ModalityList: [],
        ModalityListStr: "",
        ChangeDefalutDays: 5,
        IsTrialBasicLogicConfirmed: 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",
          },
        ],
        // 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' }
        // ]
      },
      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,
      selectedList: [],
      selectedBodyParts: [],
      trialBodyPartList: [],
      addBodyPart_model: {
        visible: false,
        title: this.$t("trials:setting:button:add"),
        width: "500px",
        appendToBody: true,
      },
      addBodyPartForm: {
        bodyPartStr: null,
      },
      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"],
          },
        ],
      },
      errMessage: null,

      renderFunc(h, option) {
        return (
          <span>
            {option.value} <span style="color:#ddd">-</span>{" "}
            {option.raw.Description}
          </span>
        );
      },
    };
  },
  created() {
    this.getTrialBodyPartList();
  },
  methods: {
    handleConfirmModality() {
      this.form.ModalityList = Object.assign(
        [],
        this.selectedList.map((v) => v)
      );
      this.form.ModalityListStr = this.form.ModalityList.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;
      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;
    },
    // 获取检查部位
    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
                );
                console.log(obj);
                this.$refs.bodyPartTable.toggleRowSelection(obj[0]);
              });
            }
          }
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 添加检查部位
    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,
        };
        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;
        }
      } catch (err) {
        console.log(err);
        if (err.Code === 5) {
          this.getTrialBodyPartList();
          this.errMessage = err.ErrorMessage;
        }
      }
    },
    handleSetBodyPart() {
      this.bodyPartListVisible = true;
      this.$nextTick(() => {
        var a = this.trialBodyPartList.filter((v) => {
          return !!this.form.BodyPartTypeList.find((v1) => {
            return v1 === v.Name;
          });
        });
        this.toggleBodyPartSelection(a);
      });
    },
    toggleBodyPartSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.bodyPartTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.bodyPartTable.clearSelection();
      }
    },
    handleConfirmBodyParts() {
      this.form.BodyPartTypeList = Object.assign(
        [],
        this.selectedBodyParts.map((v) => v.Name)
      );
      var bodyPartTypes = this.form.BodyPartTypeList;
      this.form.BodyPartTypes = bodyPartTypes.join(" | ");
      this.bodyPartListVisible = 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:exceededDays"),
          NewVal: this.form.ChangeDefalutDays,
          OldVal: this.initialForm.ChangeDefalutDays,
        },
        // {
        //   Name: '临床数据',
        //   NewVal: this.form.ClinicalDataSetNames.join(', '),
        //   OldVal: this.initialForm.ClinicalDataSetNames.join(', ')
        // }
      ];
    },
    // 筛选号规则提醒
    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];
        }
      }
      this.form.ModalityListStr = this.form.ModalityList.toString().replaceAll(
        ",",
        " | "
      );
      this.form.BodyPartTypeList = this.form.BodyPartTypes.split("|");
      var bodyPartTypes = this.form.BodyPartTypeList.map((i) => {
        return i.trim();
      });
      this.form.BodyPartTypes = bodyPartTypes.toString().replaceAll(",", " | ");
      // this.form.ClinicalDataSetNamesStr = this.form.ClinicalDataSetNames.join(', ')
      this.initialForm = { ...this.form };
      this.loading = false;
    },
    // 获取临床数据模板信息
    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("删除成功!");
            }
          })
          .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>
.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% - 100px);
}
</style>
