import Vue from 'vue'

/**
 *
 * @param {*} router
 * @param {*} authInfo
 */
function checkAuth(router, authInfo) {
    // 判断当前路由在权限数组中是否存在
    if (router.meta) {
        const metaInfo = router.meta
        if (!metaInfo.requiresAuth) {
            return true
        } else {
            if (metaInfo.index == 0) {
                return !!authInfo[metaInfo.type]
            } else if (metaInfo.index == 1) {
                if (authInfo[metaInfo.type]) {
                    return !!authInfo[metaInfo.type][metaInfo.subType]
                }
                return false
            } else {
                var typeAuth = authInfo[metaInfo.type]
                for (let index = 0; index < metaInfo.subType.length; index++) {
                    const field = metaInfo.subType[index]
                    typeAuth = typeAuth[field]
                    if (typeAuth && metaInfo.subType.length - 1 == index) {
                        return true
                    } else if (!typeAuth) {
                        return false
                    }
                }
            }
        }
    }
    return true
}

/**
 *
 * @param {*} routers
 * @param {*} authInfo
 */
const filterAsyncRouter = function(routers, authInfo) {
    const res = []
    routers.forEach(router => {
        const tmp = {
            ...router
        }
        if (checkAuth(tmp, authInfo)) {
            if (tmp.children) {
                tmp.children = filterAsyncRouter(tmp.children, authInfo)
            }
            res.push(tmp)
        }
    })
    return res
}

const permission = {
    state: {
        addRouters: []
    },
    mutations: {
        SET_ROUTERS: (state, routers) => {
            state.addRouters = routers
        }
    },
    actions: {
        GenerateRoutes({
            commit
        }, data) {
            return new Promise(resolve => {
                // TODO 实现权限验证
                resolve()
            })
        }
    }
}

export default permission