<template>
  <div class="q-pb-md" v-if="common.active === 'versions'">
    <q-card class="no-shadow q-mx-md q-pa-md no-border-radius">
      <BaseTable
        :data="list"
        :columns="columns"
        title="Версии документа"
        :loading="tableModel.loading"
        class="q-mt-md"
        :pagination="tableModel.pagination"
        @requestTable="updateTableData"
        @update="updateTableData"
      />
    </q-card>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import { RawLocation } from 'vue-router/types/router';
import { convertDateFromTimestamp } from '@utils/format-date';
import { Revision, VersioningApi } from '@openapi/registry-data';
import { CardNeedToUpdateType } from '@constants/models/Card';
import { BaseCardCommon } from '@/interfaces';

@Component
export default class RegistryVersions extends Vue {
  @Prop() model: any;
  @Prop() common!: BaseCardCommon;

  @Watch('common.needToUpdate')
  needToUpdateHandler(val: CardNeedToUpdateType) {
    if (val === CardNeedToUpdateType.VERSION) {
      this.$nextTick(() => {
        this.updateTableData();
        this.$store.commit(
          'utils/cards/needToUpdate',
          CardNeedToUpdateType.FALSE
        );
      });
    }
  }

  registryCode = this.$route.query.reg;
  registryId = this.$route.query.regid;
  list = [] as Revision[];
  tableModel = {
    loading: true,
    records: [] as Revision[],
    pagination: {
      descending: true,
      rowsPerPage: 10,
      // sortBy: 'created', todo: из сервиса VersioningApi убрана сортировка
      rowsNumber: 0,
      page: 1,
    },
  };

  columns = [
    {
      align: 'left',
      field(val: string) {
        return val;
      },
      formatField: 'number',
      handler: (id: string) => this.goToRegistryObject(id),
      handlerField: 'number',
      label: 'Номер',
      name: 'number',
      required: true,
      // sortable: true,
    },
    {
      align: 'left',
      field: 'created',
      format: (val: number) => (val ? convertDateFromTimestamp(val) : ''),
      label: 'Время и дата',
      name: 'created',
      required: true,
      // sortable: true,
    },
    {
      align: 'left',
      field: 'operation',
      format: (val: string) => {
        const operation = val.toLowerCase();
        switch (operation) {
          case 'update':
            return 'РЕДАКТИРОВАНИЕ';
          case 'create':
            return 'СОЗДАНИЕ';
          default:
            return val;
        }
      },
      label: 'действие',
      name: 'operation',
      required: true,
      // sortable: true,
    },
  ];

  goToRegistryObject(revisionNumber: string) {
    const route = this.$route;
    const newQuery = {
      ...route.query,
      active: 'data',
      num: revisionNumber,
    };
    this.$router.push({ ...route, query: newQuery } as RawLocation);
  }

  async updateTableData(data?: any) {
    // todo type BaseTablePagination
    const pagination = data?.pagination ?? this.tableModel.pagination;
    console.log('[registry-versions][updateTableData]');
    const { schema, id } = this.model;

    this.tableModel.pagination.descending = pagination.descending;
    this.tableModel.pagination.rowsPerPage = pagination.rowsPerPage;
    // this.tableModel.pagination.sortBy = pagination.sortBy;
    this.tableModel.pagination.page = pagination.page;

    const versioningApi = new VersioningApi();
    versioningApi
      .getRevisions(
        schema,
        id,
        pagination.page,
        pagination.rowsPerPage
        // pagination.sortBy
        //   ? `${pagination.descending ? '-' : '+'}${pagination.sortBy}` todo: из сервиса VersioningApi убрана сортировка
        //   : ''
      )
      .then(({ data }) => {
        if (data.totalRows) {
          this.tableModel.pagination.rowsNumber = data.totalRows;
        }
        // this.tableModel.records = data.records || [];
        this.tableModel.records = data.records || [];
        this.list = data.records || [];
        this.tableModel.loading = false;
      });
  }
}
</script>
