<template lang="pug">
  .wrapper.flex.w-full.relative.mx-2
    .wrapper-medical.relative.flex.gap-y-4.flex-col.h-full.w-full( class="pb-52px")
      .card-upper.flex.flex-col.gap-y-4.px-6.py-6
        medical-card-header(:number-card="numberCard")
        .card-basic-info.flex
          base-detail-info(
            :title="configData.identity_document.title"
            :height="configData.identity_document.height"
            :data="defineEmptyData(configData.identity_document.fields)"
            )
            base-detail-input(
              v-for="field in configData.identity_document.fields"
              :field="field"
              :data="medicalDataInit"
              :mask="field.mask"
              )
          .flex.flex-col.gap-30px
            base-detail-info(
              :title="configData.registration_address.title"
              :height="configData.registration_address.height"
              :data="defineEmptyData(configData.registration_address.fields)"
              )
              base-detail-input(
                v-for="field in configData.registration_address.fields"
                :field="field"
                :data="medicalDataInit"
                )
            base-detail-info(
              :title="configData.temporary_address.title"
              :height="configData.temporary_address.height"
              :data="defineEmptyData(configData.temporary_address.fields)"
              )
              base-detail-input(
                v-for="field in configData.temporary_address.fields"
                :field="field"
                :data="medicalDataInit"
                )
          .flex.flex-col.gap-2
            base-detail-info(
              :title="configData.snils.title"
              :height="configData.snils.height"
              :data="defineEmptyData(configData.snils.fields)"
              )
              base-detail-input(
                v-for="field in configData.snils.fields"
                :field="field"
                :data="medicalDataInit"
                :mask="field.mask"
                )
            base-detail-info(
              :title="configData.policy.title"
              :height="configData.policy.height"
              :data="defineEmptyData(configData.policy.fields)"
              )
              base-detail-input(
                v-for="field in configData.policy.fields"
                :field="field"
                :data="medicalDataInit"
                :mask="field.mask"
                )
          base-detail-info(
            :title="configData.policy_organization.title"
            :height="configData.policy_organization.height"
            :data="defineEmptyData(configData.policy_organization.fields)"
            )
            base-detail-input(
              v-for="field in configData.policy_organization.fields"
              :field="field"
              :data="medicalDataInit"
              )
          .flex.flex-col.gap-4
            base-detail-info(
              :title="configData.additional.title"
              :height="configData.additional.height"
              :data="defineEmptyData(configData.additional.fields)"
              )
              base-detail-input(
                v-for="field in configData.additional.fields"
                :field="field"
                :data="medicalDataInit"
                :mask="field.mask"
                )
            base-detail-info(
              :title="configData.agreement_form.title"
              :height="configData.agreement_form.height"
              :data="defineEmptyData(configData.agreement_form.fields)"
              direction-row
              )
              base-detail-input(
                v-for="field in configData.agreement_form.fields"
                :field="field"
                :data="medicalDataInit"
              )
      .flex.flex-col(class="px-92px gap-y-60px")
        .flex.flex-col(class="gap-y-2.5")
          .flex.flex-col.gap-y-2(v-for="(key, index) in Object.keys(dentalIndications)")
            span.font-bold.text-xsx {{`${index+1}. ${configData.dental_indications[key]}`}}
            medical-dental-formula(v-if="key === 'dental_formula'" :formula-data="dentalIndications[key]")
            base-input(v-model="dentalIndications[key]" outlined v-else)
        .flex.justify-center
          q-btn(
            @click="validateFormCard",
            color="primary",
            label="Сохранить",
            padding="8px 24px",
            no-caps
          )
</template>

