import { staticRoutes } from '@/router'
import Request from '@/utils/request'
import Layout from '@/components/layout/index'

// 从服务器获取菜单
async function fetchAsyncRoutes4Server() {
  return (new Request()).mock(true).get('menu/index').then(r => {
    if (r.errno !== 0) {
      return []
    }
    return r.data
  })
}

// 菜单路由
function menuBuildTreeAsyncRoutes(routes){
  const menus = []
  routes.forEach(item => {
    const it = { id: item.id, path: item.path, name: item.name, meta: item.meta, alwaysShow: item.alwaysShow, hidden: item.hidden }
    if (item.children && item.children.length) {
      it.children = menuBuildTreeAsyncRoutes(item.children)
    }
    menus.push(it)
  })
  return menus
}

// 组装路由结构
function buildTreeAsyncRoutes (routes, authList) {
  const menus = []
  routes.forEach(item => {
    const it = { id: item.id, path: item.path, name: item.name, meta: item.meta, alwaysShow: item.alwaysShow, hidden: item.hidden }
    if (item.redirect != null) {
      it.redirect = item.redirect
    }
    if (item.component && authList.indexOf(item.id) >= 0) {
      if (item.component === '/layout') {
        it.component = Layout
      } else {
        it.component = () => import('@/views' + item.component)
      }
      if (item.children && item.children.length) {
        item.children.forEach(v => {
          if (!it.meta.permission) {
            it.meta.permission = []
          }
          if (item.path.startsWith('/')) {
            item.path = item.path.substring(1)
          }
          if (authList.indexOf(v.id) >= 0) {
            it.meta.permission.push(item.name + '.' + v.name)
          }
        })
        it.children = buildTreeAsyncRoutes(item.children, authList)
      }
      menus.push(it)
      
    }
  })
  return menus
  
}

const state = {
  routes: []
}

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

const actions = {
  async generateRoutes (context, authList) {
    // 服务器获取菜单
    const routes = await fetchAsyncRoutes4Server()
    // 权限过滤
    // const accessRoutes = routes.filter(v => authList.indexOf(v.id) >= 0)
    // 组装路由
    const treeRoutes = buildTreeAsyncRoutes(routes, authList)
    const menuRoutes = menuBuildTreeAsyncRoutes(routes)


    const mergeTreeRoutes = staticRoutes.filter((it) => it.name != undefined).concat(treeRoutes);
    context.commit('SET_ROUTES', menuRoutes)

    // const mergeTreeRoutes = staticRoutes.concat(treeRoutes)
    // context.commit('SET_ROUTES', mergeTreeRoutes)
    return mergeTreeRoutes
  }
}

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