'use strict';

module.exports = option => {
    /**
     * 用户权限筛选中间件
     *
     * @param {function} next - 中间件继续执行的方法
     * @return {void}
     */
    return function* permissionFilter(next) {
        // 获取所有权限数据
        const permissionData = yield this.service.permission.getAllData(true, true);
        this.currentName = '';
        let currentPermissionId = 0;
        // 查找controller和action名称相同的数据
        for (const index in permissionData) {
            if (permissionData[index].controller === this.controllerName && permissionData[index].action === this.actionName) {
                this.currentName = permissionData[index].name;
                currentPermissionId = permissionData[index].id;
                break;
            }
        }
        // 如果页面没有录入db,则允许通过,否则进入权限判断
        if (currentPermissionId > 0) {
            // 查找当前用户是否有对应页面权限
            const managerSession = this.session.managerSession;
            const permission = managerSession.permission;
            try {
                checkPermission(permission, currentPermissionId);
            } catch (error) {
                this.session.message = {
                    type: 'error',
                    icon: 'exclamation-circle',
                    message: error.toString(),
                };
                return this.redirect('/dashboard');
            }
        }

        // 找出对应页面的最顶层id
        this.permissionRootId = 0;
        this.service.permission.getTopPid(currentPermissionId, permissionData);

        // 查找最顶层数据
        this.topPermission = yield this.service.permission.getCacheDataById(this.permissionRootId);

        this.currentName = this.currentName === '' ? '后台管理' : this.currentName;
        yield next;
    };
};
/**
 * 判断权限
 *
 * @param {String} permissionList - 当前用户权限字符串
 * @param {Number} currentPermissionId - 当前被访问页面的权限id
 * @return {void}
 */
function checkPermission(permissionList, currentPermissionId) {
    if (permissionList === '') {
        throw '用户组权限为空';
    }
    // 如果是超级管理员则直接返回
    if (permissionList === 'all') {
        return;
    }
    const permissionIdList = permissionList.split(',');
    if (permissionIdList.indexOf(currentPermissionId + '') < 0) {
        throw '当前用户组没有对应权限';
    }

}