<script>
import MedicalCardHeader from "@/pages/medicalCard/components/MedicalCardHeader.vue";
import MedicalDentalFormula from "@/pages/medicalCard/components/MedicalDentalFormula.vue";
import BaseDetailInput from "@/components/base/BaseDetailInput.vue";
import BaseDetailInfo from "@/components/base/BaseDetailInfo.vue";
import { formulaDataMap } from "@/pages/medicalCard/utils/medicalConfig";
import { medicalDetailConfig } from "@/pages/medicalCard/utils/medicalConfig";
import { mobilityMap } from "@/pages/medicalCard/utils/medicalConfig";
import {
  getDentalEntiesValue,
  requestUpdateMedicalCard,
  requestCreateMedicalCard,
  getRequestDataPerson,
} from "@/pages/medicalCard/utils/wrapperMedicalCard";
import { fetchWrapper } from "@/shared/fetchWrapper";
import BaseInput from "@/components/base/BaseInput.vue";
import ClientDetailInput from "@/pages/clients/components/ClientDetailInput.vue";
export default {
  name: "MedicalCardWrapper",
  components: {
    ClientDetailInput,
    BaseInput,
    BaseDetailInfo,
    BaseDetailInput,
    MedicalCardHeader,
    MedicalDentalFormula,
  },
  data() {
    return {
      personId: "",
      identityDocumentId: "",
      responseMedicalCardData: undefined,
      responseMedicalDentalData: {},
      numberCard: "",
      configData: medicalDetailConfig,
      medicalDataInit: {
        number_series: undefined,
        issued_by_org: undefined,
        issued_by_org_code: undefined,
        issued_by_date: undefined,
        registration_address: undefined,
        temporary_address: undefined,
        insurance_number: undefined,
        policy_series: undefined,
        policy_number: undefined,
        policy_organization: undefined,
        name_confidant: undefined,
        phone_confidant: undefined,
        benefit_code: undefined,
        agreement: undefined,
        agreement_date: undefined,
      },
      dentalIndications: {
        complaints: undefined,
        allergic: undefined,
        past_diseases: undefined,
        medications_taken: undefined,
        thermometry: undefined,
        tonometry: undefined,
        disease_progress: undefined,
        visual_examination: undefined,
        oral_examination: undefined,
        dental_formula: formulaDataMap,
        dental_bite: undefined,
        hygiene_index: undefined,
        dmf_index: undefined,
        diagnostic_findings: undefined,
        icd_code: undefined,
        survey_plan: undefined,
        survey_data: undefined,
        clinical_diagnosis: undefined,
        treatment_plan: undefined,
        treatment_protocol: undefined,
      },
    };
  },
  methods: {
    defineEmptyData(fields) {
      return fields.map((field) => this.medicalDataInit[field.label]);
    },
    validateFormCard() {
      const dataRequestPerson = getRequestDataPerson(
        this.medicalDataInit,
        this.dentalIndications
      );
      Object.keys(dataRequestPerson).forEach((key) => {
        let valuesData = [
          ...new Set(
            Object.values(this.responseMedicalCardData[key]).map((el) =>
              el === null || el === undefined ? undefined : el
            )
          ),
        ];
        let isUpdateData = false;
        let isCreateData =
          valuesData.length === 1 &&
          valuesData[0] === undefined &&
          Object.values(dataRequestPerson[key]).find((el) => el !== undefined);
        Object.keys(dataRequestPerson[key]).forEach((entries) => {
          if (
            this.responseMedicalCardData[key][entries] &&
            dataRequestPerson[key][entries] !==
              this.responseMedicalCardData[key][entries]
          ) {
            isUpdateData = true;
          }
        });
        if (isUpdateData) {
          requestUpdateMedicalCard(
            dataRequestPerson[key],
            key,
            key === "identity_document"
              ? this.identityDocumentId
              : this.personId
          );
        }
        if (isCreateData) {
          requestCreateMedicalCard(
            dataRequestPerson[key],
            key,
            key === "identity_document"
              ? this.identityDocumentId
              : this.personId
          );
        }
      });
      Object.keys(this.dentalIndications).forEach((key) => {
        if (key === "dental_formula") {
          const notEmptyEntries =
            this.dentalIndications.dental_formula[0].columns
              .concat(this.dentalIndications.dental_formula[1].columns)
              .filter((el) => el.dental_condition && el.tooth_mobility);
          notEmptyEntries.forEach((tooth) => {
            const toothResponse = this.responseMedicalDentalData[key].find(
              (el) => el.tooth_number === tooth.tooth_number
            );
            const isCreate =
              !toothResponse &&
              !!tooth.tooth_mobility &&
              !!tooth.dental_condition;
            if (isCreate) {
              requestCreateMedicalCard(
                tooth,
                key,
                localStorage.getItem("medicalId")
              );
            }
            if (
              toothResponse &&
              toothResponse.tooth_mobility.label !==
                tooth.tooth_mobility.label &&
              toothResponse.dental_condition !== tooth.dental_condition
            ) {
              requestUpdateMedicalCard(tooth, key, toothResponse.id);
            }
          });
        }
        if (
          key !== "dental_formula" &&
          !this.responseMedicalDentalData[key] &&
          this.dentalIndications[key]
        ) {
          requestCreateMedicalCard(
            this.dentalIndications[key],
            key,
            localStorage.getItem("medicalId")
          );
        }
        if (
          key !== "dental_formula" &&
          this.dentalIndications[key] &&
          getDentalEntiesValue(this.responseMedicalDentalData[key], key) !==
            this.dentalIndications[key]
        ) {
          requestUpdateMedicalCard(
            this.dentalIndications[key],
            key,
            this.responseMedicalDentalData[key]?.id
          );
        }
      });
    },
    saveDataMedical(data) {
      this.personId = data?.person?.id;
      this.numberCard = data?.number;
      const confidant = data ? data["confidant"] : undefined;
      const pass = data
        ? data?.person?.identity_document?.find((el) => el.kind === "PASSPORT")
        : null;
      this.identityDocumentId = pass?.id;
      this.medicalDataInit = {
        ...this.medicalDataInit,
        issued_by_org: pass.issued_by_org,
        issued_by_org_code: pass.issued_by_org_code,
        number_series: `${pass.series} ${pass.number}`,
        issued_by_date: new Date(pass.issued_by_date),
        registration_address: data?.person?.address?.find(
          (el) => el["registration_flg"]
        )?.join_address,
        temporary_address: data?.person?.address?.find(
          (el) => el["temporary_registration_flg"]
        )?.join_address,
        insurance_number: data?.person["insurance_number"] || undefined,
        policy_number: data?.person["insurance_policy"][0]?.number,
        policy_series: data?.person["insurance_policy"][0]?.series,
        policy_organization: data?.person["insurance_policy"][0]?.organization,
        name_confidant:
          confidant &&
          `${confidant?.last_name} ${confidant?.last_name} ${confidant?.patronymic}`,
        phone_confidant: confidant?.contacts?.find((el) => el?.kind === "PHONE")
          ?.username,
        benefit_code: data?.person?.benefit_code,
        agreement: data?.agreement,
        agreement_date: undefined,
      };
      Object.keys(this.dentalIndications).forEach((key) => {
        if (key === "dental_formula" && data[key].length) {
          this.responseMedicalDentalData[key] = data[key];
          data[key].forEach((tooth) => {
            if (tooth.dental_condition && tooth.tooth_mobility) {
              if (17 < tooth.tooth_number < 29) {
                this.dentalIndications.dental_formula[0] = {
                  ...this.dentalIndications.dental_formula[0],
                  columns: this.dentalIndications.dental_formula[0].columns.map(
                    (el) => {
                      if (el.tooth_number === tooth.tooth_number) {
                        return {
                          ...tooth,
                          tooth_mobility: mobilityMap.find(
                            (el) => el.label === tooth.tooth_mobility
                          ),
                        };
                      }
                      return el;
                    }
                  ),
                };
              }
              if (37 < tooth.tooth_number < 49) {
                this.dentalIndications.dental_formula[1] = {
                  ...this.dentalIndications.dental_formula[1],
                  columns: this.dentalIndications.dental_formula[1].columns.map(
                    (el) => {
                      if (el.tooth_number === tooth.tooth_number) {
                        return {
                          ...tooth,
                          tooth_mobility: mobilityMap.find(
                            (el) => el.label === tooth.tooth_mobility
                          ),
                        };
                      }
                      return el;
                    }
                  ),
                };
              }
            }
          });
        } else {
          this.dentalIndications[key] = data[key]?.length
            ? getDentalEntiesValue(data[key].at(-1), key)
            : this.dentalIndications[key];
          this.dentalIndications.allergic = data?.person?.allergic
            ? data?.person?.allergic
            : this.dentalIndications.allergic;
          this.responseMedicalDentalData[key] = data[key]?.length
            ? data[key].at(-1)
            : this.dentalIndications[key];
        }
      });
      this.responseMedicalCardData = getRequestDataPerson(
        this.medicalDataInit,
        this.dentalIndications
      );
    },
    async fetchDataMedicalCard() {
      await fetchWrapper
        .get(
          `medical_card/medical_history/${localStorage.getItem(
            "medicalId"
          )}/detail/`
        )
        .then((res) => this.saveDataMedical(res));
    },
  },
  mounted() {
    this.fetchDataMedicalCard();
  },
};
</script>

<style lang="sass" scoped>
.wrapper
  overflow: auto
  border-top-left-radius: 4px
  border-top-right-radius: 4px
.wrapper-medical
  background-color: var(--default-white)
  height: calc(100vh - 64px)
  overflow: auto
  &::-webkit-scrollbar
    height: 4px
    width: 4px
  &::-webkit-scrollbar-track
    background-color: rgba(211, 212, 220, 0.5)
    border-radius: 8px
  &::-webkit-scrollbar-thumb
    border-radius: 8px
    background-color: var(--btn-blue-color)
.card-basic-info
  display: grid
  grid-template-columns: 280px 292px 180px 360px 463px
  gap: 16px
  padding: 0 20px 20px 0
  overflow-x: auto
  &::-webkit-scrollbar
    height: 4px
    width: 4px
  &::-webkit-scrollbar-track
    background-color: rgba(211, 212, 220, 0.5)
    border-radius: 8px
  &::-webkit-scrollbar-thumb
    border-radius: 8px
    background-color: var(--btn-blue-color)
.card-upper
  border-bottom: 1px solid var(--border-light-grey-color)
</style>
