import router, { asyncRoutes, constantRoutes } from '@/router'
// import { getAsyncRoutes } from '@/router/asyncRouter'
import { getMenu } from '@/api/user'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
/**
 * 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) {
  return routes.filter((route) => {
    // const tmp = { ...route }
    if (hasPermission(roles, route)) {
      if (route.component) {
        if (route.component === 'Layout') {
          route.component = Layout
        } else if (route.component == 'ParentView') {
          route.component = ParentView
        } else {
          route.component = loadView(route.component)
        }
      } else {
        // console.log(route)
        route.component = Layout
      }
      if (!!route.children && route.children.length) {
        route.children = filterAsyncRoutes(filterChildren(route.children, route), roles)
      } else {
        delete route['children']
        delete route['redirect']
      }
    } else {
      // console.log(route)
      // 没有权限的路由，跳过不渲染
      return false
    }
    return true
  })
}
function filterChildren(childrenMap, lastRouter = false) {
  var children = []
  childrenMap.forEach((el, index) => {
    if (el.children && el.children.length) {
      // ParentView是出现三级或更多层级时做判断的标识，暂时没有用到
      if (el.component === 'ParentView') {
        let pChildren = []
        el.children.forEach((c) => {
          c.path = c.path.startsWith('/') ? c.path : `/${c.path}`
          el.path = el.path.startsWith('/') ? el.path : `/${el.path}`
          c.path = el.path + c.path
          if (c.children && c.children.length) {
            pChildren = pChildren.concat(filterChildren(c.children, c))
            return
          }
          pChildren.push(c)
        })
        el.children = pChildren
        children.push(el)
        return
      }
    } else {
      // 防止后台出现空的children
      delete el['children']
    }
    if (lastRouter) {
      // 将上下级的path拼接，路由地址栏会显示如 /system/user
      // 添加新菜单时只需要添加该层级的名称就行，不需要加 /
      lastRouter.path = lastRouter.path.startsWith('/') ? lastRouter.path : `/${lastRouter.path}`
      el.path = el.path.startsWith('/') ? el.path : `/${el.path}`
      el.path = lastRouter.path + el.path
    }
    children = children.concat(el)
  })
  return children
}
const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}
const state = {
  routes: [],
  addRoutes: [],
}

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

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve) => {
      let accessedRoutes
      getMenu().then((res) => {
        const { data } = res
        // if (roles.includes('admin')) {
        //     accessedRoutes = asyncRoutes || []
        // } else {
        //     accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        // }
        accessedRoutes = filterAsyncRoutes(data, roles)
        // console.log(accessedRoutes)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  },
}

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