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

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission (roles, route) {
  if (route.meta && route.meta.roleValue) {
    return roles.includes(route.meta.roleValue)
  } else {
    return true
  }
}

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

const state = {
  routes: constantRoutes,
  pageRoleArray: [],
  addRoutes: []
}
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PAGE_ROLE_ARRAY: (state, arr) => {
    state.pageRoleArray = arr
  }
}

const actions = {
  async generateRoutes ({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      accessedRoutes = filterAsyncRoutes(asyncRoutes, roles.user_rules)
      commit('SET_ROUTES', accessedRoutes)

      // 把所有roleId放在一个数组里
      let pageRoleArray = roles.user_rules
      commit('SET_PAGE_ROLE_ARRAY', pageRoleArray)

      resolve(accessedRoutes)
    })
  }
}

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