/*
 * @Author: Maple
 * @Date: 2021-03-22 11:42:26
 * @LastEditors: Do not edit
 * @LastEditTime: 2021-06-17 14:58:35
 * @Description: 全局权限服务
 */
import { Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';
import { cacheConf } from '@conf/cache.conf';
import { StartupService } from '@core';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { SettingsService } from '@delon/theme';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { BaseService } from '../core/base.service';
import { EACacheService } from '../core/cache.service';

@Injectable({
  providedIn: 'root',
})
export class EAAuthorizationService extends BaseService {
  // 获取我的角色
  public $api_get_my_roles = `/chia/roleInfo/getMyRoleList`;

  constructor(public injector: Injector) {
    super(injector);
  }

  // 注入路由
  private get router(): Router {
    return this.injector.get(Router);
  }
  // 注入缓存服务
  private get cacheSrv(): EACacheService {
    return this.injector.get(EACacheService);
  }
  // 注入令牌服务
  private get tokenSrv(): ITokenService {
    return this.injector.get(DA_SERVICE_TOKEN);
  }
  // 注入路由复用服务
  private get reuseTabService(): ReuseTabService {
    return this.injector.get(ReuseTabService);
  }
  // 注入全局启动服务
  private get startSrv(): StartupService {
    return this.injector.get(StartupService);
  }
  // 注入全局设置服务
  private get settingSrv(): SettingsService {
    return this.injector.get(SettingsService);
  }

  /**
   * 获取角色列表
   * @param force 强制刷新 默认值：false
   * @returns 角色列表， 类型 Array<any> | Observable<Array<any>>
   */
  getMyRoles(force: boolean = false): Observable<Array<any>> {
    // 强制刷新
    if (force) {
      return this.refreshRoles();
    }

    // 从缓存中提取角色
    const roles = this.cacheSrv.get(cacheConf.role) || [];

    // 当缓存中不存在角色时，尝试从服务器拉取角色数据
    if (roles.length > 0) {
      return of(roles);
    }

    return this.refreshRoles();
  }

  /**
   * 刷新角色权限
   */
  private refreshRoles(): Observable<Array<any>> {
    return this.request(this.$api_get_my_roles).pipe(
      tap((res) => {
        this.cacheSrv.set(cacheConf.role, res);
      }),
    );
  }
}
