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

/**
 * 没有权限的错误处理器
 *
 * @author lxm
 * @date 2022-10-11 14:10:10
 * @export
 * @class UnauthorizedHandler
 */
export class UnauthorizedHandler implements IErrorHandler {
  match(error: unknown): boolean {
    return error instanceof HttpError && error.status === 401;
  }

  /**
   * cas登录处理
   *
   * @author lxm
   * @date 2022-10-11 14:10:35
   * @protected
   * @returns {*}  {Promise<void>}
   */
  protected 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
   * @returns {*}  {Promise<void>}
   */
  protected async normalLogin(): Promise<void> {
    const ru = window.location.hash.replace('#', '');
    const targetUrl = `${UrlHelper.routeBase}/login?ru=${encodeURIComponent(
      ru,
    )}`;
    // 跳转登录地址,不加延时vue-router感知不到路由变更。
    setTimeout(() => {
      window.location.href = targetUrl;
    }, 0);
  }

  /**
   * 没有权限处理
   *
   * @author lxm
   * @date 2022-10-11 14:10:50
   * @returns {*}  {Promise<void>}
   */
  handle(error: unknown): boolean | undefined {
    if (error instanceof HttpError && error.status === 401) {
      if (ibiz.env.loginMode === LoginMode.CAS) {
        this.casLogin();
      } else {
        this.normalLogin();
      }
      return true;
    }
  }
}
