<template>
  <el-dialog :visible.sync="visible" :close-on-click-modal="false" :fullscreen="true" custom-class="upload-dialog"
    :before-close="beforeCloseStudyDig">
    <span slot="title">{{ $t("trials:subject:title:addSubject") }}（{{
      $t("trials:trials-list:table:researchNumber")
    }}：{{ researchProgramNo }}）</span>
    <div class="top">
      <p class="line">{{ $t("trials:inspection:subject:checkAddPatient") }}</p>
      <el-form :inline="true" :model="submitMessage" class="demo-form-inline topForm" :rules="rules"
        ref="addSubjectForm" :label-width="isEN ? '170px' : '130px'">
        <div>
          <!--受试者编号-->
          <el-form-item :label="$t('trials:addSubject:search:subjectId')" prop="SubjectId" class="SubjectId">
            <el-select v-model="submitMessage.SubjectId" filterable clearable :disabled="status === 'visit'"
              style="width: 300px">
              <el-option v-for="item in subjectIdList" :key="item.SubejctId" :label="item.ShortName || item.Sex
                ? `${item.SubjectCode}（${item.ShortName}，${item.Sex ? $fd('Sex', item.Sex) : ''
                }）`
                : item.SubjectCode
                " :value="item.SubejctId">
              </el-option>
            </el-select>
          </el-form-item>
          <!--添加受试者-->
          <el-button type="primary" v-if="status === 'trial'" @click="addSubject_model.visible = true">
            {{ $t("trials:selectSubject:button:add") }}
          </el-button>
          <!--患者-->
          <el-form-item :label="$t('trials:addSubject:search:patient')">
            <el-input :value="selectPatient.map((item) => item.PatientIdStr).join(', ')" disabled
              :title="selectPatient.map((item) => item.PatientIdStr).join(', ')" />
          </el-form-item>
          <el-button type="primary" @click.stop="openPatientList" v-if="status === 'trial'"
            :disabled="!submitMessage.SubjectId">
            {{ $t("common:button:check") }}
          </el-button>
          <div class="btnBox">
            <el-button type="primary" @click="save" :loading="btnLoading" v-if="status === 'trial'">
              {{ $t("trials:addRP:button:confirmAddPR") }}
            </el-button>
            <!-- <el-button
              type="primary"
              @click="remove"
              :loading="btnLoading"
              v-else
            >
              {{ $t("common:button:remove") }}
            </el-button> -->
          </div>
        </div>
        <div>
          <el-form-item :label="$t('trials:study:tabpane:bindPatient')" :style="{ opacity: bindPatientTip ? 1 : 0 }">
            <span v-if="bindPatientTip">{{
              bindPatientTip.map((item) => item.PatientIdStr).join(", ")
            }}</span>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <confirmVistList ref="confirmVisit" :Patient="Patient" :submitMessage="submitMessage" :status="status"
      @close="beforeCloseStudyDig" />
    <base-model v-if="patient_model.visible" :config="patient_model">
      <template slot="dialog-body">
        <SubjectPatientList @addPatient="addPatient" :visible.sync="patient_model.visible"
          :submitMessage="submitMessage" />
      </template>
    </base-model>
    <base-model v-if="addSubject_model.visible" :config="addSubject_model">
      <template slot="dialog-body">
        <el-form ref="addSubjectForm2" :inline="true" :model="addSubjectForm2" class="demo-form-inline"
          :rules="addSubjectrules">
          <!--受试者编号-->
          <el-form-item :label="$t('trials:addSuject:form:subjectCode')" prop="SubjectCode" label-width="150px">
            <el-input v-model="addSubjectForm2.SubjectCode" :maxlength="14" clearable @input="
              addSubjectForm2.SubjectCode =
              addSubjectForm2.SubjectCode.replace(/[^0-9a-zA-Z\_\-]/g, '')
              " @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="addSubject">
          {{ $t("common:button:confirm") }}
        </el-button>
        <el-button @click="addSubject_model.visible = false">
          {{ $t("common:button:cancel") }}
        </el-button>
      </template>
    </base-model>
  </el-dialog>
