<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">
          <BaseTable
            :hide-refresh="true"
            v-if="!loading"
            :columns="columns"
            :data="tableData"
            :loading="loading"
            :pagination.sync="pagination"
            @requestTable="init"
            :visible-columns="tableModel.visibleColumns"
          >
            <template v-slot:body-item-name="props">
              {{ showmeasureData(props.row.measureId, (el) => `${el.name} (${el.code})`) }}
            </template>
            <template v-slot:body-item-recipientCategoryData="props">
              {{ showRecipientCategoryData(props.row.recipientCategoryId, (el) => `${el.name} (${el.code})`) }}
            </template>
            <template v-slot:body-item-payment="props">
              {{ props.row.payment }} &#8381;
            </template>

            <template v-slot:body-item-status="props">
              {{ getNameStatus(props.row.status) }}
            </template>
          </BaseTable>
        </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 {
  RecipientCategoriesApi,
  RecipientCategory,
  PersonalAccountApi,
  SocialSupportMeasuresApi,
  SocialSupportMeasure,
  PersonSocialSupportMeasure,
} from '@openapi/personal-accounts';
import { notifyError } from '@/utils/notify';
import { TablePagination } from '@models/base/TablePagination';
import QColumn from '@/types/QColumn';
import { ExtendedPerson } from '@/interfaces/services/personal-accounts';
import { keyBy } from 'lodash';
import { convertDateFormat, DateFormat } from '@/utils/format-date';

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

function searchByFieldInList(field: string, list: string[]): string {
  list = list.map((s) => `'${s}'`);
  return `${field} =in= (${list.join(',')})`;
}

function prettierDate(date?: string): string {
  if (!date) return '';
  return convertDateFormat(date, DateFormat.invertedDate, DateFormat.date)
}

@Component({
  components: {},
})
export default class PersonsocialSupportMeasure extends Vue {
  @Prop({}) common?: BaseCardCommon;
  @Prop() model!: ExtendedPerson;

  loading = false;
  recipientCategoryData: Record<string, RecipientCategory> = {};
  measureData: Record<string, SocialSupportMeasure> = {};
  pagination = new TablePagination({
    page: 1,
    rowsPerPage: 10,
    descending: true,
    sortBy: 'created',
  });

  id = '';
  tableModel = {
    visibleColumns: [
      'name',
      'recipientCategoryCode',
      'measureCreationDate',
      'periodFrom',
      'periodTo',
      'payment',
      'status',
    ],
  };

  nameStatus: any = {
    NOT_CONFIRMED: 'Не подтвержден',
    NEEDS_VERIFICATION: 'Требует проверки',
    RELEVANT: 'Актуальный',
    NOT_RELEVANT: 'Не актуальный',
    WRONG: 'Ошибочный',
  };

  get columns(): TableColumn<PersonSocialSupportMeasure>[] {
    return [
      {
        align: 'left',
        label: this.$t('personalAccounts.measureCode'),
        name: 'name',
        field: 'measureId',
        style: 'white-space: normal;',
        required: false,
        sortable: false,
      },
      {
        align: 'left',
        label: this.$t('personalAccounts.recipientCategoryCode'),
        name: 'recipientCategoryData',
        field: 'recipientCategoryId',
        style: 'white-space: normal;',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('personalAccounts.measureCreationDate'),
        name: 'measureCreationDate',
        field: ({measureCreationDate}) => prettierDate(measureCreationDate),
        style: 'white-space: normal;',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('personalAccounts.periodFrom'),
        name: 'periodFrom',
        field: ({periodFrom}) => prettierDate(periodFrom),
        style: 'white-space: normal;',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('personalAccounts.periodTo'),
        name: 'periodTo',
        field: ({periodTo}) => prettierDate(periodTo),
        style: 'white-space: normal;',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('personalAccounts.payment'),
        name: 'payment',
        field: 'payment',
        style: 'white-space: normal;',
        required: false,
        sortable: true,
      },
      {
        align: 'left',
        label: this.$t('personalAccounts.status'),
        name: 'status',
        field: 'status',
        style: 'white-space: normal;',
        required: true,
        sortable: true,
      },
    ];
  }

  get isActive(): boolean {
    return this.common?.active === 'social-support-measure';
  }

  get tableData(): PersonSocialSupportMeasure[] {
    return this.model?.personsocialsupportmeasure || [];
  }

  get measureIds(): string[] {
    return this.model?.personsocialsupportmeasure?.flatMap(({ measureId }) => measureId || [] ) || [];
  }

  get categoriIds(): string[] {
    return this.model?.personsocialsupportmeasure?.flatMap(({ recipientCategoryId }) => recipientCategoryId || [] ) || [];
  }

  getNameStatus(key: string): string {
    return this.nameStatus[key];
  }

  showmeasureData(key: string, fm: { (itm: SocialSupportMeasure): string }): string {
    return this.measureData[key] && fm(this.measureData[key]);
  }

  showRecipientCategoryData(key: string, fm: { (itm: SocialSupportMeasure): string }): string {
    return this.recipientCategoryData[key] && fm(this.recipientCategoryData[key]);
  }

  async init(): Promise<void> {
    this.loading = true;

    await this.getMeasureData();
    await this.getRecipientCategoryData();
    this.loading = false;
  }

  async getRecipientCategoryData(): Promise<void> {
    this.loading = true;
    try {
      const { data } = await recipientCategoriesApi.searchRecipientCategories(
        searchByFieldInList('id', this.categoriIds)
      );
      this.recipientCategoryData = keyBy(data, 'id');
    } catch (error) {
      if (error instanceof Error) notifyError(error.message);
    }
    this.loading = false;
  }

  async getMeasureData(): Promise<void> {
    this.loading = true;
    try {
      const {
        data,
      } = await socialSupportMeasuresApi.searchSocialSupportMeasures(
        searchByFieldInList('id', this.measureIds || [''])
      );
      this.measureData = keyBy(data, 'id');
    } catch (error) {
      if (error instanceof Error) notifyError(error.message);
    }
    this.loading = false;
  }

  @Watch('model', { deep: true })
  onModelChange(model: ExtendedPerson): void {
    if (model?.personsocialsupportmeasure) this.init();
  }

  created() {
    if (this.model?.personsocialsupportmeasure) this.init();
  }
}
</script>
