<template>
  <div class="row q-pa-md justify-center" v-show="common.active === 'statements'">
    <div class="col-12 max-1280-width">
      <q-table
        v-if="!loading"
        class="no-shadow text-grey-9"
        row-key="id"
        :columns="columns"
        :data="tableData"
        :rows-per-page-options="[10, 20, 50]"
        :pagination.sync="pagination"
        wrap-cells
        @request="fetch"
        separator="none"
      >
        <template v-slot:header="props">
          <q-tr :props="props" class="theader">
            <q-th v-for="col in props.cols" :key="col.name" :props="props" class="headerCell">
              {{ col.label }}
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="tableRow" @click="openCard(get(props.row, 'application.id'), 'statements', 'author')">
            <q-td :props="props" key="orderId" class="tableCell">
              {{ get(props.row, 'application.common.orderId', '') }}
            </q-td>
            <q-td :props="props" key="startDateIso" class="tableCell">
              {{ get(props.row, 'application.system.startDate', '') }}
            </q-td>
            <q-td :props="props" key="internal" class="tableCell">
              {{ formatStatus(get(props.row, 'application.system.status.internal', '')) }}
            </q-td>
            <q-td :props="props" key="regionCode" class="tableCell">
              {{ formateRegion(get(props.row, 'application.system.regionCode', '')) }}
            </q-td>
          </q-tr>
        </template>     
      </q-table>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import camelCase from 'lodash/camelCase';
import isEmpty from 'lodash/isEmpty';
import get from 'lodash/get';

import { BaseCardCommon, TableColumn } from '@/interfaces';
import {
  DocumentApi,
  Document as Application,
} from '@openapi/document-registry';

import { regions } from '@constants/entities/Region/Regions';

import { TablePagination } from '@/models/base/TablePagination';
import { searchByFieldInList } from '@/utils/query';
import { convertDateFromBackendFormat, DateFormat } from '@/utils/format-date';
import { ExtendedPerson } from '@/interfaces/services/personal-accounts';
import { notifyError } from '@/utils/notify';
import { AxiosResponse } from 'axios';
import { PersonalAccountApi } from '@/openapi/personal-accounts';

interface TableData {
  application: Application;
}

const documentApi = new DocumentApi();

@Component({
  components: {},
  methods: {
    get,
  },
})
export default class StatementsCard extends Vue {
  @Prop() common: BaseCardCommon;
  @Prop() model: any;

  loading = false;
  activated = false;
  resolutionLoading = false;
  person: ExtendedPerson | null = null;
  applications: Application[] = [];
  tableData: TableData[] = [];

  get columns(): TableColumn<Application>[] {
    return [
      {
        align: 'left',
        label: this.$t('statements.regNumber'),
        name: 'orderId',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: this.$t('statements.dateCreate'),
        name: 'startDateIso',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: this.$t('statements.status'),
        name: 'internal',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        icon: 'people_outline',
        label: this.$tc('entities.region.name', 0),
        name: 'regionCode',
        required: true,
        sortable: false,
      },
    ];
  }

  pagination: TablePagination = {
    page: 1,
    descending: false,
    rowsPerPage: 10,
    rowsNumber: 0,
  };

  get personId(): string {
    return this.model?.personId || '';
  }

  @Watch('personId', { immediate: true })
  onPersoneIdChange(personId: string): void {
    if (personId) this.init(personId);
  }

  get applicationIds(): string[] {
    return (this.person?.personapplication || [])?.reduce(
      (ids, { serviceId, applicationUUID }) => {
        if (
          serviceId === this.model?.system?.serviceId &&
          applicationUUID &&
          applicationUUID !== this.model?.id
        ) {
          ids.push(applicationUUID);
        }
        return ids;
      },
      [] as string[]
    );
  }

  get applicationIdsOnPage(): string[] {
    const rowsPerPage = this.pagination?.rowsPerPage || 0;
    const page = this.pagination?.page - 1 || 0;
    const shift = page * rowsPerPage;

    return this.applicationIds?.slice(shift, shift + rowsPerPage);
  }

  @Watch('person')
  onPersonChange(): void {
    const pagination = this.pagination;

    if (!isEmpty(this.applicationIdsOnPage)) this.fetch({ pagination });
  }

  created(): void {
    if (!isEmpty(this.applicationIdsOnPage)) this.fetch();
  }

  openCard(
    id: string,
    path: string,
    def: string,
    query: Record<string, string> = {}
  ): void {
    this.$router.push({
      name: 'cards',
      params: {
        id: id,
        path: path,
      },
      query: {
        components: this.$store.getters[
          `cardComponents/${camelCase(path)}/components`
        ],
        active: def,
        ...query,
      },
    });
  }

  formatDate(date?: string): string {
    return date ? convertDateFromBackendFormat(date, DateFormat.date) : '';
  }

  formatStatus(statusCode: string): string {
    return this.$store.getters[
      'registryService/referenceBooks/appliedReferenceBook'
    ]({
      key: statusCode,
      id: 'gpzu_2_application_status',
      valueName: 'description',
    }).value;
  }

  formateRegion(code: string): string {
    return (
      regions.find((region) => region.code === code)?.title ??
      'Неизвестный субъект'
    );
  }

  async init(personId: string): Promise<void> {
    if (!personId) return;
    try {
      const { data } = ((await new PersonalAccountApi().getPerson(
        personId,
        'personapplication'
      )) as unknown) as AxiosResponse<ExtendedPerson>;
      this.person = data;
    } catch (error) {
      if (error instanceof Error) notifyError(error.message);
    }
  }

  async fetch({ pagination }: { pagination?: TablePagination } = {}): Promise<
    void
  > {
    this.pagination.rowsNumber = this.applicationIds?.length || 0;
    if (pagination) {
      this.pagination = {
        ...pagination,
      };
    }
    if (isEmpty(this.applicationIdsOnPage)) return;

    this.loading = true;
    this.resolutionLoading = true;
    try {
      const { data } = await documentApi.searchDocuments(
        'Applications',
        searchByFieldInList('id', this.applicationIdsOnPage)
      );
      this.applications = data;
      this.tableData = data.map((application) => {
        return {
          application,
        };
      });
    } catch (error) {
      console.warn(
        `[perconal-accounts/statements] Couldn't get list of appalcations`
      );
    }
    this.loading = false;
  }
}
</script>

<style lang="scss" scoped>

.theader {
  height: auto;
  padding: 0 6px 0 0;

  font-family: 'Golos UI', sans-serif;
  font-style: normal;
  font-weight: 400;
  font-size: 18px;
  line-height: 22px;
  letter-spacing: -0.015em;
  color: rgba(2, 12, 18, 0.58);

  display: grid;
  grid-template-columns: 1fr 1fr 4fr 2fr;
}

.headerCell {
  padding: 7px;
  font-family: 'Golos Text', sans-serif;
  font-style: normal;
  font-weight: 600;
  font-size: 10px !important;
  line-height: 12px;
  letter-spacing: 0.05em;
  text-transform: uppercase;
}

.tableRow {
  cursor: pointer;
  background: rgba(38, 117, 166, 0.025);
  border: 1px solid rgba(1, 72, 116, 0.11);
  border-radius: 8px;
  margin-bottom: 4px;
  display: grid;
  grid-template-columns: 1fr 1fr 4fr 2fr;
}

.tableCell {
  height: auto;
  padding: 0 4px 0 4px;
}

</style>