import { fetchWrapper } from "@/shared/fetchWrapper";
import { genderOptions } from "@/pages/newMedicalCard/utils/medicalConfig";

const state = () => ({
  medicalCard: {},
  contactsData: {
    phones: [],
    emails: [],
    networks: [],
  },
  basicData: {
    personalData: {
      last_name: null,
      first_name: null,
      patronymic: null,
      gender: null,
      birth_date: null,
      photo: null,
    },
    registrationAddress: {
      region: null,
      city: null,
      street: null,
      house_number: null,
      apartment_number: null,
    },
    residenceAddress: {
      region: null,
      city: null,
      street: null,
      house_number: null,
      apartment_number: null,
    },
    insuranceDMS: {
      series: null,
      number: null,
      photo: null,
      id: null,
      organization: null,
    },
    insuranceOMS: {
      series: null,
      number: null,
      photo: null,
      id: null,
      organization: null,
    },
    benefit: {
      name: null,
      discount: null,
      photo: null,
    },
  },
  documents: {},
  avatar: "",
});

const getters = {
  getBasicData(state, rootState) {
    let registrationAddress =
      state.medicalCard?.person?.address?.find((el) => el.registration_flg) ||
      {};
    let residenceAddress =
      state?.medicalCard?.person?.address?.find((el) => el.residence_flg) || {};
    let person = state.medicalCard.person;
    let OMS = person?.insurance_policy?.find((e) => e.title === "OMS");
    let DMS = person?.insurance_policy?.find((e) => e.title === "DMS");
    return {
      personalData: {
        last_name: person?.last_name,
        first_name: person?.first_name,
        patronymic: person?.patronymic,
        gender:
          person?.gender &&
          genderOptions.find((el) => el.id === person?.gender),
        birth_date: person?.birth_date
          ? new Date(person?.birth_date)
          : new Date(),
        photo: person?.photo
          ? {
              photo: rootState.getUrl + person.photo,
              file: null,
            }
          : {},
        id: person?.id,
      },
      registrationAddress: {
        region: registrationAddress?.region,
        city: registrationAddress?.city,
        street: registrationAddress?.street,
        house_number: registrationAddress?.house_number,
        apartment_number: registrationAddress?.apartment_number,
        id: registrationAddress?.id,
      },
      residenceAddress: {
        region: residenceAddress?.region,
        city: residenceAddress?.city,
        street: residenceAddress?.street,
        house_number: residenceAddress?.house_number,
        apartment_number: residenceAddress?.apartment_number,
        id: residenceAddress?.id,
      },
      insuranceDMS: {
        series: DMS?.series,
        number: DMS?.number,
        photo: DMS?.photo
          ? {
              photo: rootState.getUrl + DMS?.photo,
              file: null,
            }
          : {},
        id: DMS?.id,
        organization: DMS?.organization,
      },
      insuranceOMS: {
        series: OMS?.series,
        number: OMS?.number,
        photo: OMS?.photo
          ? {
              photo: rootState.getUrl + OMS?.photo,
              file: null,
            }
          : {},
        id: OMS?.id,
        organization: OMS?.organization,
      },
      benefit: {
        name: person?.benefit?.name,
        discount: person?.benefit?.discount,
      },
    };
  },
  getContactsData(state) {
    let phones = state.medicalCard.person.contacts
      .filter((el) => el.kind === "PHONE")
      .map((el) => ({ ...el }));
    let emails = state.medicalCard.person.contacts
      .filter((el) => el.kind === "EMAIL")
      .map((el) => ({ ...el }));
    let networks = state.medicalCard.person.contacts
      .filter((el) => el.kind !== "PHONE" && el.kind !== "EMAIL")
      .map((el) => ({ ...el }));
    return {
      phones: [...phones],
      emails: [...emails],
      networks: [...networks],
    };
  },
  getAvatar(state) {
    let lastName = state?.medicalCard?.person?.last_name;
    let firstName = state?.medicalCard?.person?.first_name;
    return lastName?.[0] + firstName?.[0];
  },
};

const actions = {
  getMedicalCardData({ commit }) {
    fetchWrapper
      .get(
        `medical_card/medical_history/${localStorage.getItem(
          "medicalId"
        )}/detail/`
      )
      .then((res) => {
        commit("setMedicalCard", res);
        commit("setBasicData");
        commit("setContactsData");
        commit("setDocumentData", res.person);
      });
  },
  returnInitData({ commit }) {
    commit("setBasicData");
    commit("setContactsData");
  },
  removeMedicalCardData({ commit, rootState }) {
    fetchWrapper
      .del(
        `medical_card/medical_history/${localStorage.getItem(
          "medicalId"
        )}/delete/`
      )
      .then(() => {
        rootState.routingHistory.back();
        commit("setMedicalCard", {});
        localStorage.removeItem("medicalId");
      });
  },
  updateContactsData({ commit, state }) {
    const personId = state.medicalCard.person.id;
    const initContacts = state.medicalCard.person.contacts;
    const allNewContacts = [
      ...state.contactsData.phones,
      ...state.contactsData.emails,
      ...state.contactsData.networks,
    ];
    let requestDelete = initContacts
      .filter((el) => !allNewContacts.find((newNet) => newNet.id === el.id))
      .map((el) => fetchWrapper.del(`general/contact/${el.id}/delete/`));
    const request = allNewContacts
      .map((network) => {
        let initNetwork = initContacts.find((el) => el.id === network.id);
        if (!network.id) {
          return fetchWrapper.post(`general/contact/create/`, {
            person: personId,
            ...network,
          });
        }
        if (network.id && network.username !== initNetwork.username) {
          return fetchWrapper.post(`general/contact/${network.id}/update/`, {
            person: personId,
            username: network.username,
            kind: network.kind,
          });
        }
        return Promise.resolve();
      })
      .concat(requestDelete);

    return Promise.allSettled(request).then(() =>
      actions.getMedicalCardData({ commit })
    );
  },
};

const mutations = {
  setMedicalCard(state, card) {
    state.medicalCard = card;
  },
  setBasicData(state) {
    state.basicData = { ...this.getters.getBasicData };
  },
  setContactsData(state) {
    state.contactsData = { ...this.getters.getContactsData };
  },
  setDocumentData(state, data, rootState) {
    const passport = data?.identity_document.find(
      (el) => el.kind === "PASSPORT"
    );
    state.documents = {
      passport: {
        id: passport?.id,
        series: passport?.series,
        number: passport?.number,
        issued_by_org: passport?.issued_by_org,
        issued_by_org_code: passport?.issued_by_org_code,
        issued_by_date: passport?.issued_by_date,
        photo: passport?.photo ? rootState.getUrl + passport.photo : "",
      },
      insurance_number: {
        insurance_number: data?.insurance_number,
        photo_insurance_number: data?.photo_insurance_number
          ? rootState.getUrl + data.photo_insurance_number
          : "",
      },
      tax_identification_number: {
        tax_identification_number: data?.tax_identification_number,
        photo_tax_identification_number: data?.photo_tax_identification_number
          ? rootState.getUrl + data?.photo_tax_identification_number
          : "",
      },
    };
  },
};

export default {
  state,
  getters,
  actions,
  mutations,
};
