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

// 根据路由名称查询路由
function findRoute(name, routes) {
  return routes.find(route => route.name === name)
}

// 设置路由meta属性
function getMeta(route) {
  return {
    icon: route.icon,
    title: route.title,
    sort: route.sort,
    id: route.id
  }
}

function filterAsyncRoutes(sourceRoutes, targetRoutes) {
  const res = []
  sourceRoutes.forEach(route => {
    const userRoute = findRoute(route.name, targetRoutes)
    if (userRoute) {
      route.hidden = Boolean(userRoute.hidden)
      route.meta = { ...route.meta, ...getMeta(userRoute) }
      if (route.children && route.children.length > 0) {
        route.children = filterAsyncRoutes(route.children, targetRoutes).sort((a, b) => a.meta.sort - b.meta.sort)
      }
      res.push(route)
    }
  })
  return res.sort((a, b) => a.meta.sort - b.meta.sort)
}

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

const actions = {
  generateRoutes({ commit, rootGetters }) {
    return new Promise(resolve => {
      const accessedRoutes = filterAsyncRoutes(asyncRoutes, rootGetters.menusList)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

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