import { Component, Mixins } from 'vue-property-decorator';
import IncidentsTable from '@components/incidents/table.vue';
import LostPetitionService from '@services/mz/LostPetitionService';
import LostStatementService from '@services/mz/LostStatementService';
import Loadable from '@mixins/Loadable';
import type { Incident } from '@components/incidents/types';
import type { PaginatedResponse } from '@interfaces/base/PaginatedResponse';
import Filterable from '@mixins/Filterable';
import { RestOutputBean } from '@openapi/mz-resend';
import { PetitionInfo, RequestInfo } from '@openapi/mz-history';
import { TableFilter } from '@models/base/TableFilter';
import { TablePagination } from '@models/base/TablePagination';
import axios from 'axios';
import { notifyError } from '@utils/notify';

@Component({
  components: { IncidentsTable },
})
class Incidents extends Mixins(Loadable, Filterable) {
  loading = false;
  incidents: Incident[] = [];
  selectedIncidents: Incident[] = [];
  isPetitionToggleActive = false;
  filter = {} as TableFilter;

  async test() {
    await axios
      .get(
        `https://${process.env.VUE_APP_API_GATEWAY}/mz/lost/requests?limit=5&offset=1`
      )
      .catch(() => console.log(''));
    await axios
      .get(
        `https://${process.env.VUE_APP_API_GATEWAY}/api/mz/lost/requests?limit=5&offset=1`
      )
      .catch(() => console.log(''));
  }

  resendSelected(): void {
    switch (this.isPetitionToggleActive) {
      case null:
        this.resendStatements();
        break;

      case true:
        this.resendPetitionsStatus();
        break;

      case false:
        this.resendPetitions();
        break;
    }
  }

  async resendStatements(): Promise<void> {
    const { resentItems, failedItems } = await LostStatementService.resend(
      this.selectedIncidents
    );
    this.showNotify(resentItems, failedItems);
  }

  async resendPetitions(): Promise<void> {
    const { resentItems, failedItems } = await LostPetitionService.resend(
      this.selectedIncidents
    );
    this.showNotify(resentItems, failedItems);
  }

  async resendPetitionsStatus(): Promise<void> {
    const {
      resentItems,
      failedItems,
    } = await LostPetitionService.requestStatus(this.selectedIncidents);
    this.showNotify(resentItems, failedItems);
  }

  fetchIncidents(): void {
    switch (this.isPetitionToggleActive) {
      case null:
        this.fetchStatements();

        break;
      case true:
        this.fetchPetitionsStatus();
        break;

      case false:
        this.fetchPetitions();
        break;
    }
  }

  async fetchPetitions(): Promise<void> {
    const {
      items = [],
      pagination = this.filter.pagination,
    } = await this.withLoading<PaginatedResponse<PetitionInfo>>(() =>
      LostPetitionService.getPaginated(this.filter)
    );
    // TODO: Обеспечиваем обратную совместимость, пока новая модель mz-request не вышла в релиз и на юат
    this.incidents = items.map((incident: Incident) => {
      // @ts-ignore
      incident.className = incident.clazz ?? incident.class ?? '';
      return incident;
    });
    this.filter.pagination = pagination;
  }

  async fetchStatements(): Promise<void> {
    const {
      items = [],
      pagination = this.filter.pagination as TablePagination,
    } = await this.withLoading<PaginatedResponse<RequestInfo>>(() =>
      LostStatementService.getPaginated(this.filter)
    );
    // TODO: Обеспечиваем обратную совместимость, пока новая модель mz-request не вышла в релиз и на юат
    this.incidents = items.map((incident: Incident) => {
      // @ts-ignore
      incident.className = incident.clazz ?? incident.class ?? '';
      return incident;
    });
    this.filter.pagination = pagination;
  }

  async fetchPetitionsStatus(): Promise<void> {
    const {
      items = [],
      pagination = this.filter.pagination,
    } = await this.withLoading<PaginatedResponse<PetitionInfo>>(() =>
      LostPetitionService.getPaginatedStatuses(this.filter)
    );
    // TODO: Обеспечиваем обратную совместимость, пока новая модель mz-request не вышла в релиз и на юат
    this.incidents = items.map((incident: Incident) => {
      // @ts-ignore
      incident.className = incident.clazz ?? incident.class ?? '';
      return incident;
    });
    this.filter.pagination = pagination;
  }

  showNotify(
    successItems: RestOutputBean[],
    failedItems: RestOutputBean[]
  ): void {
    const notify = (
      message: string,
      color: 'negative' | 'positive' = 'positive'
    ) => {
      notifyError(message, color === 'negative' ? 'error' : 'check', color);
    };

    successItems.forEach((el) =>
      notify(el.message ?? this.$t('base.messages.success').toString())
    );
    failedItems.forEach((el) =>
      notify(el.message ?? this.$t('base.messages.fail').toString(), 'negative')
    );
  }

  paginationChangeHandler(filter: TableFilter): void {
    this.filter = filter;
    this.fetchIncidents();
  }

  search(searchText: string): void {
    this.filter.search = searchText;
    this.fetchIncidents();
  }

  init(): void {
    (this as Filterable).initFilter();
    this.fetchIncidents();
  }

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

export default Incidents;
