<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="fullName" :props="props">
                  <q-chip
                    clickable
                    @click="
                      openPerson(
                        props.row.to_person[0].id,
                        'personal-accounts',
                        'personal'
                      )
                    "
                  >
                    {{ props.row.to_person[0].fullName }}
                  </q-chip>
                </q-td>
                <q-td key="birthday" :props="props">
                  {{ displayDateInvert(props.row.to_person[0].birthday) }}
                </q-td>
                <q-td key="snils" :props="props">
                  {{ props.row.to_person[0].snils }}
                </q-td>
                <q-td key="inn" :props="props">
                  {{ props.row.to_person[0].inn }}
                </q-td>
                <q-td key="relationType" :props="props">
                  {{ revealType[props.row.relationType] }}
                </q-td>
                <q-td key="status" :props="props">
                  {{
                    revealStatus[props.row.to_person[0].status]
                      ? revealStatus[props.row.to_person[0].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 { convertDateFormat, DateFormat } from '@/utils/format-date';
import camelCase from 'lodash/camelCase';
import { PersonalAccountApi, PersonRelation } from '@openapi/personal-accounts';
import { notifyError } from '@utils/notify';

const personalAccountApi = new PersonalAccountApi();

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

  loading = false;
  activated = false;
  pagination = {};
  tableData: PersonRelation[] = [];

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

  async fetch(): Promise<void> {
    this.loading = true;
    personalAccountApi
      .getPersonRelations(this.$route.params.id)
      .then((res) => {
        this.tableData = res.data;
      })
      .catch((e) => {
        notifyError(e.message.toString());
      })
      .finally(() => {
        this.loading = false;
      });
  }

  get columns(): TableColumn[] {
    return [
      {
        align: 'left',
        label: 'ФИО',
        name: 'fullName',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Дата рождения',
        name: 'birthday',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'СНИЛС',
        name: 'snils',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'ИНН',
        name: 'inn',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Тип связи',
        name: 'relationType',
        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_PersonStatus']) {
      return referenceBooks['personal-account-service_PersonStatus'];
    }
    return {};
  }

  get revealType(): Record<string, string> {
    return {
      PARTNER: 'Супруг',
      CHILD: 'Ребёнок',
      PARENT: 'Родитель',
      REPRESENTATIVE: 'Представитель',
      REPRESENTED: 'Заявитель',
    };
  }

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

  openPerson(
    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,
      },
    });
  }

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