import store from 'store'

const { getState } = store

const stroePath = 'user'

const authByArray = (auth, permissions) => {

    const flags = []

    auth.forEach(p => {
        switch (p.constructor) {
            case String:
                flags.push([permissions.includes(p), '&&'])
                break
            case Array:
                flags.push([authByArray(p, permissions), '||'])
                break
            case Boolean:
                flags.push([p, '&&'])
                break
            default:
                break
        }
    })

    let result

    flags.forEach((p, i) => {
        if (p[1] === '&&') {
            if (i === 0) {
                result = true
            }
            if (result) {
                result = p[0]
            }
        } else {
            if (i === 0) {
                result = false
            }
            if (!result) {
                result = p[0]
            }
        }
        //result = p[1] === '&&' ? result && p[0] : result || p[0]
    })

    return result
}

const authByJson = (auth, permissions) => {

    let result = true

    const flags = []

    const deepName = (arr, key) => {
        arr.forEach((p, i) => {
            switch (p.constructor) {
                case String:
                    arr[i] = `${key}:${p}`
                    break
                case Array:
                    p = deepName(p, key)
                    break
                default:
                    break
            }
        })
        return arr
    }

    for (let key in auth) {
        const app = auth[key]
        switch (app.constructor) {
            case String:
                flags.push(permissions.includes(`${key}:${app}`))
                break
            case Array:
                flags.push(authByArray(deepName(app, key), permissions))
                break
            default:
                break
        }
    }

    flags.forEach(p => {
        result = result && p
    })

    return result

}

const auth = (auth, force = false) => {

    let info = this

    if (!info || !Object.keys(info).length) {
        info = getState(stroePath)
    }

    if (!info) {
        return false
    }

    /**
     * 超级管理员
     */
    if (info.adminType === 1 && !force) {
        return true
    }

    const permissions = info.permissions

    if (!permissions) {
        return false
    }

    let flag = false

    if (auth) {
        switch (auth.constructor) {
            case String:
                flag = permissions.includes(auth)
                break
            case Array:
                flag = authByArray(auth, permissions)
                break
            case Object:
                flag = authByJson(auth, permissions)
                break
            default:
                break
        }
    }

    return flag
}

export default auth