<i18n>
{
  "en": {
    "PaymentsQuittance": {
      "quittance": "Quittance with charge",
      "title": "Charges request",
      "type": "type",
      "narrative": "Narrative"
    }
  },
  "ru": {
    "PaymentsQuittance": {
      "quittance": "Сквитировать с начислением",
      "title": "Квитировать с начислением",
      "type": "Выберите тип запроса *",
      "narrative": "Назначение",
      "amount": "Сумма",
      "payerId": "Идентификатор плательщика",
      "paymentId": "УИП",
      "supplierBillId": "УИН",
      "btnDisableCharge": "Нет зарегистрированных начислений. Сначала зарегистрируйте начисление в ГИС ГМП",
      "btnDisablePayment": "Не выбраны платежи"
    }
  }
}
</i18n>

<template>
  <q-dialog v-model="dialog" @hide="closeDialogWindow" persistent>
    <q-card class="no-shadow" style="max-width: 80vw; width: 700px;">
      <q-form ref="paymentRequestForm" greedy @submit="handler">
        <q-card-section>
          <div class="text-h6">
            {{ $t('PaymentsQuittance.title') }}
          </div>
        </q-card-section>
        <q-card-section class="q-p row justify-center">
          <div class="col-11 q-gutter-sm">
            <q-select
              ref="charges"
              v-model="model.charge"
              :options="charges"
              label="Выберите начисление *"
              class="q-mb-sm"
              dense
              filled
              :rules="[rulesRequired]"
              hide-bottom-space
              options-dense
              option-value="supplierBillId"
              option-label="supplierBillId"
            />
            <div class="flex no-wrap" v-if="model.charge">
              <q-card class="card flex column q-mt-md q-mx-sm q-pa-lg">
                <p class=" flex justify-between">
                  <b>Назначение:</b>
                  <span>{{ model.charge.billFor }}</span>
                </p>
                <p class=" flex justify-between">
                  <b>Дата начисления:</b>
                  <span class="text-right block">{{ chargeDate }}</span>
                </p>
                <p class="q-mt-auto flex justify-between">
                  <b>КБК:</b>
                  <span class="text-right block">{{ model.charge.KBK }}</span>
                </p>
                <p class="q-mb-none flex justify-between">
                  <b>Сумма начисления:</b>
                  <span class="text-right block">
                    {{ model.charge.totalAmount }} р.
                  </span>
                </p>
              </q-card>
              <q-card class="card flex column q-mt-md q-mx-sm q-pa-lg">
                <p class=" flex justify-between">
                  <b>УИП:</b>
                  <span class="text-right block q-ml-auto">{{ payment[0].paymentId }}</span>
                </p>
                <p class=" flex justify-between">
                  <b>Дата платежа:</b>
                  <span class="text-right block">{{ paymentDate }}</span>
                </p>
                <p class="q-mt-auto flex justify-between">
                  <b>КБК:</b>
                  <span class="text-right block">{{ payment[0].kbk }}</span>
                </p>
                <p class="q-mb-none flex justify-between">
                  <b>Сумма платежа:</b>
                  <span class="text-right inline-block">
                    {{ payment[0].amount }} р.
                  </span>
                </p>
              </q-card>
            </div>

          </div>
        </q-card-section>

        <q-card-actions class="q-pa-md" align="right">
          <q-btn
            :disable="false"
            :label="'Отмена'"
            outline
            unelevated
            color="primary"
            @click="closeDialogWindow"
          />
          <q-btn
            type="submit"
            :disable="!model.charge"
            :label="'Сквитировать'"
            unelevated
            color="primary"
          />
        </q-card-actions>
      </q-form>
      <q-inner-loading :showing="loading">
        <q-spinner-gears color="primary" size="50px" />
      </q-inner-loading>
    </q-card>
  </q-dialog>
</template>

<script lang="ts">

import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import { notifyError, notifyInfo } from '@/utils/notify';
import { BaseCardCommon } from '@/interfaces';
import { convertDateFromBackendFormat, DateFormat } from '@utils/format-date';
import { CardNeedToUpdateType } from '@constants/models/Card';
import { Payment, Charge } from './PaymentsSearch.vue'
import { QSelect } from 'quasar';
import { get } from 'lodash';

type Model = {
  charge?: Charge
}

@Component({})
export default class PaymentsQuittanceDialog extends Vue {
  @Prop() common?: BaseCardCommon;
  @Prop() charges!: Charge[];
  @Prop() payment!: Payment[];

  private dialog = false;
  private loading = false;
  private model: Model = {};

  @Watch('payment')
  paymentSelected(payment: Payment[]): void {
    if (!payment.length) return;
    this.dialog = true;
  }
  
  get disableQuittanceButton(): boolean {
    return !(!!this.payment?.length && !!this.charges?.length);
  }

  get paymentDate(): string {
    return convertDateFromBackendFormat(
      this.payment[0].paymentDate,
      DateFormat.date
    );
  }

  get chargeDate(): string {
    return convertDateFromBackendFormat(
      this.model?.charge?.billDate as string,
      DateFormat.date
    );
  }

  @Watch('model.charges')
  isChargeSelected(val: []): void {
    if (val?.length) {
      const charge = this.$refs.charges as QSelect;
      charge.hidePopup();
    }
  }

  openDialogWindow(): void {
    this.dialog = true;
  }

  closeDialogWindow(): void {
    this.dialog = false;
  }

  beforeDestroy(): void {
    this.$emit('clear');
  }

  async handler(): Promise<void> {
    await this.dispatchQuittance();
    this.closeDialogWindow();
  }

  private async dispatchQuittance(): Promise<void> {
    this.loading = true;
    const sendData = {
      applicationId: this.common?.id,
      chargeId: this.model.charge?.id,
      paymentReceivedIdList: [this.payment[0].id],
      action: 'reconcile',
    }
    const { traceId } = await this.$store
      .dispatch('wf/processes/dispatchProcess', {
        processKey: 'PaymentsQuittancesProcess',
        data: sendData,
      })
      .catch((e) => notifyError(e.toString()))
      .finally(() => {
        delete this.model.charge;
        this.loading = false;
        notifyInfo('Запрос отправлен');
      })
    if (traceId) {
      const handler = (e: any) => {
        const data = JSON.parse(get(e, 'data', '{}'));
        if (data.traceId === traceId) {
          this.$store.commit(
            'utils/cards/needToUpdate',
            CardNeedToUpdateType.MODEL
          );
          this.$websockets.removeListener(handler);
        }
      };
      this.$websockets.addListener(handler);
    }
  }

  rulesRequired(value: string) {
    return !!value || this.$t('validation.basic.required');
  }
}
</script>
<style lang="sass">
.card 
  width: 50%
  min-width: 30%
  font-size: 0.75rem
</style>