import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(menu, route,parentRouter) {
	if(parentRouter == null){
    let routerPath = route.path;
    if(menu[routerPath]){
        return true;
    }
  }else{
    let parentRouterPath = parentRouter.path;
    let routerPath = route.path;
    routerPath = parentRouterPath +"/" + routerPath;
    if(menu[routerPath]){
      return true;
    }
		if (routerPath.indexOf('/:id') > -1) {
			return true;
		}
  }
  return false;
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, menu,parentRouter) {
	const res = [];
	routes.forEach(route => {
		const tmp = { ...route};
		if (hasPermission(menu,tmp,parentRouter)) {
			if(tmp.children) {
				tmp.children = filterAsyncRoutes(tmp.children, menu,tmp);
			}
			res.push(tmp);
		}
	});
	return res
}

const state = {
	routes: [],
	addRoutes: []
};

const mutations = {
	SET_ROUTES: (state, routes) => {
		state.addRoutes = routes;
		state.routes = constantRoutes.concat(routes);
	}
};

const actions = {
	generateRoutes({commit}, data) {
		return new Promise(resolve => {
      //可用的菜单
      let menuabled = {};
      for(let i = 0;i<data.length;++i){
          menuabled[data[i].routerPath]=true;
      }
      let accessedRoutes = filterAsyncRoutes(asyncRoutes, menuabled,null);
			commit('SET_ROUTES', accessedRoutes);
			resolve(accessedRoutes)
		})
	}
};

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
