import router from "@/router";
import NProgress from "@/utils/nprogress";
import { isNewVersion } from "@/utils/version.js";
import { useDictionaryStore } from "@/store";
import { getUserDicts } from "@/api/auth";

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

  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    isNewVersion();
    const hasToken = localStorage.getItem("token");
    if (hasToken) {
      if (to.path === "/login") {
        // 如果已登录，跳转首页
        localStorage.removeItem("token");
        next();
        NProgress.done();
      } else {
        const dictStore = useDictionaryStore();
        dictStore.checkAllData();
        if (
          !dictStore.dicts.value ||
          JSON.stringify(dictStore.dicts.value) === "{}"
        ) {
          const res = await getUserDicts(dictStore.types);
          if (res.data) {
            dictStore.dicts = res?.data ?? [];
          }
        }
        next();
        NProgress.done();
      }
    } else {
      // 未登录可以访问白名单页面
      if (whiteList.indexOf(to.path) !== -1) {
        next();
      } else {
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  });

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