import router from "@/router";
import { useUserStore } from "@/store/modules/user";
import { usePermissionStore } from "@/store/modules/permission";
import { useDictionaryStore } from "@/store/modules/dictionary";

import NProgress from "@/utils/nprogress";
import { getUserDicts } from "@/api/auth";

export function setupPermission() {
  // 白名单路由
  const whiteList = [""];

  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    const hasToken = localStorage.getItem("token");
    if (hasToken) {
      if (to.path === "/login") {
        // 如果已登录，跳转首页
        next({ path: "/" });
        NProgress.done();
      } else {
        const dictStore = useDictionaryStore();
        if (
          !dictStore.dicts.value ||
          JSON.stringify(dictStore.dicts.value) === "{}"
        ) {
          const res = await getUserDicts(dictStore.types);
          if (res.data) {
            dictStore.dicts = res?.data;
          }
        }

        const userStore = useUserStore();
        // const hasRoles =
        //   userStore.user.roles && userStore.user.roles.length > 0;
        if (userStore.isGetAuth) {
          // 未匹配到任何路由，跳转404
          if (to.matched.length === 0) {
            from.name ? next({ name: from.name }) : next("/404");
          } else {
            next();
          }
        } else {
          const permissionStore = usePermissionStore();
          try {
            const { menus } = await userStore.getUserInfo();

            const accessRoutes = await permissionStore.generateRoutes(menus);

            accessRoutes.forEach((route) => {
              router.addRoute(route);
            });
            next({ ...to, replace: true });
          } catch (error) {
            console.error("beforeEach error", error);
            // 移除 token 并跳转登录页
            await userStore.resetToken();
            next(`/login?redirect=${to.path}`);
            NProgress.done();
          }
        }
      }
    } else {
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) !== -1) {
        // const dictStore = useDictionaryStore();
        // dictStore.checkDicts();
        next();
      } else {
        if (to.path === "/login") {
          next();
        } else {
          next(`/login`);
        }
        NProgress.done();
      }
    }
  });

  router.afterEach(() => {
    NProgress.done();
  });
}
