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

/**
 * 过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param menuList
 */
function filterAsyncRouter (asyncRouterMap, menuList, permissionList) {
  const permissionCodes = permissionList.map(i => i.code)
  // menuList 暂时未用到
  let accessedRouters = asyncRouterMap.map(route => {
    if (route.meta && route.meta.permissionName.length > 0) {
      // 取父级菜单与后台权限列表交集
      const routePermissions = route.meta.permissionName.join(',')
      const intersection = permissionCodes.find((code) => routePermissions.indexOf(code) > -1) || routePermissions.indexOf('all') > -1
      // 有交集说明需显示父级
      if (intersection) {
        // 过滤子路由
        route.children = route.children.filter(i => {
          if (i.meta && i.meta.permissionName) {
            return permissionCodes.find((code) => i.meta.permissionName.indexOf(`:${code}`) > -1)
          } else {
            return true
          }
        })

        // 设置子页面权限列表
        // route.children.forEach(item => {
        //   let list = permissionList.filter(i => {
        //     return !~i.code.indexOf(item.meta.permissionName)
        //   })
        //   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 { roleList, resourceList } = data
        let accessedRouters = asyncRouterMap
        accessedRouters = filterAsyncRouter(asyncRouterMap, roleList, resourceList)

        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}

export default permission
