<template lang="pug">
  medical-form-wrapper(
    title="Страховка",
    :is-loading-data="isLoadingData",
    :is-check-change="isCheckChange",
    :is-edit="isEdit",
    :open-edit="openEdit",
    :save="saveChange",
    :cancel="cancelEdit"
  )
    .form-wrap.gap-24.w-full
      .flex.flex-col.gap-4(v-for="insurance in insuranceConfig", :key="insurance.insuranceKey")
        .font-semibold.text-sm.whitespace-nowrap {{insurance.insuranceLabel}}
        .flex.w-full.justify-between.items-center.gap-4(
          v-for="field in insurance.fields",
          :key="insurance.insuranceKey + field.key",
          :style="{marginTop: field.label === 'Документы' ? '20px' : null}"
        )
          .label-field.font-sm.text-sm.whitespace-nowrap {{`${field.label} :`}}
          .avatar-field.flex.gap-3.items-center.h-10.w-10(v-if="field.type === 'avatar'")
            .flex.w-10.h-10.relative(v-if="basic[insurance.insuranceKey][field.key]?.photo")
              img.rounded.avatar.object-cover(
                :src="basic[insurance.insuranceKey][field.key].photo",
                alt="AV"
              )
              q-badge.delete(
                floating,
                v-if="isEdit",
                @click="removeImage(insurance?.insuranceKey, field?.key)",
                rounded
              )
                q-icon(name="app:icon-cancel", size="8px")
            .replace-photo.font-medium.text-base.cursor-pointer(
              v-if="isEdit",
              @click="changeModal(insurance.insuranceKey)"
            ) {{ basic[insurance.insuranceKey][field.key]?.photo ? "Заменить фото" : "Добавить фото" }}
            base-modal(
              v-if="insurance.insuranceKey === photoId"
              v-model="showModal",
              title="Загрузить изображение"
            )
              base-upload-photo(
                :key="insurance.insuranceKey"
                v-model="basic[photoId][field.key]"
                :confirm-upload="confirmChangePhoto" 
              )
          .flex.h-10.relative(
            v-else-if="field.type === 'select'",
            @click="openModalCategories"
          )
            q-field.items-center.cursor-pointer(
              standout,
              :readonly="!isEdit",
              :outlined="isEdit",
            ) {{selectCategory(basic[insurance.insuranceKey][field.key])}}
            base-modal(
              default-padding,
              hide-header,
              v-model="showModalCategories",
              title="Категории"
            )
              base-category-selection(
                :benefit-data="benefitData",
                :close-modal-categories="closeModalCategories",
                :save-categories="saveCategories",
                :show-modal="showModalCategories",
                :basic="basic.benefit",
                @search="filterDataBenefit"
              )
            .flex.font-medium.text-smm.absolute.top-11(
              v-if="basic?.benefit[insurance?.discount]",
              :style="{color: 'var(--font-grey-color)'}"
            )
              span Процент скидки: 
              span(
                :style="{color: 'var(--font-dark-blue-color)'}"
              ) {{"\xa0" + basic?.benefit[insurance?.discount] + "%"}}
          .input-container.flex.flex-col.relative(v-else)
            base-input(
              v-model="basic[insurance.insuranceKey][field.key]",
              @update:model-value="checkChangeInput",
              :mask="field?.inputMask",
              :readonly="!isEdit",
              :standout="!isEdit",
              :outlined="isEdit",
              :type="field.type",
              text-color="black"
            )
              q-icon.my-auto.text-lg.label-field.cursor-pointer(
                size="18px",
                name="app:icon-copy",
                v-if="checkCopiedFields(field.key, basic[insurance.insuranceKey])",
                @click="copyValue(basic[insurance.insuranceKey][field.key])"
              )
</template>

<script>
import { baseInsuranceForm } from "@/pages/newMedicalCard/utils/medicalConfig";
import { mapGetters, mapState } from "vuex";
import MedicalFormWrapper from "@/pages/newMedicalCard/components/MedicalFormWrapper.vue";
import BaseAvatar from "@/components/base/BaseAvatar.vue";
import { fetchWrapper } from "@/shared/fetchWrapper";
import BaseInput from "@/components/base/BaseInput.vue";
import BaseModal from "@/components/base/BaseModal.vue";
import BaseUploadPhoto from "@/components/base/BaseUploadPhoto.vue";
import BaseCategorySelection from "@/components/base/BaseCategorySelection.vue";
import { checkChangeData } from "@/shared/utils/changesObjects";
import { addNotification } from "@/components/Notifications/notificationContext";

