/*
 * @Date: 2022-07-05 13:48:26
 * @LastEditors: 陈禹琨 cyk910622@163.com
 * @LastEditTime: 2022-07-05 15:21:29
 * @FilePath: \upcloud-wms-hnsy-web\src\store\modules\async-router.js
 * @Description: cyk
 */
/**
 * 向后端请求用户的菜单，动态生成路由
 */
import { constantRouterMap } from "@/config/router.config";
import { generatorDynamicRouter } from "@/router/generator-routers";

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: [],
    menuId: 0,
    menus: [],
    operations: [],
    pageElements: [],
    currentOperations: [],
    currentPageElements: [],
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = constantRouterMap.concat(routers);
    },
    SET_MENU_ID: (state, id) => {
      // 设置当前路由id，过滤出当前路由拥有的操作权限
      var currentOperations = [];
      var currentPageElements = [];
      const currentHandle = (origin, current) => {
        origin.map((o) => {
          if (o.menuId === id) {
            current.push(o.code);
          }
        });
      };

      currentHandle(state.operations, currentOperations);
      currentHandle(state.pageElements, currentPageElements);

      state.menuId = id;
      state.currentOperations = currentOperations;
      state.currentPageElements = currentPageElements;
    },
    SET_OPERATIONS: (state, operations) => {
      state.operations = operations;
    },
    SET_PAGE_ELEMENTS: (state, pageElements) => {
      state.pageElements = pageElements;
    },
  },
  actions: {
    GenerateRoutes({ commit }, menus) {
      return new Promise((resolve) => {
        generatorDynamicRouter(menus).then((routers) => {
          commit("SET_ROUTERS", routers);
          resolve(routers);
        });
      });
    },
  },
};

export default permission;
