import { Component, Mixins } from 'vue-property-decorator';
import { RoleApi, Role } from '@openapi/idm';
import { notifyError } from '@utils/notify';
import { USER_SCOPES } from '@/constants/entities/Scope';
import ReTable from '@/recruits/components/common/r-table/index.vue';
import UrlIntegratedSearch from '@/recruits/mixins/url-integrated-search';
import { UrlQueryParams } from '@/recruits/models';
import { RTableColumn } from '@/interfaces';
import { prepareApiParams } from '@/recruits/utils/prepare-api-params';
import Centered1280Box from '@/recruits/components/common/centered-1280-box.vue';
import WhiteCard from '@/recruits/components/common/white-card.vue';
import { SearchFilter } from '@/recruits/models/index';
import ModalEditCountSessionRole from './ModalEditCountSessionRole.vue';

const roleApi = new RoleApi();

@Component({
  components: {
    Centered1280Box,
    WhiteCard,
    ReTable,
    ModalEditCountSessionRole,
  },
})
export default class Roles extends Mixins(UrlIntegratedSearch) {
  public roles: Array<Role> | undefined = [];
  public filter = new SearchFilter();

  private get columns(): RTableColumn<Array<Role>>[] {
    const defaultColumns: RTableColumn<Array<Role>>[] = [
      {
        name: 'displayName',
        label: 'Наименование',
        field: (row: any) => {
          return row.shortname || row.displayName || row.name;
        },
        width: '2fr',
      },
      {
        name: 'description',
        label: 'Описание',
        field: 'description',
        width: '2fr',
      },
      {
        name: 'sessionsLimit',
        label: 'Лимит сессий пользователя',
        field: 'sessionsLimit',
        format: (val: any) => val || 'Без ограничений',
      },
    ];
    if (this.$AC.haveScope(USER_SCOPES.SECURITY_ADMINISTRATOR)) {
      defaultColumns.push({
        name: 'action',
        label: '',
        field: 'action',
        width: '80px',
        componentPath: 'action-buttons',
        componentOptions: {
          actions: [
            {
              icon: 'edit',
              color: 'primary',
              cb: (row: any) => this.showEditDialog(row),
              tooltipText: 'Редактировать',
            },
          ],
        },
      });
    }

    return defaultColumns;
  }

  editableRole: Role | null = null;

  async fetchData(
    query: UrlQueryParams
  ): Promise<{ totalRows: number | undefined }> {
    const params = prepareApiParams(query);

    try {
      const { data } = await roleApi.getRolesList(
        params.pagination.page,
        params.pagination.rowsPerPage,
        'ervuRole=like=true',
        undefined,
        'shortname'
      );
      this.roles = Array.isArray(data.records) ? data.records : [];
      return { totalRows: data.totalRows };
    } catch (e: any) {
      notifyError(e.toString());
      return { totalRows: 0 };
    }
  }

  /**
   * Функция для показа диалогового окна редактирования роли
   * @param {Role} role - объект содержащий информацию о роли
   */
  showEditDialog(role: Role): void {
    this.editableRole = role;
  }

  /**
   * Функция закрытия диалогового окна с вызовом refresh редактирования роли
   */
  refreshEditDialog(): void {
    this.editableRole = null;
    this.refresh();
  }

  /**
   * Функция закрытия диалогового окна редактирования роли
   */
  closeEditDialog(): void {
    this.editableRole = null;
  }
}
