interface ToLoginPageOptions {
  callbackUrl?: boolean | string;
  replace?: boolean;
}

/** 转换 callbackUrl */
function callbackUrl2query(url: ToLoginPageOptions["callbackUrl"] = true) {
  let _url = url;
  if (typeof _url === "boolean" && _url) {
    // 如果是 true 就是用当前 url 作为登录成功后回调地址
    _url = encodeURIComponent(window.location.href);
  }
  const query = url ? `?callbackUrl=${_url}` : "";
  return query;
}

/** 区分正式和测试环境返回不同的 url */
function formatUrl(url: string, query: string) {
  let _url = `${url}${query}`;
  if (process.env.NODE_ENV === "production") {
    if (window.location.host.endsWith(".kube.ucas")) {
      // 测试环境
      _url = `https://test-www.kube.ucas/login${query}`;
    } else {
      // 正式环境
      _url = `https://xxyy.co/#/login${query}`;
    }
  }
  return _url;
}

/** 页面跳转 */
function toHandler(url: string, replace: boolean) {
  if (replace) {
    window.location.replace(url);
  } else {
    window.location.href = url;
  }
}

/**
 * 私有部署登录
 * */
function toLoginPrivate({
  replace = false,
  callbackUrl,
}: ToLoginPageOptions = {}) {
  const queryStr = callbackUrl2query(callbackUrl);

  // 私有部署没有租户相关业务，使用 minio 自有登录页
  const url = `/login${queryStr}`;

  toHandler(url, replace);
}

/**
 * 租户版本登陆
 * */
function toLoginTenant({
  replace = false,
  callbackUrl,
}: ToLoginPageOptions = {}) {
  const queryStr = callbackUrl2query(callbackUrl);
  // 租户版，使用自有登录页
  const url = formatUrl(`/saturn/fullscreen/login`, queryStr);

  toHandler(url, replace);
}

/**
 * 模块联邦本地测试环境登陆
 * */
function toLoginLocalTest({ callbackUrl }: ToLoginPageOptions = {}) {
  const queryStr = callbackUrl2query(callbackUrl);
  const url = `/saturn/fullscreen/login${queryStr}`;

  toHandler(url, false);
}

/** 跳转到登录页 */
export const toLoginPage = (options?: ToLoginPageOptions): void => {
  if (process.env.REACT_APP_SATURN_ENV === "private") {
    toLoginPrivate(options);
    return;
  }

  if (process.env.REACT_APP_LOCAL_TEST) {
    toLoginLocalTest(options);
    return;
  }

  toLoginTenant(options);
};
