import { constantRoutes } from '@/router'
import Layout from '@/layout'
import storage from '@/utils/storage'

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

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

const actions = {
  generateRoutes ({ commit }) {
    return new Promise(resolve => {
      let menus = storage.ss.get('vue_template_user_menu') || []
      let accessedRoutes = filterAsyncRouter(menus)
      accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

function filterAsyncRouter (routers) {
  let accessedRouters = routers.filter(router => {
    if (router.component) {
      if (router.component === 'Layout') {
        router.component = Layout
      } else {
        const component = router.component
        router.component = resolve => require(['@/views' + component], resolve)
      }
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children)
    }
    return true
  })
  return accessedRouters
}

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