import { asyncRoutes } from '@/router'

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

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

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

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

const actions = {
  routesByRoles({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('administrator')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles, 'role')
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  routesByPermissions({ commit }, permissions) {
    // console.log(permissions)
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, permissions, 'permission')
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

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