<template>
  <div class="row">
    <div class="col-12">
      <search-bar v-model="filter" @search="executeSearch" :loading="loading" />
    </div>
    <div class="col-12">
      <sort-bar
        v-model="sortButtons"
        :pagination="pagination"
        @click="handleSortClick"
        :loading="loading"
      />
    </div>
    <div class="col-12">
      <!-- Таблица с данными -->
      <data-table
        :loading="loading"
        :data="data"
        :pagination.sync="pagination"
        @request="onRequest"
        :rows-per-page-options="[10, 25, 50, 100]"
      />
    </div>
    <q-dialog v-model="apiErrorShow" no-backdrop-dismiss>
      <api-errors :errorObject="errorInResponse" />
    </q-dialog>
  </div>
</template>

<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator';

import SortBar from '@/recruits/components/common/sort-bar.vue';
import { SortingOption, UrlQueryParams } from '@/recruits/models';

import DataTable from './data-table.vue';
import SearchBar from './search-bar.vue';
import ApiErrors from '@/recruits/components/dialogs/ApiErrors.vue';
import { JournalSmevSearchFilter } from './search-filter';
import {
  ErvuMzMonitorServiceApi,
  SearchMzRecordResponseV1,
} from '@/recruits/openapi/ervu-service';
import UrlIntegratedSearch from '@/recruits/mixins/url-integrated-search';
import { requestApi } from '@/recruits/api';
import { QPagination } from '@models/models-ui';

@Component({
  components: {
    DataTable,
    SearchBar,
    SortBar,
    ApiErrors,
  },
})
export default class JournalSmev extends Mixins(UrlIntegratedSearch) {
  ervuMzMonitorServiceApi = new ErvuMzMonitorServiceApi();

  public filter = new JournalSmevSearchFilter();

  public sortButtons: Array<SortingOption<SearchMzRecordResponseV1>> = [
    { label: 'По дате', value: 'createDate' },
    { label: 'По наименованию ВС', value: 'mzName' },
    { label: 'По классу ВС', value: 'mzClass' },
  ];

  public data: Array<SearchMzRecordResponseV1> | undefined = [];

  pagination: QPagination = {
    sortBy: '',
    descending: false,
    page: 1,
    rowsPerPage: 50,
    rowsNumber: 0,
  };

  apiErrorShow = false;
  errorInResponse: unknown | null = null;
  // @ts-ignore:next-line
  public async fetchData(
    query: UrlQueryParams
  ): Promise<{ totalRows: number | undefined } | undefined> {
    try {
      const data = await requestApi(
        this.ervuMzMonitorServiceApi,
        'getMzRecordsV1',
        {
          pagination: {
            sortBy: query.sortby,
            descending: query.descending,
            page: Number(query.page),
            rowsPerPage: Number(query.perpage),
          },
          search: this.filter.prepareRequestParams(),
        }
      );
      this.data = data.message.data;
      return {
        totalRows: data.message.totalRows,
      };
    } catch (error) {
      this.errorInResponse = error;
      this.apiErrorShow = true;
    }
  }
}
</script>
