import { constantRoutes } from '@/router'

/**
 * 使用 meta[fieldItem] 确定当前用户是否具有权限
 * @param route
 * @param fieldObj
 * @returns {boolean}
 */
function hasPermission(route, fieldObj) {
  let flag = true
  for (const fieldItem in fieldObj) {
    if (route.meta && route.meta[fieldItem]) {
      flag = fieldObj[fieldItem].some((fItem) => route.meta[fieldItem].includes(fItem))
      if (!flag) { break }
    }
  }
  return flag
}

/**
 * 递归筛选路由
 * @param routes
 * @param fieldObj
 * @returns {*[]}
 */
export function filterAsyncRoutes(routes, fieldObj) {
  const res = []

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

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

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

const actions = {
  generateRoutes({ commit }, { accountType, authType, role }) {
    return new Promise((resolve) => {
      const accessedRoutes = filterAsyncRoutes(constantRoutes, {
        accountType: [accountType],
        authType,
        role: [role]
      })
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

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