package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户权限处理
 *
 * @author ruoyi
 */
@Component
public class SysPermissionService {
    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysUserService userService;

    /**
     * 获取角色数据权限
     *
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(SysUser user) {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            roles.add("admin");
        } else {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     *
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(SysUser user) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
        } else {
            List<SysRole> roles = user.getRoles();
            if (!roles.isEmpty() && roles.size() > 1) {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles) {
                    Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            } else {
                perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
            }
        }
        return perms;
    }

    /**
     * 更新角色旗下用户权限 ,用户数量大可能有性能问题
     *
     * @param roleId
     */
    public void refreshRolePermission(Long roleId) {
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser loginUser = redisCache.getCacheObject(key);
            if (loginUser != null) {
                for (SysRole r : loginUser.getUser().getRoles()) {
                    if (r.getRoleId().equals(roleId)) {
                        loginUser.setPermissions(getMenuPermission(loginUser.getUser()));
                        tokenService.setLoginUser(loginUser);
                    }
                }
            }
        }
    }

    /**
     * 更新用户缓存信息和权限 ,用户数量大可能有性能问题
     *
     * @param userId
     */
    public void refreshUserPermission(Long userId) {
        System.out.println("更新用户缓存*******************************************");
        Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        for (String key : keys) {
            LoginUser loginUser = redisCache.getCacheObject(key);
            if (loginUser != null && loginUser.getUser().getUserId().equals(userId)) {
                loginUser.setUser(userService.selectUserById(loginUser.getUser().getUserId()));
                if (loginUser.getUser() != null && !getMenuPermission(loginUser.getUser()).isEmpty()) {
                    loginUser.setPermissions(getMenuPermission(loginUser.getUser()));
                    tokenService.setLoginUser(loginUser);
                } else {
                    tokenService.delLoginUser(loginUser.getToken());
                }
            }
        }
    }
}
