<template>
  <div>
    <BaseTable
      v-if="preview"
      :columns="columns"
      :data="tableModel.records"
      :loading="tableModel.loading"
      :pagination="tableModel.pagination"
      @requestTable="updateTableData"
      @update="updateTableData"
    >
      <template #top>
        <div class="column full-width">
          <div class="row q-mt-md">
            <div class="q-table__control q-mb-md">
              <div class="q-table__title">
                {{ tableTitle }}
              </div>
            </div>
            <q-space />
            <div
              v-if="!revisionNumber"
              class="row q-gutter-x-md q-gutter-y-sm q-mb-md"
            >
              <q-btn
                color="primary"
                :label="$t('registries.connections.toSelectionBtnLabel')"
                @click="preview = !preview"
              />
            </div>
          </div>
        </div>
      </template>
    </BaseTable>
    <BaseTable
      v-else
      :columns="columns"
      :data="tableModel.records"
      :loading="tableModel.loading"
      :pagination="tableModel.pagination"
      :selected.sync="tableModel.selected"
      selection="multiple"
      @requestTable="updateTableData"
      @update="updateTableData"
    >
      <template #top>
        <div class="column full-width">
          <div class="row q-mt-md">
            <div class="q-table__control q-mb-md">
              <div class="q-table__title">
                {{ tableTitle }}
              </div>
            </div>
            <q-space />
            <div class="row q-gutter-x-md q-gutter-y-sm q-mb-md">
              <q-btn
                color="primary"
                :label="$t('registries.connections.toSelectedBtnLabel')"
                @click="preview = !preview"
              />
            </div>
          </div>
        </div>
      </template>
      <template #search>
        <RegistriesSearchBar @query="search" />
      </template>
    </BaseTable>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RegistriesSearchBar from '@components/registries/search-bars/search-bar.vue';
import { convertDateFormat } from '@utils/format-date';
import { DateFormat } from '@constants/utils/format-date';
import { DocumentApi, Document } from '@openapi/registry-data';
import { Registry } from '@openapi/registry-service';

@Component({
  components: {
    RegistriesSearchBar,
  },
})
export default class RegistryObjectConnectionTable extends Vue {
  @Prop() registry!: Registry;
  @Prop() selected!: any[];

  preview = true;
  tableTitle = 'Записи реестра:';
  searchQuery = '';
  tableModel = {
    loading: true,
    pagination: {
      descending: true,
      rowsPerPage: 10,
      sortBy: 'finishDate',
      rowsNumber: 0,
      page: 1,
    },
    selected: [] as any[],
    records: [] as Document[],
  };

  columns = [
    {
      align: 'left',
      field(val: number) {
        return val;
      },
      formatField: 'orderId',
      handler: (id: string) => this.goToRegistryObject(id),
      handlerField: 'id',
      label: this.$t('registries.applicationNumber'),
      name: 'orderId',
      required: true,
      sortable: true,
    },
    {
      align: 'left',
      field: 'finishDate',
      format: (val: string) =>
        val
          ? convertDateFormat(val, DateFormat.invertedDate, DateFormat.date)
          : '',
      label: this.$t('registries.finishDate'),
      name: 'finishDate',
      required: true,
      sortable: true,
    },
    {
      align: 'left',
      field: 'departmentFullName',
      label: this.$t('registries.department'),
      name: 'departmentFullName',
      required: true,
      sortable: true,
    },
    {
      align: 'left',
      field: 'status.internal',
      format: (val: string) => {
        const res = this.$store.getters[
          'registryService/referenceBooks/appliedReferenceBook'
        ]({
          key: val,
          id: 'gpzu_2_application_status',
          valueName: 'description',
        });
        return res.value;
      },
      label: this.$t('registries.status'),
      name: 'status.internal',
      required: true,
      sortable: true,
    },
    {
      align: 'left',
      field: 'document.number',
      label: this.$t('registries.objectCard.decisionNumber'),
      name: 'document.number',
      required: true,
      sortable: true,
    },
  ];

  @Watch('tableModel.selected')
  selectedHandler(selected: any[]) {
    this.$emit('update', selected);
  }

  @Watch('preview')
  modeHandler() {
    this.updateTableData();
  }

  created() {
    this.tableModel.selected = this.selected || [];
    this.updateTableData();
  }

  updateTableData({ pagination } = this.tableModel) {
    let query = '';

    if (this.preview) {
      if (this.tableModel.selected.length === 0) {
        this.tableModel.records = [];
        this.tableModel.loading = false;
        return;
      }

      this.tableModel.selected.forEach((el: Registry, i: number) => {
        if (i > 0) {
          query += ' or ';
        }
        query += `id=="${el.id}"`;
      });
    } else {
      query = this.searchQuery;
    }

    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 documentApi = new DocumentApi();
    return documentApi
      .pagingDocuments(
        this.registry.code,
        pagination.page,
        pagination.rowsPerPage,
        query,
        '',
        pagination.sortBy
          ? `${pagination.descending ? '-' : '+'}${pagination.sortBy}`
          : ''
      )
      .then(({ data }) => {
        if (data.totalRows) {
          this.tableModel.pagination.rowsNumber = data.totalRows;
        }
        this.tableModel.records = data.records || [];
        this.tableModel.loading = false;
      });
  }

  search(query: string) {
    this.searchQuery = query;
    this.updateTableData();
  }

  goToRegistryObject(id: string) {
    this.$router.push({
      name: 'cards',
      params: {
        id,
        path: `registry-object`,
      },
      query: {
        active: 'data',
        reg: this.registry.code,
        regid: this.registry.id,
        components: this.$store.getters[
          'cardComponents/registryObject/components'
        ],
      },
    });
  }

  get revisionNumber() {
    return this.$route.query.num;
  }
}
</script>
