import router from "@/router";
import NProgress from "@/utils/nprogress";
import { useDictionaryStore } from "@/store/modules/dictionary";
import { getUserDicts } from "@/api/auth";
import { isNewVersion } from "@/utils/version.js";
export function setupPermission() {
  // 白名单路由
  const whiteList: string[] = ["client-traceability"]; //由于包含动态路由，这里面存储的是路由的name而不是path

  router.beforeEach(async (to, from, next) => {
    isNewVersion();
    NProgress.start();
    //在路由跳转前判断是否为不需要全屏加载的二级路由界面(目前项目中只有pro-step界面涉及)
    const isShow = inject("isShow");
    const route = useRoute();
    if (
      !(
        route.fullPath.substr(0, 11) == "/pro-steps/" &&
        to.fullPath.substr(0, 11) == "/pro-steps/"
      )
    ) {
      //@ts-ignore
      isShow.value = true;
    }
    const hasToken = localStorage.getItem("token");
    if (hasToken) {
      if (to.path === "/login") {
        // 如果已登录，跳转首页,并且清空token
        localStorage.setItem("token", "");
        next();
        // next({ path: "/" });
        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.name as string) !== -1) {
        const dictStore = useDictionaryStore();
        dictStore.checkAllData();
        next();
      } else {
        if (to.path === "/login") {
          next();
        } else {
          next(`/login`);
        }
        NProgress.done();
      }
    }
  });

  router.afterEach(() => {
    const isShow = inject("isShow");
    const route = useRoute();
    //@ts-ignore
    if (isShow.value == true) {
      //@ts-ignore
      isShow.value = false;
    }
    NProgress.done();
  });
}
