import { useSystemStore } from "@/stores/modules/systemStore";
import { useWalletStore } from "@/stores/modules/walletStore";

import { whitelistRoutes } from "@/router/whitelist";
import { systemRoutes } from "@/router/system";


const paths = whitelistRoutes.map(item => {
  return item.path
});

const mainPath = systemRoutes[0].children.filter(item => {
  return item.meta?.tabbar || false
}).map(cItem => {
  return cItem.path
});


export function createRouterGuards(router) {
  const systemStore = useSystemStore();
  const walletStore = useWalletStore();
  // 路由拦截
  router.beforeEach(async (to, from, next) => {
    if (import.meta.env.VITE_DAPP_BUILD == "1") {
      if (mainPath.includes(from.path) && paths.includes(to.path) && to.path != '/login') {
        // 停止跳转
        next(false)
        return
      }

      if (paths.includes(to.path)) {
        return next();
      }

      // 没有钱包，则跳转到login 页
      if (!walletStore.privateKey || !walletStore.account || !systemStore.token) {
        return next("/login");
      }
    }

    if (import.meta.env.VITE_DAPP_BUILD == "2") {
      if (to.path == '/login') {
        next()
      }
      if (!systemStore.userUuid) {
        return next("/login");
      }
      // if (!systemStore.token) {
      //   return next("/login");
      // }
    }
    next();
  });

  router.afterEach((to, _, next) => { });

  // 错误
  router.onError((error) => {
    console.log(error, "路由错误");
  });
}
