<template>
  <q-card
    v-if="common.active === 'export' && !loadingCard && card"
    class="q-pa-lg q-gutter-y-md q-mx-md no-border-radius q-mt-none no-shadow"
  >
    <div v-if="!showMapping">
      <q-btn
        class="q-mr-auto"
        @click="showMapping = true"
        :label="$t('btn.createMapping')"
        color="white"
        text-color="primary"
        outline
      />
    </div>

    <div v-if="showMapping">
      <StatementsExportMapping
        card-title="Маппинг выгрузки заявлений"
        v-model="mapping.attrList"
        @commonModels="commonModels"
        @save="saveMapping"
      />
      <div v-if="card.mapping">
        <q-btn
          type="button"
          icon="delete"
          color="primary"
          label="Удалить маппинг"
          @click="() => (isDeleteModalVisible = true)"
        />
      </div>
    </div>

    <q-dialog class="full-width" v-model="isDeleteModalVisible">
      <q-card class="q-pa-md">
        <ConfirmationForm
          :input-data="{ title: 'Вы действительно хотите удалить таблицу маппинга?' }"
          @submit="(e, v) => onDeleteSubmit(v.result)"
        />
      </q-card>
    </q-dialog>
  </q-card>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import { BaseCardCommon } from "@/interfaces";
import StatementsExportMapping from "./Export/StatementsExportMapping.vue";
import type { ExtendedService } from "./types/services-types";
import { ServiceMapping, ServiceMappingApi } from "@openapi/registry-service";
import { updateService, unlinkService } from "@services/registry-service";
import { notifyError, notifySuccess } from "@/utils/notify";
import merge from "lodash/merge";
import ConfirmationForm from '@/components/forms/ConfirmationForm.vue';

const serviceMappingApi = new ServiceMappingApi();

const createEmptyMapping = () => ({
  id: '',
  attrList: []
})

@Component({
  components: {
    StatementsExportMapping,
    ConfirmationForm,
  },
})
export default class StatementsExport extends Vue {
  @Prop() common: BaseCardCommon;

  mapping: ServiceMapping = createEmptyMapping();
  showMapping = false;
  isDeleteModalVisible = false;

  async created() {
    if (this.card?.mapping?.id) {
      this.mapping = merge(this.mapping, this.card.mapping);
      this.showMapping = true;
    }
  }

  @Watch("card", { deep: true })
  onCardChange(card: any) {
    if (card.mapping && !this.mapping.id) {
      this.mapping = merge(this.mapping, card.mapping);
      this.showMapping = true;
    }
  }

  get card(): ExtendedService {
    return this.$store.getters["registryService/services/servicesCard"];
  }

  get loadingCard(): boolean {
    return (
      this.$store.getters["registryService/services/servicesLoading"] || false
    );
  }

  openMappingEditor() {
    this.showMapping = !this.showMapping;
  }

  async saveMapping() {
    if (!this.mapping?.id) {
      await this.createMapping();
    } else {
      await this.updateMapping();
    }
  }

  async createMapping() {
    if (!this.mapping) {
      return;
    }
    const { data } = await serviceMappingApi.createServiceMapping([this.mapping]);
    if (data.success) {
      notifySuccess("Маппинг успешно создан");
      this.mapping.id = data.objectIds?.[0] as string;
      this.updateModel();
    }
  }

  async updateMapping() {
    if (!this.mapping) {
      return;
    }
    const { data } = await serviceMappingApi.updateServiceMapping([this.mapping]);
    if (data.success) {
      notifySuccess("Маппинг успешно обновлён");
      this.mapping.id = data.objectIds?.[0] as string;
      this.updateModel();
    }
  }

  onDeleteSubmit(result: boolean) {
    if (result) {
      this.deleteMapping();
    }
    this.isDeleteModalVisible = false;
  }

  async deleteMapping() {
    const { data } = await unlinkService({
      ...this.card,
      mapping: [this.mapping.id],
    });
    if (data.success) {
      const { data } = await serviceMappingApi.deleteServiceMapping([this.mapping.id]);
      if (data.success) {
        notifySuccess("Маппинг успешно удалён");
        this.mapping = createEmptyMapping();
        this.showMapping = false;
      }
    }
  }

  async updateModel() {
    const service = {
      ...this.card,
      mapping: [this.mapping.id],
    };
    try {
      const { data } = await updateService(service);
      if (data.success) {
        notifySuccess("Услуга успешно обновлена");
      }
    } catch (e) {
      if (e instanceof Error) {
        notifyError(e.message);
      }
    }
    this.$store.dispatch("registryService/services/setCardForJson", {
      ...this.card,
      mapping: this.mapping.id,
    });
  }

  commonModels(val: any) {
    this.$emit('commonModels', val);
  }
}
</script>

<i18n>
{
  "en": {
    "title": {
      "create": "Create IDR"
    },
    "label": {
      "interagency": "MZ name",
      "mvz": "Process"
    },
    "btn": {
      "createMapping": "create mapping",
      "editMapping": "edit mapping"

    }
  },
  "ru": {
    "title": {
      "create": "Создать процесс МВЗ"
    },
    "label": {
      "interagency": "Наименование МЗ",
      "mvz": "Наименование"
    },
    "btn": {
      "createMapping": "Создать маппинг",
      "editMapping": "Изменить маппинг"
    }
  }
}
</i18n>
