import { constantRouterMap } from '@/router'
import Layout from '../../views/layout/Layout'
import { getAdminPermission } from '@/api/article'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
// const importq = require('../../router/_import_production.js')
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.indexOf(role) >= 0)
//   } else {
//     return true
//   }
// }

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
// function filterAsyncRouter(asyncRouterMap, roles) {
//   const accessedRouters = asyncRouterMap.filter(route => {
//     if (hasPermission(roles, route)) {
//       if (route.children && route.children.length) {
//         route.children = filterAsyncRouter(route.children, roles)
//       }
//       return true
//     }
//     return false
//   })
//   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 requestPermission = { rolename: null }
        const map = []
        requestPermission.rolename = data.roles[0]
        getAdminPermission(requestPermission).then(response => {
          for (var i = 0; i < response.data.length; i++) {
            const routeTemp = {
              path: response.data[i].path,
              component: Layout,
              redirect: {
                name: response.data[i].redirect.name
              },
              alwaysShow: response.data[i].alwaysShow,
              meta: {
                title: response.data[i].meta.title,
                icon: response.data[i].meta.icon
              },
              children: []
            }
            for (var j = 0; j < response.data[i].children.length; j++) {
              try { // 跳过无文件
                require('@/views/' + response.data[i].children[j].component + '.vue').default
              } catch (e) {
                continue
              }
              const childrenTemp = {
                path: response.data[i].children[j].path,
                component: require('@/views/' + response.data[i].children[j].component + '.vue').default,
                name: response.data[i].children[j].name,
                meta: { title: response.data[i].children[j].meta.title, noCache: false },
                hidden: response.data[i].children[j].hidden
              }
              routeTemp.children.push(childrenTemp)
            }
            map.push(routeTemp)
          }
          commit('SET_ROUTERS', map)
          resolve()
        })
      })
    }
  }
}

export default permission
