<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 { Option, 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 { prepareJournalActionsParams } from '@/recruits/utils';
import {
  AccountsJournalRecordV1,
  JournalServiceApi,
} from '@/recruits/openapi/journal-service';
import UrlIntegratedSearch from '@/recruits/mixins/url-integrated-search';
import RefreshKeyInterceptor from '@/recruits/mixins/refresh-key-interceptor.ts';
import { QPagination } from '@models/models-ui';
import { UserActionsSearchFilter } from '@/recruits/components/log/user-actions/search-filter';

const JOURNAL_SERVICE_API = new JournalServiceApi();

@Component({
  components: {
    DataTable,
    SearchBar,
    SortBar,
    ApiErrors,
  },
})
export default class LogAuth extends Mixins(
  UrlIntegratedSearch,
  RefreshKeyInterceptor
) {
  pagination: QPagination = {
    sortBy: '',
    descending: false,
    page: 1,
    rowsPerPage: 50,
    rowsNumber: 1000,
  };

  public filter = new UserActionsSearchFilter();

  public sortButtons: Array<Option> = [
    { label: 'По дате', value: 'date' },
    { label: 'По типу операции', value: 'event' },
    { label: 'По ФИО', value: 'userName' },
  ];

  public data: Array<AccountsJournalRecordV1> = [];
  apiErrorShow = false;
  errorInResponse = {};
  // @ts-ignore:next-line
  public async fetchData(
    query: UrlQueryParams
  ): Promise<{ totalRows: number | undefined } | undefined> {
    const params = prepareJournalActionsParams(query);
    try {
      const { data } = await JOURNAL_SERVICE_API.getAccountsJournalV1(params);
      this.data = data.data || [];
      return {
        totalRows: data.totalRows,
      };
    } catch (error) {
      this.errorInResponse = error;
      this.apiErrorShow = true;
    }
  }
}
</script>
