import { memberStore } from "@/store/member";
import { ElMessage } from "element-plus";
import { tagsStore } from "@/store/tags";
import { storeToRefs } from "pinia";

let loginPromise = null;
function getLoginPromise() {
  if (loginPromise) return loginPromise;
  const store = memberStore();
  const { getMemberInfo, getCorpInfo } = store;
  loginPromise = Promise.all([getMemberInfo(), getCorpInfo()]);
  return loginPromise;
}
export default async function useGuard(to, from) {
  const logined = await useLogin(to);
  return logined;
}
async function useLogin(to) {
  const { name } = to;
  const store = memberStore();
  const { setLogined } = store;
  // 登陆页面绕过授权
  if (name === "LOGIN") {
    setLogined("logined");
    return true;
  }
  if (!sessionStorage.getItem("isLogin")) {
    return {
      name: "LOGIN",
    };
  }
  const [account] = await getLoginPromise();
  if (!account || account.accountState !== 'enable') {
    ElMessage.error(!account ? '获取账号信息失败' : "账号未启用，请联系管理员");
    return {
      name: "LOGIN",
    };
  }
  setLogined("logined");

  const { setUserMenus } = tagsStore();
  const { menus, tags, menuTree } = storeToRefs(tagsStore());
  if (menus.value.length === 0) {
    try {
      await setUserMenus(account.roleIds);
    } catch (e) {
      ElMessage.error(e?.message || "Failed to fetch menu info");
      // 清理登录状态
      sessionStorage.removeItem("isLogin");
      sessionStorage.removeItem("userId");
      return {
        name: "LOGIN",
      };
    }
  }
  if (menus.value.some(i => i.path === to.name)) {
    return true;
  }
  const firstMenu = menuTree.value[0] && menuTree.value[0].children && menuTree.value[0].children[0] ? menuTree.value[0].children[0] : null;
  if (tags.value.length) {
    return true;
  }
  // 如果没有菜单信息，跳转到第一个菜单
  if (tags.value.length === 0 && firstMenu && firstMenu.path == name) {
    return true
  }
  if (tags.value.length === 0 && firstMenu) {
    return { name: firstMenu.path }
  }
  ElMessage.error("菜单信息获取失败，请重新登录");
  return { name: 'LOGIN' }
}
