import { Injectable, Injector } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { ACLGuard, ACLService } from '@delon/acl';
import { MenuService, SettingsService } from '@delon/theme';
import { EAUserService } from '@shared';
import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

@Injectable()
export class AuthGuard extends ACLGuard {
  constructor(
    srv: ACLService,
    public srv1: ACLService,
    private menuService: MenuService,
    private settings: SettingsService,
    private userService: EAUserService,
    router: Router,
    private inject: Injector
  ) {
    super(srv, router, inject);
  }

  canActivate(route: ActivatedRouteSnapshot, _state: RouterStateSnapshot): Observable<boolean> {
    // if (Object.keys(route.params)?.length > 0 || !route.routeConfig?.path) {
    //   return super.canActivate(route, _state);
    // } else {
    //   return super.canActivate(route, _state);
    // }
    return super.canActivate(route, _state);
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    if (childRoute.routeConfig?.loadChildren || childRoute.routeConfig?.children) {
      return super.canActivateChild(childRoute, state);
    } else {
      return this.handle(childRoute, state, 2, this.settingRoute(childRoute.params, state.url));
    }
  }

  private handle(route: ActivatedRouteSnapshot, state: RouterStateSnapshot, type: 1 | 2, router?: string): Observable<boolean> {
    if (!router) {
      return type === 1 ? super.canActivate(route, state) : super.canActivateChild(route, state);
    }
    return this.userService
      .request('/api/mdc/cuc/userAuthority/isUserAdmin', {
        appUserId: this.settings.user.appUserId
      })
      .pipe(
        switchMap(res => {
          if (res) {
            // 超级管理员赋值全量权限
            this.srv1.setFull(true);
            return of(true);
          } else {
            // 如果不是超级管理员 获取权限
            return this.userService.request('/api/mdc/cuc/functionButton/getUserFunctionButton', { link: router });
          }
        }),
        switchMap(res => {
          if (res?.abilities) {
            this.srv1.setAbility(res.abilities || []);
            // this.menuService.resume();
            this.userService.loadUserMenus();
          }
          return type === 1 ? super.canActivate(route, state) : super.canActivateChild(route, state);
        })
      );
  }

  /**
   * 根据参数拼接原始路由
   * @param params 参数
   * @param route 实际路由
   * @returns
   */
  private settingRoute(params: any, route: string) {
    let _route = route;
    if (_route.indexOf('?') > -1) {
      _route = route.split('?')[0];
    }
    for (const key of Object.keys(params)) {
      if (_route.indexOf(params[key]) > -1) {
        _route = _route.replace(params[key], ':' + key);
      }
    }

    return _route;
  }
}
