import qs from 'qs';
import { LoginMode, RuntimeError, UrlHelper } from '@ibiz-template/core';
import router from '@/router';

/**
 * 没有权限的处理器
 *
 * @author lxm
 * @date 2022-10-11 14:10:10
 * @export
 * @class UnauthorizedHandler
 */
export class UnauthorizedHandler {
  /**
   * cas登录处理
   *
   * @author lxm
   * @date 2022-10-11 14:10:35
   * @protected
   * @static
   * @returns {*}  {Promise<void>}
   */
  protected static async casLogin(): Promise<void> {
    if (!ibiz.env.casLoginUrl) {
      throw new RuntimeError('找不到环境参数casLoginUrl');
    }
    const { origin } = window.location;
    const baseUrl = `${origin}${ibiz.env.baseUrl}`;

    // 登录后返回来的登录的地址
    const backUrl = `${baseUrl}/cas/v7/login${qs.stringify(
      {
        RU: UrlHelper.fullPath,
        base: baseUrl,
      },
      { addQueryPrefix: true },
    )}`;

    // 要跳转的cas的登录页和参数
    const hasQueryPrefix = ibiz.env.casLoginUrl.indexOf('?') !== -1;
    const targetUrl =
      ibiz.env.casLoginUrl +
      (hasQueryPrefix ? '&' : '?') +
      qs.stringify(
        {
          service: backUrl,
        },
        { addQueryPrefix: false },
      );

    // 跳转cas登录地址
    window.location.href = targetUrl;
  }

  /**
   * 普通登录处理
   *
   * @author lxm
   * @date 2022-10-11 14:10:24
   * @protected
   * @static
   * @returns {*}  {Promise<void>}
   */
  protected static async normalLogin(): Promise<void> {
    const ru = window.location.hash.replace('#', '');
    router.push({ path: '/login', query: { ru } });
  }

  /**
   * 没有权限处理
   *
   * @author lxm
   * @date 2022-10-11 14:10:50
   * @static
   * @returns {*}  {Promise<void>}
   */
  static async handle(): Promise<void> {
    if (ibiz.env.loginMode === LoginMode.CAS) {
      await this.casLogin();
    } else {
      this.normalLogin();
    }
  }
}