<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="formContacts")
      .flex.flex-col.gap-4(v-for="(contact, key) in contacts")
        .font-semibold.text-sm.whitespace-nowrap {{configData[key].title}}
        .flex.w-full.justify-between.items-center.gap-4(v-for="(data, index) in contact")
          .label-field.font-sm.text-sm.whitespace-nowrap {{`${configData[key].fieldName} ${index+1} :`}}
          .input-wrapper.items-center.flex.h-10.gap-10px
            .flex(v-if="key === 'networks'")
              .flex.rounded-full.cursor-pointer.items-center.gap-10px.py-1.pl-1.pr-2(
                v-if="data.id || data.filled" 
                @click="() => copyLinkNetwork(data.username)"
                style="background-color: var(--bg-light-grey)"
              )
                q-icon.icon(:name="mapNetworks[data.kind].icon" :class="{old: data.id, new: data.filled}")
                span.text-sm.font-medium {{ mapNetworks[data.kind].title || data.username }}
              .flex.gap-10px(v-else v-click-outside="() => checkNetworksField(index)" :key="key+index")
                base-select-networks(
                  :list-data="Object.values(mapNetworks)"
                  :option-data="data.kind"
                  :choose-option="(e) => chooseNetwork(e, index)"
                  :style-border="true"
                  :size-input="50"
                  )
                base-input.w-full(
                  v-model="data.username"
                  type="text"
                  no-error-icon
                  :name="key"
                  :rule="configData[key].rules"
                  :standout="!isEdit" 
                  :outlined="isEdit" 
                  text-color="black"
                  )
            base-input.w-full( 
              v-else
              :readonly="!isEdit" 
              v-model="data.username"
              :name="key"
              :mask="configData[key].inputMask"
              :rule="configData[key].rules"
              no-error-icon
              @update:model-value="checkChangeInput"
              type="text"  
              :standout="!isEdit" 
              :outlined="isEdit" 
              text-color="black"
              )
            .delete-contact.icon-cancel.text-xxs.cursor-pointer(
              v-if="isEdit" 
              @click="() => deleteContact(key, index)"
              )
        q-btn.ml-2px(
          v-if="isEdit",
          color="primary",
          flat,
          :style="{'font-weight': 500, width: '104px', height: '24px'}",
          no-caps,
          padding="0",
          @click="(e) => addNewContact(e, key)"
        )
          q-icon(name="app:icon-plus", size="12px", left)
          span Добавить
</template>

<script>
import MedicalFormWrapper from "@/pages/newMedicalCard/components/MedicalFormWrapper.vue";
import BaseInput from "@/components/base/BaseInput.vue";
import BaseSelectNetworks from "@/components/base/BaseSelectNetworks.vue";
import { mapNetworks } from "@/pages/newMedicalCard/utils/medicalConfig";
import TheNotificationProvider from "@/components/Notifications/TheNotificationProvider.vue";
import { addNotification } from "@/components/Notifications/notificationContext";
import {
  checkChangeData,
  getFieldsNameUnvalidated,
} from "@/shared/utils/changesObjects";
import { contactsDataForm } from "@/pages/newMedicalCard/utils/medicalConfig";
import { getRequestArrayData } from "@/shared/utils/wrapperRequestChangeData";
import { mapState, mapGetters } from "vuex";

export default {
  name: "ContactsForm",
  components: {
    MedicalFormWrapper,
    BaseInput,
    BaseSelectNetworks,
    TheNotificationProvider,
  },
  data() {
    return {
      isEdit: false,
      isLoadingData: false,
      isCheckChange: false,
      configData: contactsDataForm,
      mapNetworks: mapNetworks,
    };
  },
  computed: {
    ...mapGetters({
      initContactsData: "getContactsData",
    }),
    ...mapState({
      contacts: (state) => state.medical.contactsData,
      personId: (state) => state.medical.medicalCard.person.id,
      initAllContacts: (state) => state.medical.medicalCard.person.contacts,
    }),
  },
  methods: {
    checkNetworksField(index) {
      if (
        this.contacts.networks[index].kind &&
        this.contacts.networks[index].username
      ) {
        this.contacts.networks[index].filled = true;
      }
    },
    openEdit() {
      this.isEdit = true;
    },
    cancelEdit() {
      this.$store.dispatch("returnInitData");
      this.isEdit = false;
      this.isCheckChange = false;
    },
    updateContacts() {
      const allNewContacts = [
        ...this.contacts.phones,
        ...this.contacts.emails,
        ...this.contacts.networks,
      ];
      const notEmptyContacts = allNewContacts.filter(
        (el) => el.kind && el.username
      );
      return getRequestArrayData(
        this.initAllContacts,
        notEmptyContacts,
        "person",
        this.personId,
        "general",
        "contact"
      );
    },
    saveChange() {
      const form = this.$refs.formContacts;
      form.validate().then((validate) => {
        if (validate) {
          this.isLoadingData = true;
          Promise.allSettled(this.updateContacts())
            .then(() => this.$store.dispatch("getMedicalCardData"))
            .then(() => {
              this.isLoadingData = false;
              this.isEdit = false;
              this.isCheckChange = false;
            });
        } else {
          getFieldsNameUnvalidated(form).forEach((errorKey) => {
            addNotification(
              this.configData[errorKey].title,
              this.configData[errorKey].title,
              this.configData[errorKey].error,
              "error",
              5000
            );
          });
        }
      });
    },
    checkChangeInput() {
      this.isCheckChange = checkChangeData(
        this.initContactsData,
        this.contacts
      );
    },
    chooseNetwork(e, index) {
      this.contacts.networks[index].kind = e.currentTarget.id;
    },
    addNewContact(e, key) {
      if (e.pointerType) {
        if (key === "networks") {
          this.contacts[key].push({
            filled: false,
            kind: this.configData[key]?.kind,
            username: null,
          });
        } else {
          this.contacts[key].push({
            kind: this.configData[key]?.kind,
            username: null,
          });
        }
      }
      this.checkChangeInput();
    },
    deleteContact(key, index) {
      this.contacts[key].splice(index, 1);
      this.checkChangeInput();
    },
    copyLinkNetwork(value) {
      navigator.clipboard.writeText(value);
    },
  },
};
</script>

<style lang="sass" scoped>
.icon
  &.old
    color: var(--btn-blue-color)
  &.new
    color: var(--icon-violet-color)
.input-wrapper
  width: 302px
.form-wrap
  display: grid
  grid-template-columns: repeat(3, 1fr)
  grid-template-rows: repeat(1, auto)
  @media(max-width: 1900px)
    grid-template-columns: repeat(2, 1fr)
    grid-template-rows: repeat(2, auto)
  @media(max-width: 1320px)
    grid-template-columns: repeat(1, 1fr)
    grid-template-rows: repeat(3, auto)
.network-field
  background-color: var(--bg-light-grey)
.label-field
  color: var(--font-grey-color)
.delete-contact
  color: var(--font-grey-color)
.on-left
  margin-right: 10px
.q-btn :deep(.q-ripple)
  display: none
</style>
