<i18n>
{
  "en": {
    "PaymentCard": {
      "title": "Payments",
      "create": "New payment"
    }
  },
  "ru": {
    "PaymentCard": {
      "title": "Платежи",
      "create": "Новый платеж"
    }
  }
}
</i18n>

<template>
  <div v-if="common.active === 'payments'" class="q-pb-md q-gutter-y-md">
    <q-card class="no-shadow q-gutter-y-md q-mx-md no-border-radius">
      <q-card-section
        class="q-gutter-y-md bg-white q-pb-md q-pt-sm q-mt-md q-mx-md"
      >
        <BaseTable
          v-model="inputSearch"
          :useSearch="true"
          :loading="loading"
          :columns="columns"
          :data="services"
          :pagination.sync="pagination"
          title="Платежи"
          @requestTable="init"
          @input="search"
        >
        </BaseTable>
      </q-card-section>
    </q-card>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import ServicesSearchBar from '@/components/services/components/search-bar.vue';
import { Service, ServiceApi } from '@openapi/registry-service';
import { BaseCardCommon } from '@/interfaces';
import { pushRoute } from '@utils/routes';
import { notifyError } from '@utils/notify';

const serviceApi = new ServiceApi();

@Component({
  components: {
    ServicesSearchBar,
  },
})
export default class Payments extends Vue {
  @Prop() readonly common: BaseCardCommon;
  @Prop() readonly model: any;

  inputSearch = '';
  services: Service[] = [];
  loading = false;
  pagination = {
    descending: true,
    page: 1,
    rowsNumber: 0,
    rowsPerPage: 10,
    sortBy: 'modified',
  };

  fulltextString = '';

  queryStart =
    '(state==signed or state==readyToPublish or state==published or state==inProgress)';

  private created() {
    this.init();
  }

  private search(string: string) {
    this.fulltextString = string
      ? `(shortName=searchprefix="${string}" or shortName=search="${string}") or (fullName=searchprefix="${string}" or fullName=search="${string}")`
      : '';
    this.fetch();
  }

  private init(val: any = null): void {
    if (val) {
      this.pagination.descending = val.pagination.descending;
      this.pagination.rowsPerPage = val.pagination.rowsPerPage;
      this.pagination.sortBy = val.pagination.sortBy;
      this.pagination.page = val.pagination.page;
    }

    this.fetch();
  }

  private async fetch(query?: string): Promise<void> {
    this.loading = true;

    const arrQuery = [query || null, this.queryStart];

    const currentQuery = arrQuery
      .filter((filter: string | null) => !!filter)
      .join(' and ');

    return serviceApi
      .pagingService(
        this.pagination.page,
        this.pagination.rowsPerPage,
        currentQuery,
        this.fulltextString,
        `${this.pagination.descending ? '-' : '+'}${this.pagination.sortBy}`
      )
      .then(({ data }) => {
        if (data.records && data.totalRows) {
          this.services = data.records;
          this.pagination.rowsNumber = data.totalRows;
        }
      })
      .catch((e) => {
        notifyError(e.message.toString());
      })
      .finally(() => {
        this.loading = false;
      });
  }

  private get columns() {
    return [
      {
        name: 'shortName',
        formatField: 'shortName',
        field: (val: any) => val,
        handler: (item: any, options: any) => {
          pushRoute(
            this.$router,
            {
              name: 'cards',
              params: {
                id: item.id,
                path: 'payments',
              },
              query: {
                active: 'index',
                components: 'index',
                regionId: this.model.id,
              },
            },
            options?.targetBlank
          );
        },
        label: 'Краткое имя',
        align: 'left',
        sortable: true,
      },
      {
        name: 'fullName',
        field: 'fullName',
        label: 'Полное имя',
        align: 'left',
        style: 'white-space: pre-wrap',
        sortable: true,
      },
    ];
  }
}
</script>
