/*
 * @Author: Maple
 * @Date: 2021-03-22 11:42:26
 * @LastEditors: Do not edit
 * @LastEditTime: 2021-05-27 14:06:18
 * @Description: 全局核心服务
 */
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { CacheService } from '@delon/cache';
import { SettingsService } from '@delon/theme';
import { EnvironmentService } from '@env/environment.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Injectable({
  providedIn: 'root',
})
export class CoreService {
  // 获取当前登录用户信息
  public $api_get_current_user_info = `/scm/cuc/cuc/user/getUserDetail`;

  // 获取当前用户所拥有的菜单
  public $api_get_current_user_menus = `/scm/cuc/cuc/functionInfo/getUserHaveFunctionsList`;

  constructor(private injector: Injector) {}
  // 注入路由
  public get router(): Router {
    return this.injector.get(Router);
  }

  // 注入全局设置服务
  public get settingSrv(): SettingsService {
    return this.injector.get(SettingsService);
  }

  // 注入缓存服务
  public get cacheSrv(): CacheService {
    return this.injector.get(CacheService);
  }

  // 注入令牌服务
  public get tokenSrv(): ITokenService {
    return this.injector.get(DA_SERVICE_TOKEN);
  }

  // 注入消息服务
  public get msgSrv(): NzMessageService {
    return this.injector.get(NzMessageService);
  }

  // 注入环境服务
  public get envSrv(): EnvironmentService {
    return this.injector.get(EnvironmentService);
  }

  // 注入路由复用服务
  private get reuseTabService(): ReuseTabService {
    return this.injector.get(ReuseTabService);
  }

  // 登录状态
  public get loginStatus(): boolean {
    try {
      return !!this.tokenSrv.get()?.token;
    } catch (error) {
      return false;
    }
  }

  // 权限认证凭据（TOKEN）
  public get token(): string {
    return this.tokenSrv.get()?.token || '';
  }

  /**
   * 登出系统
   * @param showMsg 是否显示登录过期弹窗
   */
  logout(showMsg: boolean = false): void {
    if (showMsg) {
      this.msgSrv.warning('未登录或登录信息已过期，请重新登录！');
    }
    this.settingSrv.setUser({});
    this.tokenSrv.clear();
    this.cacheSrv.clear();
    this.router.navigate([this.tokenSrv.login_url]);
  }
}
