<template>
  <div v-if="isActive" class="q-pb-md">
    <q-card class="no-shadow q-gutter-y-md q-mx-md no-border-radius">
      <div class="q-mx-md q-pt-md q-pa-sm">
        <div class="q-gutter-y-md q-mb-md">
          <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, 100]"
            wrap-cells
          >
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td key="name" :props="props">
                  {{ props.row.name }}
                </q-td>
                <q-td key="value" :props="props">
                  {{ props.row.value }}
                </q-td>
                <q-td key="categoryCreationDate" :props="props">
                  {{ displayDateInvert(props.row.categoryCreationDate) }}
                </q-td>
                <q-td key="periodFrom" :props="props">
                  {{ displayDateInvert(props.row.periodFrom) }}
                </q-td>
                <q-td key="periodTo" :props="props">
                  {{ displayDateInvert(props.row.periodTo) }}
                </q-td>
                <q-td key="checkDate" :props="props">
                  {{ displayDate(props.row.checkDate) }}
                </q-td>
                <q-td key="status" :props="props">
                  {{
                    revealStatus[props.row.status]
                      ? revealStatus[props.row.status].value
                      : ''
                  }}
                </q-td>
              </q-tr>
            </template>
          </q-table>
        </div>
      </div>
    </q-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Component, Watch, Prop } from 'vue-property-decorator';
import { BaseCardCommon, TableColumn } from '@/interfaces';
import { USER_SCOPES } from '@constants/entities/Scope';
import {
  PersonalAccountApi,
  RecipientCategoriesApi,
} from '@openapi/personal-accounts';
import type { ExtendedPerson } from '@interfaces/services/personal-accounts';
import { notifyError } from '@utils/notify';
import {
  convertDateFromBackendFormat,
  convertDateFormat,
  DateFormat,
} from '@/utils/format-date';

const personalAccountApi = new PersonalAccountApi();
const recipientCategoriesApi = new RecipientCategoriesApi();

@Component({
  components: {},
})
export default class RecipientCategory extends Vue {
  @Prop({}) private common?: BaseCardCommon;

  USER_SCOPES = USER_SCOPES;

  loading = false;
  activated = false;

  tableData: Array<any> = [];

  @Watch('common.active', { immediate: true })
  onChangeActiveModule(): void {
    if (this.activated) return;
    if (this.common?.active === 'recipient-category') {
      this.fetch();
      this.activated = true;
    }
  }

  get columns(): TableColumn[] {
    return [
      {
        align: 'left',
        label: 'Наименование категории',
        name: 'name',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Дата установления категории',
        name: 'categoryCreationDate',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Период действия от',
        name: 'periodFrom',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Период действия до',
        name: 'periodTo',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Дата проверки',
        name: 'checkDate',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Статус',
        name: 'status',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
    ];
  }

  get revealStatus(): unknown {
    const referenceBooks = this.$store.getters[
      'registryService/referenceBooks/referenceBooks'
    ];

    if (referenceBooks['personal-account-service_PersonInfoStatus']) {
      return referenceBooks['personal-account-service_PersonInfoStatus'];
    }
    return {};
  }

  async fetch(): Promise<void> {
    this.loading = true;
    try {
      const { data: person } = await personalAccountApi.getPerson(
        this.$route.params.id,
        'personcategory'
      );

      if (person && (person as ExtendedPerson).personcategory) {
        const idList = (person as ExtendedPerson).personcategory.map(
          (e: any) => e.recipientCategoryId
        );
        let records = (person as ExtendedPerson).personcategory;
        const ids = `id =in= (${idList})`;

        await recipientCategoriesApi
          .searchRecipientCategories(ids)
          .then((response) => {
            records = records.map((category: any) => {
              const name = response.data.find((cat) => {
                if (cat.id === category.recipientCategoryId) {
                  return category;
                } else {
                  return null;
                }
              });
              return { ...category, name: name?.name };
            });
            this.tableData = records;
          })
          .catch((e) => {
            notifyError(e.message.toString());
          });
      }
    } catch (error) {
      if (error instanceof Error) notifyError(error.message.toString());
    }
    this.loading = false;
  }

  get isActive(): boolean {
    return this.common?.active === 'recipient-category';
  }

  displayDate(date: string): string {
    if (!date) return '';
    return convertDateFromBackendFormat(date, DateFormat.date);
  }

  displayDateInvert(date: string): string {
    if (!date) return '';
    return convertDateFormat(date, DateFormat.invertedDate, DateFormat.date);
  }
}
</script>
