import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, NavigationExtras } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd';
import { Subscription } from 'rxjs';
import { NgCortexService } from '@ng-cortex/core';

@Component({
  selector: 'nc-bridge',
  templateUrl: './nc-bridge.component.html',
  styleUrls: ['./nc-bridge.component.scss']
})
export class NcBridgeComponent implements OnInit, OnDestroy {

  private _changeAppSubscription: Subscription = null;

  constructor(
    private _router: Router,
    private _modalSrv: NzModalService,
    private _ncSrv: NgCortexService
  ) { }

  ngOnInit() {
    if (this._ncSrv.passport) {
      const appCode = this._router.url.match(/[^/]+/)[0];
      const app = this._ncSrv.apps.find(i => i.code == appCode);
      if (app && app !== this._ncSrv.activeApp) {
        if (this._ncSrv.activeApp && this._ncSrv.routeContents.length > 0) {
          this._modalSrv.confirm({
            nzTitle: `切换应用`,
            nzContent: `
              <p>是否从 <strong>“${this._ncSrv.activeApp.name}”</strong> 切换至 <strong>“${app.name}”</strong> ？</p>
              <div>切换应用后，当前打开模块将被全部关闭，导航菜单将重新加载。</div>
            `,
            nzOnOk: () => {
              this._changeAppSubscription = this._ncSrv.changeApp(appCode)
                .subscribe(
                  () => this._navigateByUrl(this._router.url, { replaceUrl: true }),
                  () => this._navigateByUrl(`/500`, { replaceUrl: true })
                );
            },
            nzOnCancel: () => {
              this._navigateByUrl(`/${this._ncSrv.activeApp.code}`, { replaceUrl: true });
            }
          });
        } else {
          this._changeAppSubscription = this._ncSrv.changeApp(appCode)
            .subscribe(
              () => this._navigateByUrl(this._router.url, { replaceUrl: true }),
              () => this._navigateByUrl(`/500`, { replaceUrl: true })
            );
        }
      } else {
        this._navigateByUrl(`/404`, { replaceUrl: true });
      }
    } else {
      this._ncSrv.setNavigateAfterLogin(this._router.url);
      this._navigateByUrl(`/403`, { replaceUrl: true });
    }
  }

  ngOnDestroy() {
    this._changeAppSubscription && this._changeAppSubscription.unsubscribe();
  }

  private _navigateByUrl(url: string, extras?: NavigationExtras) {
    this._ncSrv.closeRoute(this._router.url, null);
    setTimeout(() => {
      this._router.navigateByUrl(url, extras)
        .then(result => {
          if (!result) {
            this._router.navigateByUrl(url, extras);
          }
        });
    });
  }

}
