import router from "@/router";
import { ResultEnum } from "@/enums/httpEnum";
import { ErrorPageNameMap } from "@/enums/pageEnum";
import { clearLocalStorage, getLocalStorage } from "./storage";
import { StorageEnum } from "@/enums/storageEnum";
import { cryptoDecode } from "./crypto";
/**
 * * 根据名字跳转路由
 * @param pageName
 * @param isReplace
 * @param windowOpen
 */
export const routerTurnByName = (
  pageName: string,
  isReplace?: boolean,
  windowOpen?: boolean
) => {
  if (windowOpen) {
    const path = fetchPathByName(pageName, "href");
    openNewWindow(path);
    return;
  }
  if (isReplace) {
    router.replace({
      name: pageName,
    });
    return;
  }
  router.push({
    name: pageName,
  });
};

/**
 * * 错误页重定向
 * @param icon
 * @returns
 */
export const redirectErrorPage = (code: ResultEnum) => {
  if (!code) return false;
  const pageName = ErrorPageNameMap.get(code);
  if (!pageName) return false;
  routerTurnByName(pageName);
};

/**
 * * 根据名称获取路由信息
 * @param pageName
 * @param pageName
 */
export const fetchPathByName = (pageName: string, p?: string) => {
  try {
    const pathData = router.resolve({
      name: pageName,
    });
    return p ? (pathData as any)[p] : pathData;
  } catch (error) {
    console.log("查询路由信息失败，请联系管理员！");
  }
};

/**
 * * 新开页面
 * @param url
 */
export const openNewWindow = (url: string) => {
  return window.open(url, "_blank");
};

/**
 * * 判断是否登录（现阶段是有 login 数据即可）
 * @return boolean
 */
export const loginCheck = () => {
  try {
    const info = getLocalStorage(StorageEnum.ZS_LOGIN_INFO_STORE);
    if (!info) return false;
    const decodeInfo = cryptoDecode(info);

    if (decodeInfo) {
      return true;
    }
    return false;
  } catch (error) {
    return false;
  }
};

/**
 * * 退出
 */
export const logout = () => {
  clearLocalStorage(StorageEnum.ZS_LOGIN_INFO_STORE);
  routerTurnByName("Login");
};
