<i18n>
{
  "en": {
    "PaymentCard": {
      "type": "Type",
      "code": "Code",
      "DirectoriesTitle": "Directories",
      "regionCode": "region code",
      "KBK": "Kbk",
      "billFor": "bill for",
      "value": "Value",
      "totalAmount": "Total amount",
      "discountType": "Discount type",
      "discountSizePercent": "Discount size percent",
      "discountSize": "Discount size",
      "discountValue": "Discount value",
      "goal": "Goal",
      "applicationStatusForWaitPayment": "Application status for wait payment",
      "applicationStatusForCharge": "Application status for charge",
      "applicationStatusForRegister": "Application status for register",
      "expiryPlusDays": "Expiry plus Days",
      "tableRejectDocTitle": "eject Document",
      "name": "Name",
      "noProcessesResult": "No Processes directories",
      "confirmationMessage": "Are you sure you want to delete the directory?"
    }
  },
  "ru": {
    "PaymentCard": {
      "type": "Тип",
      "code": "Код",
      "DirectoriesTitle": "Платежи",
      "regionCode": "Код региона",
      "Kbk": "КБК платежа",
      "totalAmount": "Cумма платежа",
      "billFor": "Назначение платежа",
      "applicationStatusForCharge": "Cтатус для формирования начисления",
      "discountType": "Тип скидки",
      "discountSizePercent": "Условия оплаты со скидкой",
      "discountSize": "Условия оплаты с фиксированной суммой скидки",
      "discountValue": "Скидка",
      "goal": "Цель",
      "applicationStatusForWaitPayment": "Cтатус для ожидания оплаты начисления",
      "applicationStatusForRegister": "Cтатус для регистрации начисления",
      "expiryPlusDays": "Kоличество дней действия скидки",
      "noProcessesResult": "Платежи не найдены",
      "create": "Новый платеж",
      "confirmationMessage": "Вы уверены, что хотите удалить платеж?"
    }
  }
}
</i18n>

<template>
  <div>
    <div class="flex justify-between q-my-md row" style="width: 100%">
      <div class="text-h6">{{ $t('PaymentCard.DirectoriesTitle') }}</div>
      <q-btn
        v-if="stateAddPayment.includes(state) && canEdit"
        color="primary"
        icon="add_box"
        :label="$t('PaymentCard.create')"
        @click="addPayment"
      />
    </div>

    <div v-if="payments.length">
      <q-table
        :columns="columns"
        :data="payments"
        :pagination.sync="pagination"
        hide-bottom
      >
        <template #header="props">
          <q-tr :props="props">
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              {{ col.label }}
            </q-th>
            <q-th v-if="stateAddPayment.includes(state)" />
          </q-tr>
        </template>
        <template #body="props">
          <q-tr :props="props">
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              {{ col.value }}
            </q-td>
            <q-td v-if="stateAddPayment.includes(state)" auto-width>
              <q-btn
                v-if="canEdit"
                text-color="primary"
                icon="edit"
                flat
                @click="editPayment(props.row)"
              />

              <q-btn
                v-if="canEdit"
                text-color="negative"
                icon="delete"
                flat
                @click="toggleDeleteConfirm(props.row)"
              />
            </q-td>
          </q-tr>
        </template>
      </q-table>
    </div>
    <div v-else class="full-width text-center">
      {{ $t('PaymentCard.noProcessesResult') }}
    </div>

    <PaymentDialog :common="common" @commonModels="commonModels" />

    <q-dialog v-model="deleteConfirm" class="full-width">
      <q-card class="no-shadow full-width">
        <q-card-section>
          <div class="text-h6">{{ $t('PaymentCard.confirmationMessage') }}</div>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn color="primary" label="Удалить" @click="deletePayment" />

          <q-btn
            color="white"
            text-color="primary"
            outline
            label="Отменить"
            @click="toggleDeleteConfirm"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { unlinkService } from '@services/registry-service';
import get from 'lodash/get';
import cloneDeep from 'lodash/cloneDeep';
import { Component, Prop, Vue } from 'vue-property-decorator';
import { BaseCardCommon, BaseCardCommonModels } from '@/interfaces';
import QColumn from '@/types/QColumn';
import PaymentDialog from '@components/cards/services/PaymentDialog.vue';
import { Payment, Service } from '@openapi/registry-service';
import { ServiceExpanded } from '@models/ServiceExpanded';
import { DialogMode } from '@constants/models/Card';
import { notifyError } from '@utils/notify';

