import auth from "@/plugins/auth";
import router, { constantRoutes, dynamicRoutes } from "@/router";
const permission = {
  state: {
    routes: [],
    addRoutes: [],
    defaultRoutes: [],
    topbarRouters: [],
    sidebarRouters: [],
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    },
    SET_DEFAULT_ROUTES: (state, routes) => {
      state.defaultRoutes = constantRoutes.concat(routes);
    },
    SET_TOPBAR_ROUTES: (state, routes) => {
      state.topbarRouters = routes;
    },
    SET_SIDEBAR_ROUTERS: (state, routes) => {
      state.sidebarRouters = routes;
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise((resolve) => {
        const menuRouter = filterDynamicRoutes(dynamicRoutes);
        router.addRoutes([...menuRouter, { path: "*", redirect: "/404", hidden: true }]);
        commit("SET_SIDEBAR_ROUTERS", menuRouter);
        resolve();
      });
    },
  },
};

// 动态路由遍历，验证是否具备权限
export function filterDynamicRoutes(routes) {
  const res = [];

  routes.forEach((route) => {
    const temp = {
      ...route,
      children: route.children ? filterDynamicRoutes(route.children) : [],
    };
    if (auth.hasPermiOr(temp.permissions)) {
      res.push(temp);
    }
  });
  return res;
}

export default permission;
