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

/**
 * 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
}

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

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

const actions = {
  generateRoutes({commit}, menu) {

    return new Promise(resolve => {

      const info = menu.reduce((map, node) =>
        {
        const myComponent = resolve => {
          require(['@/views' + node.component_path], resolve)
        }

        // if (node.component_name != null) {
        //   node.url = "/" + node.system_code.toLowerCase() + "/" + node.url
        // }
        node.path = node.parent_id ? node.url : '/scgl/' + node.url
          //console.log(node)
        node.component = node.component_path ?
                                    myComponent :
                                    Layout,
                                    node.redirect = node.redirect,
                                    // node.name = node.id,
                                    node.name = node.component_name,
                                    node.noCache = false,
                                    node.keep_alive = true,
                                    node.alwaysShow = node.always_show == 1,
                                    node.meta = node.menu_name.length===4?
                                                            {title: node.menu_name, icon: 'el-icon-folder', keep_alive: true}:
                                                            {title: node.menu_name, icon: 'el-icon-folder', keep_alive: true}

          return  map[node.id] = node,
                node.children = [],
                map
        },

        {}
      )

      const result = menu.filter(node => {
        if (info[node.parent_id]) {
          info[node.parent_id].children.push(node)
        }
        return !node.parent_id
      })
      commit('SET_ROUTES', result)
      resolve(result)
    })
  }
}

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