@Component({
  components: {
    PaymentDialog,
  },
})
export default class PaymentTable extends Vue {
  @Prop() common: BaseCardCommon;
  @Prop() card: ServiceExpanded;
  @Prop({ default: '' }) regionCode: string;
  @Prop() payments: Payment[];
  @Prop() stateAddPayment: string[];
  @Prop({ default: true }) canEdit: boolean;

  deleteConfirm = false;
  deleteItem: Payment | null;
  pagination = {
    rowsPerPage: 0,
  };

  get columns(): Array<QColumn> {
    const headerStyle = 'font-size: 16px; font-weight: 600';
    return [
      {
        align: 'left',
        field: 'regionCode',
        label: this.$t('PaymentCard.regionCode'),
        name: 'regionCode',
        sortable: false,
        headerStyle,
      },
      {
        align: 'left',
        field: 'billFor',
        label: this.$t('PaymentCard.billFor'),
        name: 'billFor',
        sortable: true,
        style: 'white-space: pre-wrap',
        headerStyle,
      },
      {
        align: 'left',
        field: 'KBK',
        label: this.$t('PaymentCard.Kbk'),
        name: 'KBK',
        sortable: true,
        style: 'white-space: pre-wrap',
        headerStyle,
      },
      {
        align: 'left',
        field: 'totalAmount',
        label: this.$t('PaymentCard.totalAmount'),
        format: (val: number) => `${val || 0} руб.`,
        name: 'totalAmount',
        sortable: true,
        style: 'white-space: pre-wrap',
        headerStyle,
      },
      {
        align: 'left',
        field: 'discountType',
        label: this.$t('PaymentCard.discountType'),
        format: (val: string) => (val ? this.$t(`PaymentCard.${val}`) : ''),
        name: 'discountType',
        sortable: true,
        style: 'white-space: pre-wrap',
        headerStyle,
      },
      {
        align: 'left',
        field: 'discountValue',
        label: this.$t('PaymentCard.discountValue'),
        name: 'discountValue',
        sortable: true,
        style: 'white-space: pre-wrap',
        headerStyle,
      },
      {
        align: 'left',
        field: 'expiryPlusDays',
        label: this.$t('PaymentCard.expiryPlusDays'),
        name: 'expiryPlusDays',
        sortable: true,
        style: 'white-space: pre-wrap',
        headerStyle,
      },
      {
        align: 'left',
        field: 'goal',
        label: this.$t('PaymentCard.goal'),
        name: 'goal',
        sortable: false,
        headerStyle,
      },
      {
        align: 'left',
        field: 'applicationStatusForCharge',
        label: this.$t('PaymentCard.applicationStatusForCharge'),
        name: 'applicationStatusForCharge',
        sortable: false,
        headerStyle,
      },
      {
        align: 'left',
        field: 'applicationStatusForRegister',
        label: this.$t('PaymentCard.applicationStatusForRegister'),
        name: 'applicationStatusForRegister',
        sortable: false,
        headerStyle,
      },
      {
        align: 'left',
        field: 'applicationStatusForWaitPayment',
        label: this.$t('PaymentCard.applicationStatusForWaitPayment'),
        name: 'applicationStatusForWaitPayment',
        sortable: false,
        headerStyle,
      },
    ];
  }

  get state() {
    return get(this.card, 'state', 'inProgress');
  }

  toggleDeleteConfirm(item: Payment | null = null) {
    this.deleteConfirm = !this.deleteConfirm;
    this.deleteItem = item;
  }

  async deletePayment() {
    if (this.deleteItem === null) return;

    try {
      const { data: result } = await unlinkService(({
        id: this.card.id,
        paymentLinks: [this.deleteItem?.id],
        modified: this.card.modified,
      } as unknown) as Service);
      const card = cloneDeep(
        this.$store.getters['registryService/services/servicesCard']
      );
      card.paymentLinks = this.payments.filter(
        (i) => i.id !== this.deleteItem?.id
      );
      // eslint-disable-next-line vue/no-mutating-props
      this.card.modified = result.modified;
      this.$store.dispatch('registryService/services/setCardForJson', card);
    } catch (e) {
      notifyError(e.message.toString());
    } finally {
      this.toggleDeleteConfirm();
    }
  }

  editPayment(payment: Payment) {
    this.commonModels({
      paymentDialog: {
        mode: DialogMode.EDIT,
        data: payment,
      },
    });
  }

  addPayment() {
    this.commonModels({
      paymentDialog: {
        mode: DialogMode.CREATE,
        data: { regionCode: this.regionCode },
      },
    });
  }

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