<template lang="pug">
  .wrapper.flex.flex-col.gap-y-6.justify-between
    .flex.flex.flex-col.gap-y-6
      span.text-center.font-bold.text-xl Создание медицинской карты стоматологического пациента
      .flex.self-center
        base-stepper-quasar(
          :steps="steps",
          :currentStep="currentStep",
          :next-step="nextStep",
          :prev-step="prevStep",
          :finish="finishCreateCard",
          finishLabel="Создать медицинскую карту",
          flat
        )
          component(
            v-bind:is="currentTabComponent",
            :client-detail="clientData"
          )
</template>

<script>
import BaseInput from "@/components/base/BaseInput";
import BaseSelect from "@/components/base/BaseSelect";
import MedicalBaseData from "@/pages/oldMedicalCard/components/MedicalBaseData";
import MedicalIdentityDocuments from "@/pages/oldMedicalCard/components/MedicalIdentityDocuments";
import MedicalPolicyDocuments from "@/pages/oldMedicalCard/components/MedicalPolicyDocuments";
import { requestMedicalCardData } from "@/pages/clients/utils/wrapperClientForm";
import { fetchWrapper } from "@/shared/fetchWrapper.js";
import { v_model } from "@/shared/mixins/v-model";
import BaseStepperQuasar from "@/components/base/BaseStepperQuasar";

export default {
  name: "FormCreateMedicalCard",
  mixins: [v_model],
  components: {
    BaseInput,
    BaseSelect,
    MedicalBaseData,
    MedicalIdentityDocuments,
    MedicalPolicyDocuments,
    BaseStepperQuasar,
  },
  props: {
    selectedClientId: String,
    fetchClients: Function,
  },
  data() {
    return {
      isBaseData: true,
      isIdentityDoc: false,
      isPolicyDoc: false,
      currentStep: 0,
      steps: [
        {
          id: 0,
          label: "1",
          value: "Основное",
          component: "medical-base-data",
        },
        {
          id: 1,
          label: "2",
          value: "ДУЛ",
          component: "medical-identity-documents",
        },
        {
          id: 2,
          label: "3",
          value: "Полис",
          component: "medical-policy-documents",
        },
      ],
      sourceСlientDetail: {},
      clientData: {},
    };
  },
  computed: {
    currentTabComponent: function () {
      return this.steps[this.currentStep]?.component;
    },
  },
  methods: {
    nextStep() {
      this.currentStep += 1;
    },
    prevStep() {
      this.currentStep -= 1;
    },
    finishCreateCard() {
      requestMedicalCardData(this.clientData, this.sourceСlientDetail).then(
        () =>
          fetchWrapper
            .post(`medical_card/medical_history/create/`, {
              person: this.sourceСlientDetail.id,
              organization: "3883e8f5-cede-4645-97a3-6d1511e63d10",
              agreement: true,
            })
            .then(() => {
              this.value = false;
              this.fetchClients();
            })
      );
    },
    fetchClientDetail() {
      fetchWrapper
        .get(`general/person/${this.selectedClientId}/detail/`)
        .then((detail) => this.saveClientDetail(detail));
    },
    saveClientDetail(detail) {
      this.sourceСlientDetail = detail;
      this.clientData = {
        id: detail.id,
        registration_address: detail.address.find(
          (address) => address.registration_flg
        )?.join_address,
        temporary_address: detail.address.find(
          (address) => address.temporary_registration_flg
        )?.join_address,
        benefit_code: detail.benefit_code,
        birth_date: detail.birth_date ? new Date(detail.birth_date) : null,
        //contacts: detail.contacts,
        fullName: `${detail.last_name ?? ""} ${detail.first_name ?? ""} ${
          detail.patronymic ?? ""
        }`,
        gender: detail?.gender,
        insurance_number: detail.insurance_number,
        special_mark: detail.special_mark,
        phone: detail.contacts.find((el) => el.kind === "PHONE")?.username,
        email: detail.contacts.find((el) => el.kind === "EMAIL")?.username,
        confidant_name: "",
        confidant_phone: "",
        policy: "OMS",
      };
      this.saveClientIdentityDoc(detail.identity_documents);
      this.saveCLientPolicy(detail.insurance_policy);
    },
    saveCLientPolicy(data) {
      let OMSPolicy = data.find((el) => el.title === "OMS"),
        DMSPolicy = data.find((el) => el.title === "DMS");
      this.clientData.OMSPolicy = {
        number:
          OMSPolicy?.series && OMSPolicy?.number
            ? `${OMSPolicy?.series} ${OMSPolicy?.number}`
            : "",
        organization: OMSPolicy?.organization || "",
        title: "OMS",
      };
      if (OMSPolicy?.id) this.clientData.OMSPolicy.id = OMSPolicy?.id;
      this.clientData.DMSPolicy = {
        number:
          DMSPolicy?.series && DMSPolicy?.number
            ? `${DMSPolicy?.series} ${DMSPolicy?.number}`
            : "",
        organization: DMSPolicy?.organization || "",
        title: "DMS",
      };
      if (DMSPolicy?.id) this.clientData.DMSPolicy.id = DMSPolicy?.id;
    },
    saveClientIdentityDoc(data) {
      let identityDoc = data.find((el) => el.kind === "PASSPORT");
      this.clientData.identity_documents = {
        kind: "PASSPORT",
        series_number:
          identityDoc?.series && identityDoc?.number
            ? `${identityDoc?.series} ${identityDoc?.number}`
            : "",
        issued_by_org: identityDoc?.issued_by_org || "",
        issued_by_org_code: identityDoc?.issued_by_org_code || "",
        issued_by_date: identityDoc?.issued_by_date
          ? new Date(identityDoc?.issued_by_date)
          : null,
      };
      if (identityDoc?.id)
        this.clientData.identity_documents.id = identityDoc?.id;
    },
  },
  mounted() {
    this.fetchClientDetail();
  },
};
</script>

<style lang="sass" scoped>
.wrapper
  width: 570px
</style>
