<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"
        @row-selected="$emit('row-selected', $event)"
        :resetSelect="resetSelect"
        :rows-per-page-options="[10, 25, 50, 100]"
        @accept="accept"
        @decline="decline"
      />
    </div>
    <AcceptDialog
      v-if="isAcceptModalVisible"
      :opened.sync="isAcceptModalVisible"
      :model="itemToAccept"
      @refresh="refresh"
    />
  </div>
</template>

<style lang="scss" scoped></style>

<script lang="ts">
import { Component, Prop, Mixins } from 'vue-property-decorator';
import SortBar from '@/recruits/components/common/sort-bar.vue';
import { SortingOption, UrlQueryParams } from '@/recruits/models';
import {
  MilitaryRegistrationItem,
  PersonRegistryApi,
} from '@/recruits/openapi/person-registry';
import DataTable from './data-table.vue';
import SearchBar from './search-bar.vue';
import { SearchFilterUtils } from '@/recruits/utils/search-filter';
import UrlIntegratedSearch from '@/recruits/mixins/url-integrated-search';
import { prepareApiParams } from '@/recruits/utils/prepare-api-params';
import ProcessStarter from '@/mixins/ProcessStarter';
import AcceptDialog from './dialogs/AcceptDialog.vue';

@Component({
  components: {
    DataTable,
    SearchBar,
    SortBar,
    AcceptDialog,
  },
})
export default class Recruits extends Mixins(
  UrlIntegratedSearch,
  ProcessStarter
) {
  @Prop({ default: 'milBaseUserActionDistribute' }) declare processKey: string;

  @Prop()
  resetSelect: boolean;

  @Prop()
  public listId: string;

  itemToAccept: MilitaryRegistrationItem | null = null;

  get isAcceptModalVisible(): boolean {
    return !!this.itemToAccept;
  }

  set isAcceptModalVisible(val: boolean) {
    if (!val) this.itemToAccept = null;
  }

  RecruitApi = new PersonRegistryApi();
  public sortButtons: Array<SortingOption<MilitaryRegistrationItem>> = [
    { label: 'По ФИО', value: 'fullName' },
    { label: 'По дате рождения', value: 'birthDate' },
    { label: 'По ИД ЕРН', value: 'idern' },
    { label: 'По СНИЛС', value: 'snils' },
    { label: 'По статусу', value: 'statusCode' },
  ];

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

  public filter = new SearchFilterUtils();

  public async fetchData(
    query: UrlQueryParams
  ): Promise<{ totalRows: number | undefined }> {
    const params = prepareApiParams(query);
    const { data } = await this.RecruitApi.getMilitaryRegistrationV1(params);
    this.data = data.data || [];
    this.$emit('data-loading', { data: this.data, loading: false });
    return {
      totalRows: data.totalRows,
    };
  }

  accept(item: MilitaryRegistrationItem): void {
    if (!item.acceptEnable) return;
    this.itemToAccept = item;
  }

  async decline(item: MilitaryRegistrationItem): Promise<void> {
    if (!item.cancelEnable) return;
    const traceId = await this.startProcess({
      processTraceIds: [item.processTraceId],
      actionType: 'privateFileCancel',
    });

    this.registerListener((message, removeListener) => {
      if (traceId !== message.traceId) return;

      if (message.body.type === 'finish') {
        removeListener();
        this.refresh();
        return;
      }

      if (message.body.type === 'error') {
        this.$q.notify({
          color: 'negative',
          icon: 'error',
          message: 'Не удалось отменить запрос личного дела',
        });
      }
    });
  }
}
</script>
