import { asyncRouterMap, constantRouterMap } from '@/router'

/**
 * 过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param menuList
 */
function filterAsyncRouter (asyncRouterMap, menuList, permissionList) {
  // menuList 暂时不使用
  let accessedRouters = asyncRouterMap.map(route => {
    if (route.meta && route.meta.permissionName.length > 0) {
      // 取父级菜单与后台权限列表交集
      const intersection = route.meta.permissionName.filter(i => {
        return permissionList.indexOf(i) !== -1 || i === 'all'
      })

      // 有交集说明需显示父级
      if (intersection.length > 0) {
        // 过滤子路由
        route.children = route.children.filter(i => {
          if (i.meta && i.meta.permissionName) {
            return permissionList.indexOf(i.meta.permissionName) !== -1
          } else {
            return true
          }
        })

        // 设置子页面权限列表
        route.children.forEach(item => {
          const list = permissionList.filter(i => {
            return i.indexOf(item.meta.permissionName) !== -1
          })
          item.meta.permissionList = list.map(i => {
            return i.split(':')[1]
          })
        })
        return route
      } else {
        return null
      }
    } else {
      return route
    }
  })
  // 去除空元素
  accessedRouters = accessedRouters.filter(Boolean)
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes ({ commit }, data) {
      return new Promise(resolve => {
        const extraInfo = data
        // if (extraInfo.name === 'admin') {
        // accessedRouters = asyncRouterMap
        // } else {
        const accessedRouters = filterAsyncRouter(asyncRouterMap, extraInfo.menuList, extraInfo.permissionList)
        // }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
