import Routes from '@/router/routes'

function filterRoutes (routes, permissions) {
  return routes.reduce((result, route) => {
    const required = (route.meta && route.meta.permissions) || []
    if (required.some(permission => !permissions.includes(permission))) return result
    const copy = { ...route }
    if (route.children) copy.children = filterRoutes(route.children, permissions)
    result.push(copy)
    return result
  }, [])
}
const state = {
  refresh: true, // 更新路由
  roles: Routes.routes,
  permission: Routes.permission
}

const mutations = {
  SET_REFRESH (state, params) {
    state.refresh = params
  },
  SET_ROLES (state, route) {
    state.roles = route
    // setRoles(route)
  },
  SET_PERMISSION (state, permission) {
    state.permission = permission
    // setPermission(permission)
  }
}

const actions = {
  getMenu2 ({ commit, rootState }) {
    return new Promise((resolve, reject) => {
      const { routes, permission } = Routes
      const permissions = rootState.user.userInfo.permissions || []
      const visibleRoutes = filterRoutes(routes, permissions)
      commit('SET_ROLES', visibleRoutes)
      commit('SET_PERMISSION', permission)
      // 路由重新配置触发更新
      commit('SET_REFRESH', true)
      resolve(visibleRoutes)
    })
  }
}

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