package com.zhentao.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.entity.AdminPermission;
import com.zhentao.entity.AdminRole;
import com.zhentao.entity.AdminRolePermission;
import com.zhentao.entity.AdminUser;
import com.zhentao.entity.AdminUserRole;
import com.zhentao.mapper.AdminPermissionMapper;
import com.zhentao.mapper.AdminRoleMapper;
import com.zhentao.mapper.AdminRolePermissionMapper;
import com.zhentao.mapper.AdminUserMapper;
import com.zhentao.mapper.AdminUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Admin用户详情服务，实现Spring Security的UserDetailsService
 */
@Service
public class AdminUserDetailsService implements UserDetailsService {
    
    @Autowired
    private AdminUserMapper adminUserMapper;
    
    @Autowired
    private AdminUserRoleMapper adminUserRoleMapper;
    
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    
    @Autowired
    private AdminRolePermissionMapper adminRolePermissionMapper;
    
    @Autowired
    private AdminPermissionMapper adminPermissionMapper;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户
        QueryWrapper<AdminUser> userWrapper = new QueryWrapper<>();
        userWrapper.eq("username", username);
        AdminUser adminUser = adminUserMapper.selectOne(userWrapper);
        
        if (adminUser == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        
        // 查询用户角色
        QueryWrapper<AdminUserRole> userRoleWrapper = new QueryWrapper<>();
        userRoleWrapper.eq("user_id", adminUser.getId());
        List<AdminUserRole> userRoles = adminUserRoleMapper.selectList(userRoleWrapper);
        
        // 判断是否是超级管理员
        boolean isSuperAdmin = false;
        List<Integer> roleIds = new ArrayList<>();
        
        for (AdminUserRole userRole : userRoles) {
            roleIds.add(userRole.getRoleId());
            AdminRole role = adminRoleMapper.selectById(userRole.getRoleId());
            if (role != null && "超级管理员".equals(role.getRoleName())) {
                isSuperAdmin = true;
                break;
            }
        }
        
        // 查询权限
        List<String> permissions = new ArrayList<>();
        if (isSuperAdmin) {
            // 超级管理员拥有所有权限，添加特殊权限标识
            permissions.add("ROLE_SUPER_ADMIN");
            permissions.add("*");
        } else {
            // 普通管理员查询具体权限
            if (!roleIds.isEmpty()) {
                QueryWrapper<AdminRolePermission> rolePermissionWrapper = new QueryWrapper<>();
                rolePermissionWrapper.in("role_id", roleIds);
                List<AdminRolePermission> rolePermissions = adminRolePermissionMapper.selectList(rolePermissionWrapper);
                
                Set<Integer> permissionIds = rolePermissions.stream()
                        .map(AdminRolePermission::getPermissionId)
                        .collect(Collectors.toSet());
                
                if (!permissionIds.isEmpty()) {
                    QueryWrapper<AdminPermission> permissionWrapper = new QueryWrapper<>();
                    permissionWrapper.in("id", permissionIds);
                    permissionWrapper.eq("status", 1); // 只查询启用的权限
                    List<AdminPermission> permissionList = adminPermissionMapper.selectList(permissionWrapper);
                    
                    for (AdminPermission permission : permissionList) {
                        // 添加权限编码作为权限标识
                        if (permission.getPermissionCode() != null) {
                            permissions.add(permission.getPermissionCode());
                        }
                    }
                }
            }
            
            // 添加角色标识
            for (Integer roleId : roleIds) {
                AdminRole role = adminRoleMapper.selectById(roleId);
                if (role != null && role.getStatus() == 1) {
                    permissions.add("ROLE_" + role.getRoleCode());
                }
            }
        }
        
        return new AdminUserDetails(adminUser, permissions, isSuperAdmin);
    }
    
    /**
     * 根据用户ID加载用户详情（用于Token认证）
     */
    public UserDetails loadUserById(Integer userId) {
        AdminUser adminUser = adminUserMapper.selectById(userId);
        
        if (adminUser == null) {
            throw new UsernameNotFoundException("用户不存在: " + userId);
        }
        
        // 查询用户角色
        QueryWrapper<AdminUserRole> userRoleWrapper = new QueryWrapper<>();
        userRoleWrapper.eq("user_id", adminUser.getId());
        List<AdminUserRole> userRoles = adminUserRoleMapper.selectList(userRoleWrapper);
        
        // 判断是否是超级管理员
        boolean isSuperAdmin = false;
        List<Integer> roleIds = new ArrayList<>();
        
        for (AdminUserRole userRole : userRoles) {
            roleIds.add(userRole.getRoleId());
            AdminRole role = adminRoleMapper.selectById(userRole.getRoleId());
            if (role != null && "超级管理员".equals(role.getRoleName())) {
                isSuperAdmin = true;
                break;
            }
        }
        
        // 查询权限
        List<String> permissions = new ArrayList<>();
        if (isSuperAdmin) {
            permissions.add("ROLE_SUPER_ADMIN");
            permissions.add("*");
        } else {
            if (!roleIds.isEmpty()) {
                QueryWrapper<AdminRolePermission> rolePermissionWrapper = new QueryWrapper<>();
                rolePermissionWrapper.in("role_id", roleIds);
                List<AdminRolePermission> rolePermissions = adminRolePermissionMapper.selectList(rolePermissionWrapper);
                
                Set<Integer> permissionIds = rolePermissions.stream()
                        .map(AdminRolePermission::getPermissionId)
                        .collect(Collectors.toSet());
                
                if (!permissionIds.isEmpty()) {
                    QueryWrapper<AdminPermission> permissionWrapper = new QueryWrapper<>();
                    permissionWrapper.in("id", permissionIds);
                    permissionWrapper.eq("status", 1);
                    List<AdminPermission> permissionList = adminPermissionMapper.selectList(permissionWrapper);
                    
                    for (AdminPermission permission : permissionList) {
                        if (permission.getPermissionCode() != null) {
                            permissions.add(permission.getPermissionCode());
                        }
                    }
                }
            }
            
            for (Integer roleId : roleIds) {
                AdminRole role = adminRoleMapper.selectById(roleId);
                if (role != null && role.getStatus() == 1) {
                    permissions.add("ROLE_" + role.getRoleCode());
                }
            }
        }
        
        return new AdminUserDetails(adminUser, permissions, isSuperAdmin);
    }
}

