// 专门处理权限路由的模块
import { publicRoutes, privateRoutes } from "@/router";
/**
 * 
 * @param {本地路由} data 
 * @param {数据库缓存的路由路径} menus 
 * @returns 
 */
function filter(data, menus) {
  var newData = data.filter((x) => menus?.includes(x.name));
  newData.forEach(
    (x) => x.children && (x.children = filter(x.children, menus))
  );
  return newData;
}
export default {
  namespaced: true,
  state: {
    // 路由表：初始拥有静态路由权限
    routes: [],
    routeReady: 0
  },
  mutations: {
    /**
     * 增加路由
     */
    setRoutes(state, newRoutes) {
      // 永远在静态路由的基础上增加新路由
      state.routes = [...publicRoutes, ...newRoutes];
    },
    setRouteReady(state, num) {
      state.routeReady = state.routeReady + num;
    },
    resetrouteReady(state) {
      state.routeReady = 0;
    },
    deleteRouter(state) {
      state.routes = [];
    }
  },
  actions: {
    /**
     * 根据权限筛选路由
     */
    filterRoutes(context, menus) {
      let routes = [];
      // 路由权限匹配
      // if(menus && menus.length > 0){
      //   menus.forEach(key => {
      //     // 权限名 与 路由的 name 匹配
      //     routes.push(...privateRoutes.filter(item => item.name === key))
      //   })
      // }

      /**
       * 树结构数据条件过滤
       * js 指定删除数组(树结构数据)
       */
      //如果有权限，就筛选路由
      // if (menus) {
      //   routes = filter(privateRoutes, menus);
      // } else {
      //   //没有权限 获取全部路由表
      //   routes = privateRoutes;
      // }
      routes = filter(privateRoutes, menus);

      // 最后添加 不匹配路由进入 404
      routes.push({
        path: "/:catchAll(.*)",
        redirect: "/404"
      });
      context.commit("setRoutes", routes);
      context.commit("setRouteReady", 1);
      // context.commit('setRouteReady', true);
      return routes;
    }
  }
};
