import {
    asyncRoutes,
    constantRoutes,
    resetRouter
} from '@/router'
import {
    getRoule
} from '@/api/user'
import {
    clearStorage
} from '../../utils/auth'
/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param routes asyncRoutes
 * @param roles 传递参数-用户权限内容
 */
function filterAsyncRoutes(routes, roles) {
    const res = []
    routes.forEach(route => {
            const currentRoute = {
                ...route
            }
            if (currentRoute.meta && currentRoute.meta.module) {
                const routeModule = currentRoute.meta.module
                    // console.log(roles)
                if (roles.some(role => role.indexOf(routeModule) === 0)) {
                    if (Array.isArray(currentRoute.children) && currentRoute.children.length > 0) {
                        currentRoute.children = filterAsyncRoutes(currentRoute.children, roles)
                    }
                    res.push(currentRoute)
                }
            } else {
                // res.push(currentRoute)
            }
        })
        // console.log(routes)
    return res
}

/**
 * 权限添加 日后优化
 * @param {*} roles
 * @param {*} res
 * @param {*} parentModule
 */
function handleRoles(roles, res, parentModule) {
    // console.log(roles, res, parentModule)
    roles.forEach((role) => {
        if (Array.isArray(role.children) && role.children.length > 0) {
            handleRoles(role.children, res, parentModule + role.name + '.')
        } else {
            const lastIndex = role.name.lastIndexOf('.')
            if (parentModule.indexOf(role.name.split('.')[0]) != -1) {
                res.push(`${parentModule}${role.name.substring(lastIndex + 1)}`)
            } else {
                res.push(`${parentModule}${role.name}`)
            }
        }
    })
}
const state = {
    routes: [],
    menu: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        const routerList = constantRoutes.concat(routes)
        console.log(routerList)
        state.menu = routerList
        state.routes = routerList
    },
    SET_MENU: (state, menu) => {
        state.menu = menu
    }
}

const actions = {
    generateRoutes({
        commit
    }) {
        return new Promise(async resolve => {
            const data = await getRoule().then().catch(error => {
                clearStorage()
                resetRouter()
                window.location.href=location.protocol+'//' + location.host+"/#/login"
            })
            // console.log(location.protocol,location.host)
            const roles = []
            handleRoles(data.data, roles, '')
            console.log('roles', roles)
            const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
            commit('user/SET_ROLES', roles, {
                root: true
            })
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    }
}

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