import { Component, Vue } from 'vue-property-decorator';
import get from 'lodash/get';
import { TablePagination } from '@models/base/TablePagination';
import {
  CriteriaApi,
  Criteria,
  CriteriaTypeEnum,
  CriteriaStatusEnum,
} from '@openapi/personal-accounts';
import QColumn from '@/types/QColumn';
import { notifyError } from '@/utils/notify';
import type { TableColumnOptions, TableColumn } from '@/interfaces';
import { pushRoute } from '@utils/routes';
import { USER_SCOPES } from '@/constants/entities/Scope';

type StatusTypeKeys<TEnumType> = keyof TEnumType;
const criteriaApi = new CriteriaApi();

@Component({
  methods: {
    get,
  },
})
export default class CriteriaDirectoryList extends Vue {
  USER_SCOPES = USER_SCOPES;
  data: Criteria[] = [];
  loading = false;
  typeListCriteria: CriteriaTypeEnum[] = Object.values(CriteriaTypeEnum);
  pagination = {
    descending: true,
    sortBy: 'created',
    rowsPerPage: this.$route.query.rowsPerPage
      ? Number(this.$route.query.rowsPerPage)
      : 10,
    rowsNumber: 0,
    page: this.$route.query.page ? Number(this.$route.query.page) : 1,
  };

  statusType: Record<string, string> = {
    DRAFT: 'Черновик',
    ACTIVATED: 'Активен',
    DEACTIVATED: 'Деактивирован',
  };

  statusList = false;

  criteriaTypes: Record<string, string> = {
    BOOLEAN: 'Флаг',
    NUMBER: 'Числовой',
    TEXT: 'Текстовый',
    LIST: 'Список значений',
  };

  listTypeCheck(val: string): boolean {
    this.statusList = val === CriteriaTypeEnum.List;
    return true;
  }

  model = {
    visibleColumns: [
      'name',
      'description',
      'status',
      'type',
      'values',
      'delete',
    ],
  };

  get columns(): TableColumn<Criteria>[] {
    return [
      {
        align: 'left',
        label: this.$t('criteriaDirectory.name'),
        field: (i) => i,
        name: 'name',
        required: true,
        formatField: 'name',
        handler: ({ id }, options?) => {
          if (!id) return;
          if (this.$AC.haveScope(USER_SCOPES.SOCIAL_DICTIONARY_ADMIN)) {
            pushRoute(
              this.$router,
              {
                name: 'edit_criteria_directoria',
                params: {
                  id: id,
                  path: 'edit',
                },
              },
              options?.targetBlank
            );
          } else {
            pushRoute(this.$router, {
              name: 'read_criteria_directoria',
              params: {
                id: id,
                path: 'card',
              },
            });
          }
        },
      },
      {
        align: 'left',
        label: this.$t('criteriaDirectory.description'),
        field: 'description',
        name: 'description',
        required: false,
        sortable: false,
      },
      {
        align: 'left',
        label: this.$t('criteriaDirectory.activity'),
        field: ({ status }) => this.getStatusType(status),
        name: 'status',
        required: false,
        sortable: false,
      },
      {
        align: 'right',
        label: this.$t('criteriaDirectory.type'),
        field: ({ type }) => this.getCriteriaType(type),
        name: 'type',
        required: false,
        sortable: false,
      },
      {
        align: 'left',
        field: 'values',
        label: this.$t('criteriaDirectory.value'),
        name: 'values',
        required: true,
      },
      {
        align: 'right',
        label: this.$t('criteriaDirectory.delete'),
        field: 'id',
        name: 'delete',
        required: false,
      },
    ];
  }

  startCreate(): void {
    this.$router.push({
      name: 'create_criteria_directoria',
    });
  }

  created(): void {
    this.init();
  }

  startDelete(data: string): void {
    this.$router.push({
      name: 'delete_criteria_directoria',
      params: {
        id: data,
        path: 'delete',
      },
    });
  }

  startEdit(data: string): void {
    this.$router.push({
      name: 'edit_criteria_directoria',
      params: {
        id: data,
        path: 'edit',
      },
    });
  }

  getStatusType(status: string): string {
    return this.statusType[status];
  }

  getCriteriaType(type: string): string {
    return this.criteriaTypes[type] || type;
  }

  private async init(val: any = null): Promise<void> {
    if (val) {
      this.pagination.descending = val.pagination.descending;
      this.pagination.rowsPerPage = val.pagination.rowsPerPage;
      this.pagination.sortBy = val.pagination.sortBy;
      this.pagination.page = val.pagination.page;
    }

    this.loading = true;
    return criteriaApi
      .pagingCriteria(
        this.pagination.page,
        this.pagination.rowsPerPage,
        undefined,
        undefined,
        '-modified',
        '',
        {}
      )
      .then((data) => {
        // @ts-ignore todo поправить типы в api
        this.data = data.data.records;
        this.pagination.rowsNumber = data.data.totalRows || 0;
      })
      .catch((error: Error) => {
        notifyError(error.message);
      })
      .finally(() => {
        this.loading = false;
      });
  }
}
