<template>
  <div>
    <q-btn
      :disable="disableAllButtons || prepareModelLoading"
      padding="6px"
      class="q-ml-sm"
      flat
      :label="get(buttonSettings, 'props.label')"
      :color="get(buttonSettings, 'props.color')"
      :icon="get(buttonSettings, 'props.icon')"
      @click="printStatement"
    >
      <slot />
    </q-btn>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { prepareStatementData } from '@utils/statement-print';
import { BaseCardCommon } from '@/interfaces';
import cloneDeep from 'lodash/cloneDeep';
import get from 'lodash/get';
import {
  createDictionaryMapFromSchema,
  setValuesFromDictionaries,
} from '@utils/dict-map-utils';
import PrinterService from '@services/printer/index';
import { Schema } from '@devsun/eva-models';
import { ServiceFileNameFactory } from '@utils/file/ServiceFileNameFactory';
import { Document } from '@interfaces/entities/Document/Document';
import { notifyError, notifySuccess } from '@utils/notify';

@Component({
  methods: {
    get,
  },
})
export default class PrintStatementButton extends Vue {
  @Prop({}) private common?: BaseCardCommon;
  @Prop({}) private model?: any;
  @Prop({}) private disableAllButtons?: boolean;
  @Prop({}) private userTask?: any;
  @Prop({}) private buttonSettings?: ButtonSettings;

  adoptedModel = {};
  prepareModelLoading = false;

  protected get serviceCard() {
    return this.$store.getters['registryService/services/servicesCard'];
  }

  get schema(): Schema.MetaClassSchemaRaw {
    return this.$store.getters['utils/cards/getSchemaByPath']('data');
  }

  get authorSchema(): Schema.MetaClassSchemaRaw {
    return this.$store.getters['utils/cards/getSchemaByPath']('authorSchema');
  }

  @Watch('model', { immediate: true })
  async prepareModel() {
    this.prepareModelLoading = true;
    await this.setAdoptedModel();
    this.prepareModelLoading = false;
  }

  async setAdoptedModel(): Promise<void> {
    const dictionaryMap = {
      ...createDictionaryMapFromSchema(this.schema),
      ...createDictionaryMapFromSchema(this.authorSchema),
    };

    const adoptedModel = await setValuesFromDictionaries(
      cloneDeep(this.model),
      dictionaryMap
    );
    this.adoptedModel = adoptedModel;
  }

  async printStatement() {
    this.$recordActivity({
      buttonCode: 'application_print',
      extraInfo: {
        previewInfo: [
          {
            value: this.model?.common?.orderId,
            label: 'номер',
          },
        ],
      },
    });
    const document = this.serviceCard.documents.find(
      (doc: Document) =>
        doc.source === 'printApplication' &&
        doc.goal === get(this.adoptedModel, 'statement.goal', 1)
    );
    const documentName = ServiceFileNameFactory.create(this.model, document);
    PrinterService.fetchConvertedFileSync(
      await prepareStatementData(
        this.schema,
        this.authorSchema,
        this.adoptedModel,
        this.serviceCard,
        false,
        documentName
      )
    )
      .then(() => {
        notifySuccess(
          this.$t('statements.printer.done').toString(),
          'check_circle_outline'
        );
      })
      .catch(() => {
        notifyError(this.$t('statements.printer.fail').toString());
      });
  }
}

declare interface ButtonSettings {
  props: {
    color?: string;
    disable?: boolean;
    label?: string;
    loading?: boolean;
    icon?: string;
    visible?: boolean;
  };
}
</script>
