import { HttpErrorResponse } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NcApplication, NgCortexService } from '@ng-cortex/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';
import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';

/** 应用桥接页面 */
@Component({
  selector: 'nc-application-bridge',
  templateUrl: './nc-application-bridge.page.html',
  styleUrls: ['./nc-application-bridge.page.scss']
})
export class NcApplicationBridgePage implements OnInit {

  constructor(
    private _router: Router,
    private _nzModalService: NzModalService,
    private _nzNotificationService: NzNotificationService,
    private _ngCortexService: NgCortexService) { }

  /** 初始化后 */
  ngOnInit(): void {
    const route = this._router.url;
    const { applicationList, currentApplication, routeRecordList } = this._ngCortexService.data;
    const applicationCode = route.match(/[^/]+/g)![1];
    const application = applicationList.find(application => application.code === applicationCode);
    if (application && application !== currentApplication) {
      if (routeRecordList.length > 0) {
        if (currentApplication) {
          this._nzModalService.confirm({
            nzTitle: '切换应用',
            nzContent:
              '<p>是否从 <strong>“' + currentApplication.name + '”</strong> 切换至 <strong>“' + application.name + '”</strong> ？</p>' +
              '<div>切换应用后，当前打开页面将被全部关闭，导航菜单将重新加载。</div>',
            nzOnOk: () => this._changeApplication(application),
            nzOnCancel: () => this._ngCortexService.closeRoute(route)
          });
        } else {
          this._nzModalService.confirm({
            nzTitle: '进入应用',
            nzContent:
              '<p>是否进入 <strong>“' + application.name + '”</strong> ？</p>' +
              '<div>进入应用后，当前打开页面将被全部关闭，导航菜单将重新加载。</div>',
            nzOnOk: () => this._changeApplication(application),
            nzOnCancel: () => this._ngCortexService.closeRoute(route)
          });
        }
      } else {
        this._changeApplication(application);
      }
    } else {
      this._ngCortexService.closeRoute(route, this._ngCortexService.routeForApplication404);
    }
  }

  /**
   * 改变应用
   * @param application 应用
   */
  private _changeApplication(application: NcApplication): void {
    const { currentApplication } = this._ngCortexService.data;
    (window as any).Spinner.start();
    this._ngCortexService.changeApplication(application)
      .pipe(catchError((httpErrorResponse: HttpErrorResponse) => {
        this._nzNotificationService.error((currentApplication ? '切换' : '进入') + '应用失败', httpErrorResponse.error && httpErrorResponse.error.message || httpErrorResponse.statusText);
        return of(null);
      }))
      .subscribe(() => (window as any).Spinner.done());
  }

}
