<template>
  <div class="q-pa-md q-gutter-y-md">
    <div
      class="flex justify-between items-center bg-white q-pa-md rounded-borders"
    >
      <div class="column justify-center text-h5" style="min-height: 36px">
        {{ $t('registries.label') }}
      </div>
      <q-btn
        v-if="$AC.haveScope(USER_SCOPES.CLOUD_ADMIN)"
        icon="create"
        color="primary"
        :label="$t('registries.createBtnLabel')"
        @click="createNewRegistry"
      />
    </div>
    <div class="bg-white rounded-borders">
      <BaseTable
        :title="$t('registries.listLabel')"
        :columns="columns"
        :data="model.records"
        :loading="model.loading"
        :pagination.sync="pagination"
        :rows-per-page-options="rowPerPageList"
        :visible-columns="visibleColumns"
        @requestTable="init"
        @update="init"
        saveQuery
      />
      <RegistryFormDialog
        :registry-dialog.sync="registryDialog"
        :form-model.sync="formModel"
        @created="fetch"
      />
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import QColumn from '@/types/QColumn';
import RegistryFormDialog from '@components/registries/registry-form-dialog.vue';
import { pushRoute } from '@utils/routes';
import { USER_SCOPES } from '@constants/entities/Scope';
import { Registry, RegistryApi } from '@openapi/registry-service';
import { notifyError } from '@utils/notify';
import axios from 'axios';
import BaseRegistryPage from './base-registry-page.vue';

const registryApi = new RegistryApi();

@Component({
  components: {
    RegistryFormDialog,
  },
})
export default class Registries extends BaseRegistryPage {
  model = {
    loading: false,
    records: [] as Registry[],
  };

  registryDialog = false;
  formModel: Partial<Registry> | null = null;

  columns: QColumn[] = [
    {
      align: 'left',
      field: (val: any) => val,
      formatField: 'name',
      handler: (id: string, opts?: any) => {
        pushRoute(
          this.$router,
          {
            name: 'registry-list',
            params: {
              id,
            },
          },
          opts?.targetBlank
        );
      },
      handlerField: 'id',
      label: this.$t('registries.name'),
      name: 'name',
      required: true,
      sortable: true,
    },
    {
      align: 'left',
      field: 'description',
      label: this.$t('registries.description'),
      name: 'description',
      required: true,
      classes: ['registries-table__descr-col'],
      sortable: true,
    },
  ];

  pending = 0;

  // Вызывается в родительском классе
  async fetch(): Promise<void> {
    if (this.pending) {
      this.pending++;
      return;
    }
    this.pending = 1;

    this.model.loading = true;

    try {
      const paging = await registryApi
        .pagingRegistry(
          this.pagination.page,
          this.pagination.rowsPerPage,
          undefined,
          undefined,
          this.sort
        )
        .then((it) => it.data);
      if (paging.totalRows && paging.records) {
        this.pagination.rowsNumber = paging.totalRows;
        this.model.records = paging.records;
      }
    } catch (e) {
      if (e instanceof Error) notifyError(e.message);
    } finally {
      this.model.loading = false;
    }

    if (this.pending > 1) {
      this.pending = 0;
      await this.fetch();
      return;
    }
    this.pending = 0;
  }

  createNewRegistry(): void {
    this.registryDialog = true;
    this.formModel = {
      name: '',
      description: '',
      code: '',
    };
  }

  get isAdmin(): boolean {
    return this.$AC.haveScope(USER_SCOPES.CLOUD_ADMIN);
  }
}
</script>

<style lang="scss">
.registries-table {
  &__descr-col {
    width: 758px;
    white-space: normal !important;
  }
}
</style>
