package com.trade.admin.system.service.impl;

import com.trade.admin.system.service.ISysPermissionService;
import com.trade.admin.system.domain.entity.SysRole;
import com.trade.admin.system.domain.entity.SysUser;
import com.trade.admin.system.service.ISysMenuService;
import com.trade.admin.system.service.ISysRoleService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @description: 系统权限实现类
 * @Author: wanglang
 * @Date: 2023/7/27 10:53
 * @Version: 1.0
 */
@Service
public class SysPermissionServiceImpl implements ISysPermissionService {

    @Resource
    private ISysRoleService roleService;
    @Resource
    private ISysMenuService menuService;

    @Override
    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;
    }

    @Override
    public Set<String> getMenuPermission(SysUser user) {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
        } else {
            List<SysRole> roles = user.getRoles();
            if (!CollectionUtils.isEmpty(roles)) {
                // 多角色设置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;
    }
}
