import { asyncRoutes, constantRoutes } 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.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

function getMenuId(path, routes, prevPath, commit) {
  const rootPath = (prevPath === '') ? prevPath : `${prevPath}/`
  routes.forEach(route => {
    if (path === `${rootPath}${route.path}`) {
      commit('SET_CURRENTMENUID', route.menuId)
    } else if (route.children) {
      getMenuId(path, route.children, route.path, commit)
    }
  })
}

const state = {
  routes: [],
  addRoutes: [],
  permissions: [],
  currentRoute: {},
  currentMenuId: null
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_CURRENTROUTE: (state, currentRoute) => {
    state.currentRoute = currentRoute
  },
  SET_CURRENTMENUID: (state, currentMenuId) => {
    state.currentMenuId = currentMenuId
  },
  RESET_CURRENTMENUID: (state, currentMenuId) => {
    state.currentMenuId = currentMenuId
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      const accessedRoutes = asyncRoutes || []
      // commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  setRoutes({ commit }, accessedRoutes) {
    return new Promise(resolve => {
      commit('SET_ROUTES', accessedRoutes)
      resolve()
    })
  },
  setPermissions({ commit }, permissions) {
    return new Promise(resolve => {
      commit('SET_PERMISSIONS', permissions)
      resolve()
    })
  },
  setCurrentRoute({ commit, state }, currentRoute) {
    return new Promise(resolve => {
      commit('SET_CURRENTROUTE', currentRoute)
      getMenuId(currentRoute.path, state.routes, '', commit)
      resolve()
    })
  },
  reSetCurrentRoute({ commit }, currentRoute) {
    return new Promise(resolve => {
      commit('RESET_CURRENTMENUID', null)
      commit('SET_CURRENTROUTE', currentRoute)
      resolve()
    })
  }
}

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