<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
            :pagination.sync="pagination"
            @request="init"
            @update="init"
          >
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td key="decisionNumber" :props="props">
                  <q-chip
                    clickable
                    @click="openRegistry(props.row.order.serviceId)"
                  >
                    {{ props.row.order.RecipientData[0].decisionNumber }}
                  </q-chip>
                </q-td>
                <q-td key="shortName" :props="props">
                  {{ props.row.shortName }}
                </q-td>
                <q-td key="departmentName" :props="props">
                  {{ props.row.order.departmentName }}
                </q-td>
                <q-td key="regNumber" :props="props">
                  {{ props.row.order.regNumber }}
                </q-td>
                <q-td key="creationDate" :props="props">
                  {{ displayDate(props.row.order.creationDate) }}
                </q-td>
                <q-td key="state" :props="props">
                  {{ props.row.order.state }}
                </q-td>
                <q-td key="totalSum" :props="props">
                  {{ props.row.order.totalSum }}
                </q-td>
              </q-tr>
            </template>
          </q-table>
        </div>
      </div>
    </q-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Component, Prop, Watch } from 'vue-property-decorator';
import { BaseCardCommon, TableColumn } from '@/interfaces';
import {
  PaymentsApi,
  ServiceApi,
  PersonOrderResponseDto,
} from '@openapi/registry-service';
import { convertDateFromBackendFormat, DateFormat } from '@utils/format-date';
import { USER_SCOPES } from '@constants/entities/Scope';
import { notifyError } from '@utils/notify';

interface PersonOrder extends PersonOrderResponseDto {
  serviceName: string;
}

const paymentsApi = new PaymentsApi();
const serviceApi = new ServiceApi();

interface Pagination {
  page?: number;
  rowsPerPage?: number;
  descending?: boolean;
  sortBy?: string;
  rowsNumber?: number;
}
interface TableContext {
  pagination: Pagination;
}
@Component({
  components: {},
})
export default class PaymentData extends Vue {
  @Prop({}) private common?: BaseCardCommon;

  loading = false;
  activated = false;
  pagination: Pagination = {
    page: 1,
    rowsPerPage: 10,
    descending: false,
    sortBy: 'decisionNumber',
    rowsNumber: 0,
  };

  tableData: PersonOrder[] = [];

  get columns(): TableColumn[] {
    return [
      {
        align: 'left',
        label: 'Номер решения',
        name: 'decisionNumber',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Название услуги',
        name: 'shortName',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Уполномоченный орган',
        name: 'departmentName',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Номер распоряжения',
        name: 'regNumber',
        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: 'state',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
      {
        align: 'left',
        label: 'Размер выплаты',
        name: 'totalSum',
        style: 'white-space: normal;',
        required: true,
        sortable: false,
      },
    ];
  }

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

  @Watch('common.active', { immediate: true })
  onChangeActiveModule(activeModule: string): void {
    if (this.activated) return;
    if (activeModule === 'payment-data') {
      this.fetch();
      this.activated = true;
    }
  }

  async fetch(): Promise<void> {
    this.loading = true;
    try {
      const { data } = await paymentsApi.getPersonDetailedPayments(
        this.$route.params.id,
        this.pagination.page,
        this.pagination.rowsPerPage
      );
      this.pagination.rowsNumber = data.totalRows;
      const records = data?.records || [];
      const serviceIds = [
        ...records.reduce((serviceIds, record) => {
          if (record.order?.serviceId) {
            serviceIds.add(record.order?.serviceId);
          }
          return serviceIds;
        }, new Set<string>()),
      ];
      const services = await Promise.all(
        serviceIds.map(async (id) => {
          const { data: service } = await serviceApi.getService(id);
          return service;
        })
      );
      const serviceNamesById = services.reduce(
        (serviceNamesById, { id, shortName }) => {
          return {
            ...serviceNamesById,
            [id]: shortName,
          };
        },
        {} as Record<string, string>
      );
      this.tableData = records.map((record) => {
        const serviceId = record.order?.serviceId;

        return {
          ...record,
          serviceName: serviceId ? serviceNamesById[serviceId] : '—',
        };
      });
    } catch (error) {
      if (error instanceof Error) notifyError(error.message.toString());
    }
    this.loading = false;
  }

  init<T extends TableContext>(context: T): void {
    if (context?.pagination) {
      this.pagination.page = context.pagination.page;
      this.pagination.rowsPerPage = context.pagination.rowsPerPage;
    }
    this.fetch();
  }

  openRegistry(id: string): void {
    console.log(id);
    
    this.$router.push({
      name: 'registry-list',
      params: {
        id,
      },
    });
  }

  displayDate(date: string): string {
    return convertDateFromBackendFormat(date, DateFormat.date);
  }
}
</script>
