<template>
  <div class="BaseCard">
    <div class="BaseCard__Header">
      <list-header
        :data="data"
        :selected="selected"
        :loading="loading"
        @on-reload="loadNewData"
        class="BaseCard__Record"
      />
      <redesigned-tabs
        :clickHandler="tabClickHandler"
        :current-tab="$route.name"
        :tabs="tabs"
        dense
        class="BaseCard__Tabs"
      />
    </div>
    <keep-alive>
      <router-view
        @data-loading="request"
        @request="onRequest"
        @row-selected="setSelect"
        @request-handler="handleSortClick"
        @execute-search="loadNewData"
        :loading="loading"
        :data="data"
        :selected="selected"
        :sort-buttons="sortButtons"
        :pagination.sync="pagination"
        @update-pagination="updatePagination"
        :filter="filter"
        @change-filter="setNewFilter"
      />
    </keep-alive>
  </div>
</template>

<script lang="ts">
import { Component, Mixins } from 'vue-property-decorator';
import { Tab } from '@/interfaces/base/BaseTabs';
import ListHeader from '@/recruits/components/call-list/listHeader.vue';
import {
  ListRecordV2,
  ListSearchResponseV2,
  SummonListRegistryApi,
} from '@/recruits/openapi/summon-list-service';
import UrlIntegratedSearch from '@/recruits/mixins/url-integrated-search';
import { Option, UrlQueryParams } from '@/recruits/models';
import { prepareRecruitsFromListRequestParams } from '@/recruits/utils';
import { RecruitsFromListSearchFilter } from '@/recruits/components/call-list/recruits-from-list-search-filter';
import { QPagination } from '@models/models-ui';

const customSortOrder: Record<string, number> = {
  actualAddress: 1,
  residentialAddress: 2,
  residenceAddress: 3,
  criminalAddress: 4,
  universityAddress: 4,
  workAddress: 4,
};

@Component({
  components: { ListHeader },
})
export default class ListRecordTab extends Mixins(UrlIntegratedSearch) {
  SummonListRegistry = new SummonListRegistryApi();

  public filter = new RecruitsFromListSearchFilter();

  public readonly listId: string = this.$route.params.id;
  public data: ListSearchResponseV2 = {};
  public loading = true;
  public selected: string[] = [];
  public statusAllSubpoenaSend = true;

  public sortButtons: Array<Option> = [
    { label: 'По ФИО', value: 'fullName' },
    { label: 'По ИД ЕРН', value: 'idERN' },
    { label: 'По адресу', value: 'address' },
    { label: 'По серии повестки', value: 'subpoenaSeries' },
    { label: 'По номеру повестки', value: 'subpoenaNumber' },
    { label: 'По статусу', value: 'status' },
  ];

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

  get tabs(): Tab[] {
    return [
      {
        label: 'Список граждан',
        name: 'call-list',
        isVisible: true,
        badge: false,
      },
      {
        label: 'Типы адресов направления',
        name: 'call-list-settings',
        isVisible: true,
        badge: false,
      },
    ].map((tab) => ({
      name: tab.label,
      path: tab.name,
      visible: tab.isVisible === undefined || tab.isVisible,
      alert: tab.badge ?? false,
    }));
  }

  public tabClickHandler(selectedTab: Tab): void {
    if (this.$route.name !== selectedTab.path) {
      this.$router.replace({
        name: selectedTab.path,
        params: { id: this.$route.params.id },
      });
    }
  }

  public async fetchData(
    query: UrlQueryParams
  ): Promise<{ totalRows: number | undefined }> {
    this.loading = true;
    this.statusAllSubpoenaSend = true;
    const params = prepareRecruitsFromListRequestParams(query);
    const { data } = await this.SummonListRegistry.getRecruitsFromListV2(
      this.listId,
      params
    );

    data.data?.forEach((el: ListRecordV2) => {
      // need add to request empty field for this case
      if (!el?.sendInfo) Object.assign(el, { sendInfo: [] });
      el?.address?.sort((a, b) => {
        return (
          customSortOrder[a.type as keyof typeof customSortOrder] -
          customSortOrder[b.type as keyof typeof customSortOrder]
        );
      });
      Object.assign(el, { showOptions: false });
    });

    this.data = data;

    // FIXME перенесли логику на процесс
    if (data.data?.length) {
      data.data?.forEach((subpoena) => {
        if (subpoena.status !== '3') {
          this.statusAllSubpoenaSend = false;
        }
      });
    } else {
      this.statusAllSubpoenaSend = false;
    }
    this.loading = false;
    this.logPageVisit();
    return {
      totalRows: data.totalRows,
    };
  }

  setSelect(val: string[]) {
    this.selected = val;
  }

  setNewFilter(newFilter: RecruitsFromListSearchFilter) {
    this.filter = newFilter;
  }

  loadNewData() {
    this.executeSearch();
    this.selected = [];
  }

  logPageVisit() {
    // @ts-ignore
    this.$recordActivity({
      event: 'navigation',
      extraInfo: {
        breadcrumbs: ['Карточка списка'],
        type: 'call-list',
        id: this.data.listInfo?.id,
        number: this.data.listInfo?.number,
      },
    });
  }

  request(data: { data: ListSearchResponseV2; loading: boolean }) {
    this.data = data.data;
    this.loading = data.loading;
  }

  updatePagination(pagination: QPagination) {
    this.pagination = pagination;
    this.executeSearch();
  }
}
</script>

<style lang="scss" scoped>
.BaseCard {
  position: relative;

  &__Header {
    position: sticky;
    top: 0;
    z-index: 10;
    background: #edf3f7;
  }

  &__Record {
    min-height: 100px;
  }

  &__Tabs {
    border-top: 1px solid rgba(1, 72, 116, 0.11);
    border-bottom: 1px solid rgba(1, 72, 116, 0.11);
  }
}
</style>
