<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:inspection:button:addTrials") }}（{{
        $t("trials:uploadDicomList:table:patientInfo")
      }}：{{ Patient.PatientIdStr }}，{{ Patient.PatientName }}）</span
    >
    <div class="top">
      <p class="line">{{ $t("trials:inspection:message:checkAddTrials") }}</p>
      <el-form
        ref="submitMessageForm"
        :inline="true"
        :model="submitMessage"
        class="demo-form-inline"
        :rules="rules"
        label-width="150px"
      >
        <div>
          <!--项目-->
          <el-form-item
            :label="$t('trials:workbench:label:trialsStats')"
            prop="TrialId"
          >
            <trialsSelect
              :options="trialList"
              :data.sync="submitMessage"
              :status="status"
            />
          </el-form-item>
        </div>
        <div class="selectAndBtn">
          <!--受试者编号-->
          <el-form-item
            :label="$t('trials:crcQuestion:table:subjectId')"
            prop="SubjectId"
          >
            <el-select
              v-model="submitMessage.SubjectId"
              filterable
              allow-create
              default-first-option
              clearable
              :disabled="status === 'visit' || !submitMessage.TrialId"
            >
              <el-option
                v-for="item in subjectIdList"
                :key="item.SubejctId"
                :label="item.SubjectCode"
                :value="item.SubejctId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <div class="btnBox">
            <!--确认添加按钮-->
            <el-button
              type="primary"
              v-if="status === 'trial'"
              @click="addTrials"
              :loading="btnLoading"
            >
              {{ $t("trials:addRP:button:confirmAddPR") }}
            </el-button>
            <!--移除按钮-->
            <el-button
              type="primary"
              v-else
              @click="remove"
              :loading="btnLoading"
            >
              {{ $t("common:button:remove") }}
            </el-button>
          </div>
        </div>
      </el-form>
    </div>
    <confirmVisitList
      ref="confirmVisit"
      :Patient="Patient"
      :submitMessage="submitMessage"
      :status="status"
    />
  </el-dialog>
</template>
<script>
import Pagination from "@/components/Pagination";
import trialsSelect from "./trials-select.vue";
import confirmVisitList from "./confirm-visit-list.vue";
import {
  getPatientJoinTrialInitSelectList,
  getTrialSubejctSelectList,
  addSubjectPatientBinding,
  deleteSubjectPatientBinding,
} from "@/api/inspection.js";
export default {
  name: "addTrialsList",
  components: { Pagination, trialsSelect, confirmVisitList },
  props: {
    visible: {
      required: true,
      default: false,
    },
    Patient: {
      required: true,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      // 绑定项目相关提交数据
      status: "trial", // 页面当前状态  trial 绑定项目  visit 确认访视
      trialList: [],
      btnLoading: false,
      submitMessage: {
        SubjectId: null,
        TrialId: null,
        TrialCode: null,
        ResearchProgramNo: null,
      },
      subjectIdList: [], // 受试者列表
      rules: {
        TrialId: [
          {
            required: true,
            message: this.$t("trials:inspection:message:checkAddTrials"),
            trigger: "change",
          },
        ],
        SubjectId: [
          {
            required: true,
            message: this.$t("trials:inscept:rules:selectOrInputSubject"),
            trigger: "change",
          },
        ],
      },
    };
  },
  created() {
    this.getTrialList();
  },
  watch: {
    "submitMessage.TrialId": {
      handler() {
        if (this.submitMessage.TrialId) {
          this.getTrialSubejctSelectList(this.submitMessage.TrialId);
        } else {
          this.subjectIdList = [];
        }
      },
    },
  },
  methods: {
    // 获取受试者列表
    async getTrialSubejctSelectList(id) {
      let data = {
        TrialId: id,
      };
      try {
        let res = await getTrialSubejctSelectList(data);
        if (res.IsSuccess) {
          this.subjectIdList = res.Result;
          this.submitMessage.SubjectId = null;
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 关闭弹框
    beforeCloseStudyDig() {
      this.$emit("update:visible", false);
    },
    // 加入项目
    async addTrials() {
      if (this.btnLoading) return;
      try {
        let validate = await this.$refs.submitMessageForm.validate();
        if (!validate) return;
        let data = {
          TrialId: this.submitMessage.TrialId,
          PatientIdList: [this.Patient.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;
          if (data.SubjectCode) {
            let obj = {
              PatientList: [],
              SubejctId: res.Result,
              SubjectCode: data.SubjectCode,
            };
            this.subjectIdList.unshift(obj);
          }
          this.$message.success(this.$t("common:message:addedSuccessfully"));
          this.status = "visit";
          this.$emit("getList");
          this.$nextTick(() => {
            this.$refs.confirmVisit.getList(true);
            this.$refs.confirmVisit.getSubjectVisitSelectList();
          });
        }
      } catch (err) {
        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.btnLoading = true;
        let res = await deleteSubjectPatientBinding(params);
        this.btnLoading = false;
        if (res.IsSuccess) {
          this.$refs.confirmVisit.reset(true);
          this.status = "trial";
          this.$message.success(this.$t("common:message:removedSuccessfully"));
          this.$emit("getList");
          this.$refs.confirmVisit.changeVisitStatus(true);
        }
      } catch (err) {
        console.log(err);
      }
    },
    // 获取项目列表
    async getTrialList() {
      let data = {};
      data.PatientId = this.Patient.PatientId;
      try {
        let res = await getPatientJoinTrialInitSelectList(data);
        if (res.IsSuccess) {
          this.trialList = res.Result;
        }
      } catch (err) {
        console.log(err);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.top {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
}
.search {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .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;
}
.demo-form-inline {
  width: 100%;
}
</style>