import router, { configRoutes } from "@/router";
import { useUserStore } from "@/store/modules/user";
import { usePermissionStore } from "@/store/modules/permission";
import { useDictionaryStore } from "@/store/modules/dictionary";
import { isNewVersion } from "@/utils/version.js";
import NProgress from "@/utils/nprogress";
import { getUserDicts } from "@/api/auth";
import {RouteRecordRaw} from "vue-router";

export function setupPermission() {
  // 白名单路由
  const whiteList = [""];
  const userStore = useUserStore();
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    isNewVersion();
    const hasToken = localStorage.getItem("token");
    if (hasToken) {
      let userRole=await userStore.getUserInfo();
      console.log("bbbb",userRole);
      if (to.path === "/login") {
        // 如果已登录，跳转首页
        next({ path: "/" });
        NProgress.done();
      } else {
        // 如果已经登录，让菜单加载本地的写死路由的数据
        const userStore = usePermissionStore();
        const roleList:any=ref([]);
        console.log("aaa",configRoutes);
        if (!userStore.routes || userStore.routes.length === 0) {
          for(let i=0;i<configRoutes.length;i++){
            if(configRoutes[i].path==='/statistic'||configRoutes[i].path==='/analysis'||configRoutes[i].path==='/system') {
              if(userRole.spcMenus.some(item => item.path == configRoutes[i].path)){
                let rotes=configRoutes[i];
                const child:any=ref([]);
                let children=userRole.spcMenus.filter(spc=>spc.parentPath===configRoutes[i].path);
                console.log("ccc",children);
                rotes.redirect=rotes.path+"/"+children[0].path;
                for(let j=0;j<rotes.children.length;j++){
                    if(children.some(item=>item.path===rotes.children[j].path)){
                      child.value.push(rotes.children[j]);
                    }
                }
                console.log(child);
                rotes.children=child.value;
                roleList.value.push(rotes);
              }
            }else roleList.value.push(configRoutes[i]);

          }
          userStore.setRoutes(roleList.value);
        }

        next();
      }
    } 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();
  });
}
