<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">
                  <q-chip
                    v-if="
                      $AC.haveOneOfScope([
                        USER_SCOPES.SOCIAL_DICTIONARY_OPERATOR,
                        USER_SCOPES.SOCIAL_DICTIONARY_ADMIN,
                      ])
                    "
                    clickable
                    @click="openCriteria(props.row.criteriaId)"
                  >
                    {{ props.row.name }}
                  </q-chip>
                  <span v-else>{{ props.row.name }}</span>
                </q-td>
                <q-td key="value" :props="props">
                  {{ props.row.value }}
                </q-td>
                <q-td key="creationDate" :props="props">
                  {{ displayDate(props.row.creationDate) }}
                </q-td>
                <q-td key="calculationDate" :props="props">
                  {{ displayDateInvert(props.row.calculationDate) }}
                </q-td>
                <q-td key="dateTo" :props="props">
                  {{ displayDateInvert(props.row.dateTo) }}
                </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 { PersonalAccountApi, CriteriaApi } from '@openapi/personal-accounts';
import {
  convertDateFromBackendFormat,
  convertDateFormat,
  DateFormat,
} from '@/utils/format-date';
import { notifyError } from '@utils/notify';
import type { ExtendedPerson } from '@interfaces/services/personal-accounts';
import { USER_SCOPES } from '@constants/entities/Scope';

const personalAccountApi = new PersonalAccountApi();
const criteriaApi = new CriteriaApi();

@Component({
  components: {},
})
export default class PersonCriteria 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 === 'person-criteria') {
      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: 'value',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Дата добавления',
        name: 'creationDate',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Дата последнего расчета',
        name: 'calculationDate',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Дата перерасчета',
        name: 'dateTo',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
    ];
  }

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

      records?.forEach((crit) => {
        if (!crit.criteriaId) return;
        criteriaApi
          .getCriteria(crit.criteriaId)
          .then((criteria) => {
            if (criteria.data && criteria.data.name) {
              this.tableData.push({ ...crit, name: criteria.data.name });
            } else {
              this.tableData.push(crit);
            }
          })
          .catch((e) => {
            this.tableData.push(crit);
            notifyError(e.message.toString());
          });
      });
    } catch (error) {
      if (error instanceof Error) notifyError(error.message.toString());
    }
    this.loading = false;
  }

  openCriteria(id: string): void {
    this.$router.push({
      name: 'read_criteria_directoria',
      params: {
        id: id,
      },
    });
  }

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

  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>
