package top.tqx.demo_1.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.tqx.demo_1.entity.Permission;
import top.tqx.demo_1.entity.Role;
import top.tqx.demo_1.mapper.PermissionMapper;
import top.tqx.demo_1.mapper.RolePermissionMapper;
import top.tqx.demo_1.mapper.UserRoleMapper;
import top.tqx.demo_1.service.PermissionService;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 检查用户是否有指定权限
     */
    @Override
    public boolean hasPermission(Long userId, String permissionCode) {
        // 获取用户的所有角色
        List<Role> roles = userRoleMapper.selectRolesByUserId(userId);
        
        if (roles.isEmpty()) {
            return false;
        }

        // 检查是否有超级管理员角色
        boolean isSuperAdmin = roles.stream()
                .anyMatch(role -> "SUPER_ADMIN".equals(role.getRoleCode()));
        
        if (isSuperAdmin) {
            return true;
        }

        // 获取所有角色的权限
        for (Role role : roles) {
            List<Permission> permissions = rolePermissionMapper.selectPermissionsByRoleId(role.getId());
            
            // 检查是否有所需权限
            boolean hasPermission = permissions.stream()
                    .anyMatch(p -> permissionCode.equals(p.getPermissionCode()));
            
            if (hasPermission) {
                return true;
            }
        }

        return false;
    }

    /**
     * 获取用户的所有权限编码
     */
    @Override
    public List<String> getUserPermissions(Long userId) {
        List<Role> roles = userRoleMapper.selectRolesByUserId(userId);
        
        return roles.stream()
                .flatMap(role -> rolePermissionMapper.selectPermissionsByRoleId(role.getId()).stream())
                .map(Permission::getPermissionCode)
                .distinct()
                .collect(Collectors.toList());
    }

    /**
     * 获取用户的所有权限详情
     */
    @Override
    public List<Permission> getUserPermissionDetails(Long userId) {
        List<Role> roles = userRoleMapper.selectRolesByUserId(userId);
        
        return roles.stream()
                .flatMap(role -> rolePermissionMapper.selectPermissionsByRoleId(role.getId()).stream())
                .distinct()
                .collect(Collectors.toList());
    }
}