<template lang="pug">
  medical-form-wrapper(
    title="Основные данные"
    :is-check-change="isCheckChange" 
    :is-loading-data="isLoadingData" 
    :is-edit="isEdit" 
    :save="saveChange" 
    :cancel="cancelEdit" 
    :open-edit="openEdit"
    )
    q-form.form-wrap.gap-24.w-full(ref="formBasicData")
      .flex.flex-col.gap-4(v-for="data in configData")
        .font-semibold.text-sm.whitespace-nowrap {{data.dataLabel}}
        .flex.w-full.justify-between.items-center.gap-4(v-for="field in data.fields")
          .label-field.font-sm.text-sm.whitespace-nowrap {{`${field.label} :`}}
          .avatar-field.flex.gap-3.items-center(v-if="field.type === 'avatar'")
            base-avatar(:size="40")
              img.avatar.object-cover(
                v-if="basic[data.dataKey][field.key]?.photo" 
                :src="basic[data.dataKey][field.key].photo" 
                alt="AV"
                )
              span(v-else) {{ avatar }}
            .replace-photo.font-medium.text-base.cursor-pointer(v-if="isEdit" @click="showModal = true") Заменить фото
            base-modal(v-model="showModal" title="Загрузить изображение")
              base-upload-photo(
                v-model="basic[data.dataKey][field.key]"
                :confirm-upload="confirmCahngeAvatar" 
              )
          .select(v-else-if="field.type === 'select'")
            base-select(
              :readonly="!isEdit"
              v-model="basic[data.dataKey][field.key]"
              @update:model-value="checkChangeInput"
              :hide-dropdown-icon="!isEdit"
              :outlined="isEdit"
              :standout="!isEdit"
              :items="genderOptions"
              bg-color="#e9e9f6"
              )
          base-input(
            v-else 
            :readonly="!isEdit" 
            v-model="basic[data.dataKey][field.key]"
            @update:model-value="checkChangeInput"
            :type="field.type"
            :name="field.key" 
            :width="278" 
            :standout="!isEdit" 
            :outlined="isEdit"
            no-error-icon
            :rule="field.rules"
            text-color="black"
            )
</template>

<script>
import BaseSelect from "@/components/base/BaseSelect.vue";
import BaseInput from "@/components/base/BaseInput.vue";
import BaseAvatar from "@/components/base/BaseAvatar.vue";
import BaseModal from "@/components/base/BaseModal.vue";
import BaseUploadPhoto from "@/components/base/BaseUploadPhoto.vue";
import MedicalFormWrapper from "@/pages/newMedicalCard/components/MedicalFormWrapper.vue";
import TheNotificationProvider from "@/components/Notifications/TheNotificationProvider.vue";
import { getFieldsNameUnvalidated } from "@/shared/utils/changesObjects";
import { addNotification } from "@/components/Notifications/notificationContext";
import { getRequestChangeData } from "@/shared/utils/wrapperRequestChangeData";
import { checkChangeData } from "@/shared/utils/changesObjects";
import { fetchWrapper } from "@/shared/fetchWrapper";
import moment from "moment";
import {
  baseDataForm,
  genderOptions,
  errorMap,
} from "@/pages/newMedicalCard/utils/medicalConfig.js";
import { mapGetters, mapState } from "vuex";

export default {
  name: "BasicDataForm",
  components: {
    MedicalFormWrapper,
    BaseInput,
    BaseAvatar,
    BaseSelect,
    BaseModal,
    BaseUploadPhoto,
    TheNotificationProvider,
  },
  data() {
    return {
      showModal: false,
      isEdit: false,
      isLoadingData: false,
      isCheckChange: false,
      genderOptions: genderOptions,
      configData: baseDataForm,
      errorMapBasic: errorMap,
    };
  },
  computed: {
    ...mapGetters({
      url: "getUrl",
      avatar: "getAvatar",
      initDataBasic: "getBasicData",
    }),
    ...mapState({
      basic: (state) => state.medical.basicData,
    }),
  },
  methods: {
    checkChangeInput() {
      this.isCheckChange = checkChangeData(this.initDataBasic, this.basic);
    },
    confirmCahngeAvatar() {
      this.showModal = false;
      this.isCheckChange = true;
    },
    cancelEdit() {
      this.$store.dispatch("returnInitData");
      this.isEdit = false;
      this.isCheckChange = false;
    },
    updateBasicData() {
      let registration = this.basic.registrationAddress;
      let residence = this.basic.residenceAddress;
      let personal = this.basic.personalData;
      const personalFormData = new FormData();
      personalFormData.append(
        "full_name",
        `${personal.last_name} ${personal.first_name} ${personal.patronymic}`
      );
      if (personal.birth_date) {
        personalFormData.append(
          "birth_date",
          moment(personal.birth_date).format("YYYY-MM-DD")
        );
      }
      if (personal.gender) {
        personalFormData.append("gender", personal.gender?.id);
      }
      if (
        personal.photo.file &&
        personal.photo.photo !== this.initDataBasic.personalData.photo.photo
      ) {
        personalFormData.append("photo", personal.photo.file[0]);
      }
      const request = Object.keys(this.basic).map((key) => {
        if (key === "personalData") {
          return fetchWrapper.post(
            `general/person/${personal.id}/update/`,
            personalFormData,
            "formData"
          );
        }
        if (key === "registrationAddress") {
          let createRegistration = {
            person: personal.id,
            registration_flg: true,
            ...registration,
          };
          return getRequestChangeData(
            createRegistration,
            registration,
            this.initDataBasic[key],
            "address",
            registration.id
          );
        }
        if (key === "residenceAddress") {
          let createResidence = {
            person: personal.id,
            residence_flg: true,
            ...residence,
          };
          return getRequestChangeData(
            createResidence,
            residence,
            this.initDataBasic[key],
            "address",
            residence.id
          );
        }
      });
      return request;
    },
    saveChange() {
      const form = this.$refs.formBasicData;
      form.validate().then((validate) => {
        if (validate) {
          this.isLoadingData = true;
          let updateBasic = this.updateBasicData();
          Promise.allSettled(updateBasic)
            .then(() => this.$store.dispatch("getMedicalCardData"))
            .then(() => {
              this.isLoadingData = false;
              this.isEdit = false;
              this.isCheckChange = false;
            });
        } else {
          getFieldsNameUnvalidated(form).forEach((errorKey) => {
            addNotification(
              this.errorMapBasic[errorKey].title,
              this.errorMapBasic[errorKey].title,
              this.errorMapBasic[errorKey].error,
              "error",
              5000
            );
          });
        }
      });
    },
    openEdit() {
      this.isEdit = true;
    },
  },
};
</script>

<style lang="sass" scoped>
.select
  width: 302px
.avatar-field
  min-width: 302px
.avatar
  height: 100%
  border-radius: 50%
.replace-photo
  color: var(--btn-blue-color)
.form-wrap
  display: grid
  grid-template-columns: repeat(3, 1fr)
  grid-template-rows: repeat(1, 1fr)
  @media(max-width: 1900px)
    grid-template-columns: repeat(2, 1fr)
    grid-template-rows: repeat(2, 1fr)
  @media(max-width: 1320px)
    grid-template-columns: repeat(1, 1fr)
    grid-template-rows: repeat(3, 1fr)
.label-field
  color: var(--font-grey-color)
</style>
