import { constantRoutes, asyncRoutes } from '@/router'


// function hetAllRoleChecked(roles) {
//     let res = []
//     roles.forEach(role => {
//         if (role.checked) {
//             res.push(role.value)
//         }
//         if (role.data && role.data.length > 0) {
//             res = res.concat(hetAllRoleChecked(role.data))
//         }
//     })
//     return res
// }


/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roleValue) {
        // return roles.some(role => route.meta.roleValue.includes(role))
        return roles.includes(route.meta.roleValue)
    } else {
        return true
    }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []
    // let roleIds = hetAllRoleChecked(roles)
    let roleIds = roles
    routes.forEach(route => {
        const tmp = { ...route }
        if (hasPermission(roleIds, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })
    return res
}

const state = {
    routes: constantRoutes,
    pageRoleArray: [],
    addRoutes: []
}
const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    },
    SET_PAGE_ROLE_ARRAY: (state, arr) => {
        state.pageRoleArray = arr
    }
}

const actions = {
    async generateRoutes({ commit }, roles) {
        return new Promise(resolve => {
            let accessedRoutes
            // accessedRoutes = asyncRoutes
            accessedRoutes = filterAsyncRoutes(asyncRoutes, roles.user_rules)
            // accessedRoutes = [...accessedRoutes, {
            //     path: '/',
            //     redirect: accessedRoutes[0].path
            // }]
            console.log({accessedRoutes});
            commit('SET_ROUTES', accessedRoutes)

            // 把所有roleId放在一个数组里
            // let pageRoleArray = hetAllRoleChecked(roles.user_rules)
            let pageRoleArray = roles.user_rules
            commit('SET_PAGE_ROLE_ARRAY', pageRoleArray)


            resolve(accessedRoutes)
        })
    }
}

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