<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"
        )
          .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
              img.avatar.object-cover(
                v-if="basic[insurance.insuranceKey][field.key]?.photo",
                :src="basic[insurance.insuranceKey][field.key].photo",
                alt="AV"
              )
            .replace-photo.font-medium.text-base.cursor-pointer(
              v-if="isEdit",
              @click="changeModal(insurance.insuranceKey)"
            ) {{ basic[insurance.insuranceKey][field.key] ? "Заменить фото" : "Добавить фото"}}
            base-modal(
              v-model="showModal",
              title="Загрузить изображение"
            )
              base-upload-photo(
                :key="insurance.insuranceKey"
                v-model="basic[photoId][field.key]"
                :confirm-upload="confirmChangePhoto" 
              )
          .flex.flex-col.relative(v-else)
            base-input(
              v-model="basic[insurance.insuranceKey][field.key]",
              @update:model-value="checkChangeInput",
              :disabled="!isEdit",
              :standout="!isEdit",
              :outlined="isEdit",
              :type="field.type", 
              :width="300",
              text-color="black"
            )
            .flex.font-medium.text-smm.absolute.top-10(
              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] + "%"}}
</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";

export default {
  name: "InsuranceForm",
  components: {
    MedicalFormWrapper,
    BaseAvatar,
    BaseInput,
    BaseModal,
    BaseUploadPhoto,
  },
  data() {
    return {
      insuranceConfig: baseInsuranceForm,
      isCheckChange: false,
      isEdit: false,
      isLoadingData: false,
      showModal: false,
      photoId: "",
    };
  },
  computed: {
    ...mapGetters({
      url: "getUrl",
      avatar: "getAvatar",
      initDataBasic: "getBasicData",
    }),
    ...mapState({
      basic: (state) => state.medical.basicData,
    }),
  },
  methods: {
    changeModal(id) {
      this.photoId = id;
      this.showModal = 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 benefit = this.basic.benefit;

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

      if (
        insuranceDMS.photo.file &&
        insuranceDMS.photo.photo !== this.initDataBasic.insuranceDMS.photo.photo
      )
        insuranceFormDataDMS.append("photo", insuranceDMS.photo.file[0]);

      if (insuranceDMS.series)
        insuranceFormDataDMS.append("series", insuranceDMS.series);

      if (insuranceDMS.number)
        insuranceFormDataDMS.append("number", insuranceDMS.number);

      if (
        insuranceOMS.photo.file &&
        insuranceOMS.photo.photo !== this.initDataBasic.insuranceOMS.photo.photo
      )
        insuranceFormDataOMS.append("photo", insuranceOMS.photo.file[0]);

      if (insuranceOMS.series)
        insuranceFormDataOMS.append("series", insuranceOMS.series);

      if (insuranceOMS.number)
        insuranceFormDataOMS.append("number", insuranceOMS.number);

      const request = Object.keys(this.basic).map((key) => {
        if (key === "insuranceDMS") {
          insuranceFormDataDMS.append(
            "organization",
            insuranceDMS.organization
          );
          insuranceFormDataDMS.append("title", "DMS");
          return fetchWrapper.post(
            `general/insurance_policy/${insuranceDMS.id}/update/`,
            insuranceFormDataDMS,
            "formData"
          );
        }
        if (key === "insuranceOMS") {
          insuranceFormDataOMS.append(
            "organization",
            insuranceDMS.organization
          );
          insuranceFormDataOMS.append("title", "OMS");
          return fetchWrapper.post(
            `general/insurance_policy/${insuranceOMS.id}/update/`,
            insuranceFormDataOMS,
            "formData"
          );
        }
      });
      return request;
    },
    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;
        });
    },
  },
};
</script>

<style lang="sass" scoped>
.select
  width: 324px

.avatar-field
  min-width: 324px

.avatar
  height: 100%

.replace-photo
  color: var(--btn-blue-color)

.input
  color: purple

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