import { Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { FastifyRequest, FastifyReply } from 'fastify';
import { logger } from '@/core';
import { AuthenticationUser } from './core/entities';
import { AuthService } from './core/module/auth/auth.service';
import { isNilOrEmpty, notNilEmpty } from 'qx-util';
import { UniRes } from './config';
import { CookieConstants } from './core/constants';

@Injectable()
export class AppService {
  /**
   * 是否开启权限认证
   *
   * @author chitanda
   * @date 2021-08-22 17:08:52
   * @protected
   * @type {boolean}
   */
  protected enablePermissionValid: boolean;

  /**
   * Creates an instance of AppService.
   *
   * @author chitanda
   * @date 2021-08-22 17:08:46
   * @param {ConfigService} configService
   */
  constructor(private readonly configService: ConfigService, private readonly authService: AuthService) {
    this.enablePermissionValid = this.configService.get<boolean>('ibiz.enablePermissionValid');
  }

  /**
   * 获取应用数据
   *
   * @author chitanda
   * @date 2021-08-18 01:08:04
   * @param {FastifyRequest} request
   * @return {*}  {Promise<Record<string, unknown>>}
   */
  async getAppData(request: FastifyRequest, response: FastifyReply): Promise<Record<string, unknown>> {
    const appData: Record<string, any> = {};
    const appMenu: any[] = [];
    const uniRes: any[] = [];
    const username = request.cookies[CookieConstants.USER_NAME];
    if (isNilOrEmpty(username)) {
      throw new UnauthorizedException(null, '用户信息获取异常，请检查是否已启动 cookie 功能');
    }
    const curUser: AuthenticationUser = await this.authService.loginByUsername(request, response, username);
    if (this.enablePermissionValid) {
      try {
        if (notNilEmpty(UniRes) && isNilOrEmpty(curUser.uniRes)) {
          uniRes.push(...await this.authService.testSysUniRes(request, response, UniRes));
          curUser.uniRes = uniRes;
        }
      } catch (err) {
        logger.error(err);
      }
    }
    if (curUser) {
      const context: any = curUser.sessionParams || {};
      context.srfusername = curUser.personname;
      appData.context = context;
      appData.enablepermissionvalid = this.enablePermissionValid;
      if (curUser.superuser == 1) {
        appData.enablepermissionvalid = false;
      }
    }
    appData.unires = uniRes;
    appData.appmenu = appMenu;
    return appData;
  }
}
