<template>
  <div class="logincal-config-form">
    <!-- 配置信息表单 -->
    <el-form
      ref="logicalConfigForm"
      v-loading="loading"
      :model="form"
      label-width="220px"
      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 :maxLength="$inputMax"
          v-model="form.SubjectCodeRule"
          :disabled="form.IsTrialBasicLogicConfirmed && !isEdit"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          maxlength="50"
          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 :maxLength="$inputMax"
          v-model="form.OutEnrollmentVisitName"
          :disabled="form.IsTrialBasicLogicConfirmed && !isEdit"
          maxlength="50"
          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 :maxLength="$inputMax"
          v-model="form.BodyPartTypes"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 8}"
          :disabled="form.IsTrialBasicLogicConfirmed && !isEdit"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
      <el-form-item
        :label="$t('trials:logincCfg:form:modality')"
        prop="ModalityListStr"
      >
        <el-input :maxLength="$inputMax"
          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
        :label="$t('trials:logincCfg:form:clinicalInforTransfer')"
        prop="ClinicalInformationTransmissionEnum"
      >
        <el-radio-group
          v-model="form.ClinicalInformationTransmissionEnum"
          :disabled="form.IsTrialBasicLogicConfirmed && !isEdit"
        >
          <el-radio
            v-for="item of $d.ClinicalInformationTransmissionEnum"
            :key="item.id"
            :label="item.value"
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        v-if="form.ClinicalInformationTransmissionEnum === 1"
        label="临床数据配置"
        prop="ClinicalDataSetNamesStr"
      >
        <el-input :maxLength="$inputMax"
          v-model="form.ClinicalDataSetNamesStr"
          type="textarea"
          :autosize="{ minRows: 1, maxRows: 3}"
          style="width:80%;"
          disabled
        />
        <el-button icon="el-icon-plus" circle :disabled="form.IsTrialBasicLogicConfirmed && !isEdit" @click="handleSetCD" />
      </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="上传人"
            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="modalityListVisible"
      :visible.sync="modalityListVisible"
      :close-on-click-modal="false"
      title="检查技术"
      custom-class="base-dialog-wrapper"
      width="400px"
    >
      <div class="base-dialog-body">
        <el-table
          ref="multipleTable"
          :data="$d.Modality"
          stripe
          height="450"
          row-key="Id"
          class="criterion-table"
          @select="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            align="left"
            width="45"
            :reserve-selection="true"
          />
          <el-table-column
            prop="value"
            label="检查技术"
          />
        </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>
  </div>
</template>
<script>
import { configTrialBasicInfo, getTrialClinicalDataTrialSetList, deleteClinicalTrialSetData, DownloadTrialClinicalFile } from '@/api/trials'
import { ConfigTrialBasicInfoConfirm } from '@/api/trials/setting'
import SignForm from '@/views/trials/components/newSignForm'
import ClinicalDataForm from './clinicalDataForm'
import const_ from '@/const/sign-code'
export default {
  name: 'LogicalConfig',
  components: { SignForm, ClinicalDataForm },
  data() {
    return {
      form: {
        TrialId: '',
        IsNoticeSubjectCodeRule: false,
        SubjectCodeRule: '',
        IsSubjectSecondCodeView: false,
        IsVerifyVisitImageDate: false,
        IsHaveFirstGiveMedicineDate: true,
        IsHaveSubjectAge: false,
        IsSubjectSexView: false,
        OutEnrollmentVisitName: 'EOT',
        // ClinicalInformationTransmissionEnum: 1,
        IsImageReplicationAcrossTrial: false,
        BodyPartTypes: '',
        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: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` }
        ],
        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: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` }
        ],
        BodyPartTypes: [
          { required: true, message: this.$t('trials:trialCfg:formRule:bodyPart'), trigger: 'blur' },
          { max: 500, message: `${this.$t('common:ruleMessage:maxLength')} 500` }
        ],
        // 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' },
          { max: 500, message: `${this.$t('common:ruleMessage:maxLength')} 500` }
        ],
        // 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,
      selectedList: []
    }
  },

  methods: {
    handleConfirmModality() {
      this.form.ModalityList = Object.assign([], this.selectedList.map(v => v.value))
      this.form.ModalityListStr = this.form.ModalityList.toString().replaceAll(',', '|')
      this.modalityListVisible = false
    },
    handleSelectionChange(val) {
      this.selectedList = val
    },
    toggleSelection(rows) {
      console.log(this.$refs.multipleTable)
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    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)
      })
    },
    // 配置信息保存
    handleSave() {
      this.$refs['logicalConfigForm'].validate((valid) => {
        if (!valid) return
        this.loading = true
        // 保存配置信息
        configTrialBasicInfo(this.form).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
        // 保存配置信息
        configTrialBasicInfo(this.form).then(res => {
          this.btnLoading = false
          if (res.IsSuccess) {
            this.initialForm = { ...this.form }
            this.signVisible = true
          }
        }).catch(_ => { this.btnLoading = false })
      })
    },

    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名并确认
    signConfirm(signInfo) {
      this.loading = true
      const params = {
        data: this.form,
        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(',', '|')
      console.log(this.form.ModalityListStr)
      // 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('是否确认删除?', {
        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;
  }
}
</style>
