import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { ApplicationService } from '@core/application';
import { BreadcrumbService } from '@core/breadcrumb';
import { CacheService } from '@core/cache';
import { Config } from '@core/config';
import { ToastService } from '@core/toast';
import { DomainRemissionService } from '@domain/remission';
import { UiErrorModalComponent, UiModalService } from '@ui/modal';

@Component({
  selector: 'page-finish-remission',
  templateUrl: 'finish-remission.component.html',
  styleUrls: ['finish-remission.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FinishRemissionComponent implements OnInit, OnDestroy {
  get processId() {
    return this._config.get('process.ids.remission');
  }

  constructor(
    private _activatedRoute: ActivatedRoute,
    private _applicationService: ApplicationService,
    private _modal: UiModalService,
    private _remissionService: DomainRemissionService,
    private _router: Router,
    private _breadcrumb: BreadcrumbService,
    private _config: Config,
    private _cache: CacheService,
    private _toastService: ToastService
  ) {}

  async ngOnInit() {
    await this.removeBreadcrumbs();
    await this.addBreadcrumbIfNotExists();
  }

  ngOnDestroy(): void {
    this._cache.delete({ processId: String(this.processId) });
  }

  async createRemission() {
    const returnId = +this._activatedRoute.snapshot.params?.returnId;

    if (returnId) {
      try {
        const returnDto = await this._remissionService.getReturn(returnId).toPromise();
        this.clearProcessData();
        await this._router.navigate(['/filiale', 'remission', 'create', returnDto.returnGroup], {
          queryParams: { ...this._activatedRoute.snapshot.queryParams },
        });
      } catch (err) {
        this._modal.open({
          content: UiErrorModalComponent,
          title: 'Fehler beim fortsetzen der Remission',
          data: err,
        });
      }
    } else {
      this._modal.open({
        content: UiErrorModalComponent,
        title: 'Fehler beim Abschließen der Remission',
        data: new Error('Keine gültige ID'),
      });
    }
  }

  async completeRemission() {
    const returnId = +this._activatedRoute.snapshot.params?.returnId;

    if (returnId) {
      try {
        await this._remissionService.completeRemission(returnId);
        this.clearProcessData();
        this.createToast();
        await this.navigateToList();
      } catch (err) {
        this._modal.open({
          content: UiErrorModalComponent,
          title: 'Fehler beim Abschließen der Remission',
          data: err,
        });
      }
    } else {
      this._modal.open({
        content: UiErrorModalComponent,
        title: 'Fehler beim Abschließen der Remission',
        data: new Error('Keine gültige ID'),
      });
    }
  }

  async navigateToList() {
    await this._router.navigate(['/filiale', 'remission', 'list']);
  }

  createToast() {
    const supplierId = +this._activatedRoute?.snapshot?.queryParams?.supplier;
    this._toastService.create({
      title: 'Warenbegleitschein versendet',
      text:
        supplierId === 1
          ? 'Der Warenbegleitschein wurde digital an ZL versendet.'
          : supplierId === 2
          ? 'Der Warenbegleitschein wurde digital an Blank versendet.'
          : '',
    });
  }

  clearProcessData() {
    // Muss beim Abschließen der Remission erfolgen, da er sonst auf die Liste routet (siehe remission.component.ts updateProcess())
    this._applicationService.patchProcess(this.processId, {
      closeable: true,
      data: {},
    });
  }

  async addBreadcrumbIfNotExists() {
    const returnId = +this._activatedRoute.snapshot.params?.returnId;
    await this._breadcrumb.addBreadcrumbIfNotExists({
      key: this.processId,
      name: 'Wanne abgeschlossen',
      path: `/filiale/remission/${returnId}/finish-remission`,
      params: this._activatedRoute.snapshot.queryParams,
      section: 'branch',
      tags: ['remission', 'finish-remission'],
    });
  }

  async removeBreadcrumbs() {
    await this._breadcrumb.removeBreadcrumbsByKeyAndTags(this.processId, ['remission', 'shipping-documents']);
    await this._breadcrumb.removeBreadcrumbsByKeyAndTags(this.processId, ['remission', 'finish-shipping-document']);
  }
}