export default {
  name: "InsuranceForm",
  components: {
    MedicalFormWrapper,
    BaseAvatar,
    BaseInput,
    BaseModal,
    BaseUploadPhoto,
    BaseCategorySelection,
  },
  data() {
    return {
      insuranceConfig: baseInsuranceForm,
      isCheckChange: false,
      isEdit: false,
      isLoadingData: false,
      showModal: false,
      showModalCategories: false,
      photoId: "",
      copiedFields: ["series", "number"],
    };
  },
  computed: {
    ...mapGetters({
      url: "getUrl",
      avatar: "getAvatar",
      initDataBasic: "getBasicData",
    }),
    ...mapState({
      basic: (state) => state.medical.basicData,
      benefitData: (state) => state.medical.benefitData,
    }),
  },
  methods: {
    filterDataBenefit(text) {
      if (text.length > 1) {
        localStorage.setItem("searchBenefit", text);
        this.$store.dispatch("getBenefitDataSearch");
      } else {
        this.$store.dispatch("getBenefitData");
        localStorage.removeItem("searchBenefit", text);
      }
    },
    removeImage(docKey, field) {
      this.basic[docKey][field] = {};
      this.isCheckChange = true;
    },
    checkCopiedFields(key, item) {
      return (
        !this.isEdit &&
        this.copiedFields.some((elem) => elem === key) &&
        item[key]
      );
    },
    copyValue(text) {
      navigator.clipboard.writeText(text);
    },
    selectCategory(str) {
      if (str) return str.length > 30 ? str.substr(0, 30) + "..." : str;
      return "Выберите категорию";
    },
    saveCategories(obj) {
      this.showModalCategories = false;
      this.basic.benefit.id = obj.id;
      this.basic.benefit.name = obj.name;
      this.basic.benefit.discount = obj.discount;
      this.isCheckChange = true;
    },
    changeModal(id) {
      this.photoId = id;
      this.showModal = true;
    },
    closeModalCategories() {
      this.showModalCategories = false;
    },
    openModalCategories() {
      if (this.isEdit) this.showModalCategories = true;
    },
    checkChangeInput() {
      this.isCheckChange =
        JSON.stringify(this.initDataBasic) !== JSON.stringify(this.basic)
          ? true
          : false;
    },
    confirmChangePhoto() {
      this.showModal = false;
      this.isCheckChange = true;
    },

    updateBasicData() {
      let insuranceDMS = this.basic.insuranceDMS;
      let insuranceOMS = this.basic.insuranceOMS;
      let personal = this.basic.personalData;
      let benefit = this.basic.benefit;

      const insuranceFormDataDMS = new FormData();
      const insuranceFormDataOMS = new FormData();
      const benefitFormData = new FormData();

      if (insuranceDMS.series && insuranceDMS.number) {
        for (let key in insuranceDMS) {
          if (insuranceDMS[key] && key !== "photo" && key !== "id")
            insuranceFormDataDMS.append(key, insuranceDMS[key]);
        }
      }
      if (
        insuranceDMS.photo.file &&
        insuranceDMS.photo.photo !== this.initDataBasic.insuranceDMS.photo.photo
      )
        insuranceFormDataDMS.append("photo", insuranceDMS.photo.file[0]);

      if (insuranceOMS.series && insuranceOMS.number) {
        for (let key in insuranceOMS) {
          if (insuranceOMS[key] && key !== "photo" && key !== "id")
            insuranceFormDataOMS.append(key, insuranceOMS[key]);
        }
      }
      if (
        insuranceOMS.photo.file &&
        insuranceOMS.photo.photo !== this.initDataBasic.insuranceOMS.photo.photo
      )
        insuranceFormDataOMS.append("photo", insuranceOMS.photo.file[0]);

      const request = Object.keys(this.basic).map((key) => {
        if (
          key === "insuranceDMS" &&
          !insuranceDMS?.id &&
          insuranceDMS.series &&
          insuranceDMS.number
        ) {
          insuranceFormDataDMS.append("title", "DMS");
          insuranceFormDataDMS.append("person", personal.id);
          return this.sendData(
            `general/insurance_policy/create/`,
            insuranceFormDataDMS
          );
        }
        if (
          key === "insuranceOMS" &&
          !insuranceOMS?.id &&
          insuranceOMS.series &&
          insuranceOMS.number
        ) {
          insuranceFormDataOMS.append("title", "OMS");
          insuranceFormDataOMS.append("person", personal.id);
          return this.sendData(
            `general/insurance_policy/create/`,
            insuranceFormDataOMS
          );
        }
        if (
          checkChangeData(this.initDataBasic.insuranceDMS, insuranceDMS) &&
          key === "insuranceDMS" &&
          insuranceDMS.id
        ) {
          this.checkedPhoto(
            insuranceDMS.photo,
            insuranceDMS.id,
            "insurance_policy",
            "delete_photo"
          );
          insuranceFormDataDMS.append("title", "DMS");
          return this.sendData(
            `general/insurance_policy/${insuranceDMS.id}/update/`,
            insuranceFormDataDMS
          );
        } else if (
          insuranceDMS.id &&
          (!insuranceDMS.series || !insuranceDMS.number)
        ) {
          this.addErrorNotification(
            "Ошибка заполнения формы ДМС",
            "Пожалуйста заполните все поля"
          );
        }
        if (
          checkChangeData(this.initDataBasic.insuranceOMS, insuranceOMS) &&
          key === "insuranceOMS" &&
          insuranceOMS.id
        ) {
          this.checkedPhoto(
            insuranceOMS.photo,
            insuranceOMS.id,
            "insurance_policy",
            "delete_photo"
          );
          insuranceFormDataOMS.append("title", "OMS");
          return this.sendData(
            `general/insurance_policy/${insuranceOMS.id}/update/`,
            insuranceFormDataOMS
          );
        } else if (
          insuranceOMS.id &&
          (!insuranceOMS.series || !insuranceOMS.number)
        ) {
          this.addErrorNotification(
            "Ошибка заполнения формы ОМС",
            "Пожалуйста заполните все поля"
          );
        }
        if (
          checkChangeData(this.initDataBasic.benefit, benefit) &&
          key === "benefit"
        ) {
          this.checkedPhoto(
            benefit.photo,
            personal.id,
            "person",
            "delete_photo_benefit"
          );
          fetchWrapper.post(`general/person/${personal.id}/update/`, {
            benefit: benefit.id,
          });
          if (
            benefit.photo.file &&
            benefit.photo.photo !== this.initDataBasic.benefit.photo.photo
          ) {
            benefitFormData.append("photo_benefit", benefit.photo.file[0]);
            return this.sendData(
              `general/person/${personal.id}/update/`,
              benefitFormData
            );
          }
        }
      });
      return request;
    },
    checkedPhoto(photo, id, key, title) {
      if (!photo?.photo) {
        return this.delPhoto(`general/${key}/${id}/${title}/`);
      }
    },
    addErrorNotification(title, message) {
      addNotification(title + message, title, message, "error", 5000);
    },

    async sendData(url, body) {
      return await fetchWrapper.post(url, body, "formData");
    },
    async delPhoto(url) {
      return await fetchWrapper.del(url);
    },
    cancelEdit() {
      this.$store.dispatch("returnInitData");
      this.isEdit = false;
      this.isCheckChange = false;
    },
    openEdit() {
      this.isEdit = true;
    },
    saveChange() {
      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;
        });
    },
  },
  watch: {
    showModalCategories: {
      immediate: true,
      handler(newVal) {
        if (newVal) this.$store.dispatch("getBenefitData");
      },
    },
  },
};
</script>

<style lang="sass" scoped>
.q-field :deep(.q-field__control)
  min-height: 40px
  width: 302px
  align-items: center
  background: rgba(0, 0, 0, 0.05)
  color: var(--font-dark-blue-color)

.avatar-field
  min-width: 302px

.avatar
  height: 100%

.input-container
  width: 302px

.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)

.q-badge
  padding: 4px
  cursor: pointer
.delete
  background-color: var(--btn-red-color)
</style>