</template>
<script>
import confirmVistList from "@/views/trials/trials-inspection/components/confirm-visit-list.vue";
import SubjectPatientList from "./patient-list.vue";
import BaseModel from "@/components/BaseModel";
import Pagination from "@/components/Pagination";
import {
  getTrialSubejctSelectList,
  addSubjectPatientBinding,
  verifyTrialSubject,
} from "@/api/inspection.js";
const defaultSearchData = () => {
  return {
    PatientIdStr: null,
    PatientName: null,
    CalledAEList: [],
    EarliestStudyTime: null,
    LatestStudyTime: null,
    Asc: false,
    SortField: "LatestPushTime",
    PageIndex: 1,
    PageSize: 20,
  };
};
export default {
  name: "addSubject",
  components: { Pagination, confirmVistList, SubjectPatientList, BaseModel },
  props: {
    visible: {
      require: true,
      default: false,
    },
  },
  data() {
    return {
      researchProgramNo: null,
      // 查询
      searchData: defaultSearchData(),
      // 可加入项目列表
      total: 0,
      loading: false,
      list: [],
      // 提交数据
      Patient: {},
      status: "trial", // 页面当前状态  trial 绑定患者  visit 确认访视
      patient_model: {
        visible: false,
        title: this.$t("trials:subject:messge:selectPatient"),
        width: "1200px",
        appendToBody: true,
      },
      btnLoading: false,
      submitMessage: { SubjectId: null },
      selectPatient: [],
      subjectIdList: [],
      rules: {
        SubjectId: [
          {
            required: true,
            message: this.$t("trials:inscept:rules:selectOrInputSubject"),
            trigger: "change",
          },
        ],
      },
      // 新增受试者
      addSubject_model: {
        visible: false,
        title: this.$t("trials:selectSubject:button:add"),
        width: "500px",
        appendToBody: true,
      },
      addSubjectForm2: {
        SubjectCode: null,
      },
      addSubjectrules: {
        SubjectCode: [
          {
            required: true,
            message: this.$t("trials:subject:format:notSubject"),
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              let flag = this.subjectIdList.some(
                (item) => item.SubjectCode === value
              );
              if (flag) {
                callback(
                  new Error(this.$t("trials:addSubject:format:hasSubject"))
                );
              } else {
                callback();
              }
            },
            message: this.$t("trials:addSubject:format:hasSubject"),
            trigger: ["blur", "change"],
          },
        ],
      },
      errMessage: null,
    };
  },
  computed: {
    bindPatientTip() {
      if (!this.submitMessage.SubjectId) return false;
      let PatientList = [];
      this.subjectIdList.some((item) => {
        if (
          item.SubejctId === this.submitMessage.SubjectId &&
          item.PatientList &&
          item.PatientList.length > 0
        ) {
          PatientList.push(...item.PatientList);
        }
      });
      if (PatientList.length <= 0) return false;
      return PatientList;
    },
    isEN() {
      return this.$i18n.locale !== 'zh'
    }
  },
  watch: {
    "addSubject_model.visible": {
      handler() {
        if (!this.addSubject_model.visible) {
          this.addSubjectForm2.SubjectCode = null;
        }
      },
    },
  },
  created() {
    this.researchProgramNo = this.$route.query.researchProgramNo;
    this.getTrialSubejctSelectList(this.$route.query.trialId);
  },
  methods: {
    // 新增受试者(前端操作未同步后端)
    async addSubject() {
      try {
        this.errMessage = null;
        let validate = await this.$refs.addSubjectForm2.validate();
        if (!validate) return;
        let data = {
          TrialId: this.$route.query.trialId,
          SubjectCode: this.addSubjectForm2.SubjectCode,
        };
        let res = await verifyTrialSubject(data);
        if (res.IsSuccess) {
          let subject = {
            SubjectCode: this.addSubjectForm2.SubjectCode,
            SubejctId: this.addSubjectForm2.SubjectCode,
          };
          this.subjectIdList.unshift(subject);
          this.submitMessage.SubjectId = this.addSubjectForm2.SubjectCode;
          this.addSubject_model.visible = false;
        }
      } catch (err) {
        console.log(err);
        if (err.Code === 5) {
          this.getTrialSubejctSelectList(this.$route.query.trialId);
          this.$emit("getList");
          this.errMessage = err.ErrorMessage;
        }
      }
    },
    // 删除选中患者
    delPatient(index) {
      this.selectPatient.splice(index, 1);
    },
    addPatient(item) {
      this.selectPatient = item;
    },
    // 关闭弹框
    beforeCloseStudyDig() {
      this.$emit("update:visible", false);
    },
    // 确认添加
    async save() {
      try {
        if (this.btnLoading) return;
        let validate = await this.$refs.addSubjectForm.validate();
        if (!validate) return;
        if (this.selectPatient.length <= 0)
          return this.$message.warning(
            this.$t("trials:subject:formatData:notCheckPantient")
          );
        let data = {
          TrialId: this.$route.query.trialId,
          PatientIdList: this.selectPatient.map((item) => item.PatientId),
        };
        if (this.submitMessage.SubjectId.length === 36) {
          data.SubjectId = this.submitMessage.SubjectId;
        } else {
          data.SubjectCode = this.submitMessage.SubjectId;
        }
        this.btnLoading = true;
        let res = await addSubjectPatientBinding(data);
        this.btnLoading = false;
        if (res.IsSuccess) {
          this.submitMessage.SubjectId = res.Result;
          this.submitMessage.TrialId = data.TrialId;
          let patient = this.bindPatientTip
            ? this.bindPatientTip.map((item) => item.PatientId)
            : [];
          this.Patient.PatientId = [...data.PatientIdList, ...patient];
          this.$message.success(this.$t("common:message:addedSuccessfully"));
          this.$emit("getList");
          this.status = "visit";
          if (data.SubjectCode) {
            let obj = {
              PatientList: [],
              SubejctId: res.Result,
              SubjectCode: data.SubjectCode,
            };
            this.subjectIdList.unshift(obj);
          }
          this.$nextTick(() => {
            this.$refs.confirmVisit.getList();
            this.$refs.confirmVisit.getSubjectVisitSelectList();
          });
        }
      } catch (err) {
        this.btnLoading = false;
        console.log(err);
      }
    },
    // 移除项目
    async remove() {
      try {
        let confirm = await this.$confirm(
          this.$t("trials:sitesList:message:removeSite"),
          {
            type: "warning",
            distinguishCancelAndClose: true,
            confirmButtonText: this.$t("common:button:confirm"),
            cancelButtonText: this.$t("recompose:button:cancel"),
          }
        );
        if (confirm !== "confirm") return;
        let params = {
          PatientId: this.Patient.PatientId,
          SubjectId: this.submitMessage.SubjectId,
        };
        this.loading = true;
        let res = await deleteSubjectPatientBinding(params);
        this.loading = false;
        if (res.IsSuccess) {
          this.getList();
          this.$message.success(this.$t("common:message:removedSuccessfully"));
          this.$emit("getList");
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 获取受试者列表
    async getTrialSubejctSelectList(id) {
      let data = {
        TrialId: id,
      };
      try {
        let res = await getTrialSubejctSelectList(data);
        if (res.IsSuccess) {
          this.subjectIdList = res.Result;
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 打开患者弹框
    openPatientList() {
      if (!this.submitMessage.SubjectId) {
        return this.$message.warning(
          this.$t("trials:inscept:rules:selectOrInputSubject")
        );
      }
      this.patient_model.visible = true;
    },
  },
};
</script>
<style lang="scss" scoped>
.errTip {
  color: #f56c6c;
  font-size: 12px;
  line-height: 1;
  padding-top: 4px;
  position: absolute;
  top: 100%;
  left: 0;
}

.top {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;

  .topForm {
    width: 100%;
  }
}

.btnBox {
  float: right;
}

.search {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  p {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    &::after {
      display: block;
      content: "";
      flex: 1;
      height: 1px;
      border-top: 1px solid #ddd;
    }
  }

  .form {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.line {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;

  &::after {
    display: block;
    content: "";
    flex: 1;
    height: 1px;
    border-top: 1px solid #ddd;
  }
}

.selectAndBtn {
  width: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
}

.patientBox {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;

  p {
    flex: 1;
    padding: 0;
    margin: 0;
  }
}
</style>