import { Component, ElementRef, OnDestroy, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NcApplication, NcPassport, NgCortexService } from '@ng-cortex/core';
import { NzModalService } from 'ng-zorro-antd/modal';
import { delay } from 'rxjs/operators';

/** 应用索引页面 */
@Component({
  selector: 'nc-application-index',
  templateUrl: './nc-application-index.page.html',
  styleUrls: ['./nc-application-index.page.less']
})
export class NcApplicationIndexPage implements OnInit, OnDestroy {

  /** 问候语 */
  _greeting!: string;
  /** 通行证 */
  _passport: NcPassport | null = null;
  /** 应用索引路由 */
  _routeForApplicationIndex!: string;
  /** 应用组列表 */
  _applicationGroupList: any[] = [];

  /** 取消通行证 */
  private _cancelPassportObserveFn = () => { };

  constructor(
    private _elementRef: ElementRef,
    private _router: Router,
    private _nzModalService: NzModalService,
    private _ngCortexService: NgCortexService) { }

  /** 初始化后 */
  ngOnInit(): void {
    const route = this._router.url;
    const element = this._elementRef.nativeElement;
    const { applicationList, currentApplication, routeRecordList } = this._ngCortexService.data;
    if (applicationList.length === 1) {
      this._ngCortexService.closeRoute(route);
    } else {
      if (routeRecordList.length === 0) {
        if (currentApplication) {
          this._ngCortexService.closeCurrentApplication();
        }
      } else {
        element.hidden = true;
        this._nzModalService.confirm({
          nzTitle: '返回首页',
          nzContent: currentApplication
            ? '即将退出 <strong>“' + currentApplication.name + '”</strong> 应用，当前打开页面将被全部关闭。'
            : '当前打开页面将被全部关闭。',
          nzOnOk: () => {
            element.hidden = false;
            if (currentApplication) {
              this._ngCortexService.closeCurrentApplication();
            } else {
              this._ngCortexService.closeAllRoutes();
            }
          },
          nzOnCancel: () => {
            this._ngCortexService.closeRoute(route);
          }
        });
      }
    }
    const hours = new Date().getHours();
    if (hours >= 0 && hours <= 12) {
      this._greeting = '上午好';
    } else if (hours > 12 && hours <= 14) {
      this._greeting = '中午好';
    } else if (hours > 14 && hours <= 18) {
      this._greeting = '下午好';
    } else {
      this._greeting = '晚上好';
    }
    const passportSubscription = this._ngCortexService.passport.pipe(delay(24)).subscribe(passport => this._passport = passport);
    this._cancelPassportObserveFn = () => { passportSubscription.unsubscribe() };
    this._routeForApplicationIndex = this._ngCortexService.routeForApplicationIndex;
    this._generateApplicationGroupList();
  }

  /** 注销后 */
  ngOnDestroy(): void {
    this._cancelPassportObserveFn();
  }

  /**
   * 申请应用
   * @param application 应用
   */
  _applyApplication(application: any): void {
    this._nzModalService.info({
      nzTitle: '申请使用',
      nzContent: '您所在的企业尚未进行公司备案，请先提交公司备案。'
    });
  }

  /** 生成应用组列表 */
  private _generateApplicationGroupList(): void {
    const { applicationList } = this._ngCortexService.data;
    const groupMap = new Map();
    applicationList.forEach(application => {
      const groupName = application.groupName || `其它`;
      let group = groupMap.get(groupName);
      if (!group) {
        group = { name: groupName, children: [] };
        groupMap.set(groupName, group);
      }
      group.children.push(application);
    });
    this._applicationGroupList = Array.from(groupMap.values());
  }

}
