package com.zhentao.service.impl;

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.AdminUserRole;
import com.zhentao.mapper.AdminPermissionMapper;
import com.zhentao.mapper.AdminRoleMapper;
import com.zhentao.mapper.AdminRolePermissionMapper;
import com.zhentao.mapper.AdminUserRoleMapper;
import com.zhentao.service.AdminSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

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

/**
 * 基于角色权限表的管理员权限服务实现（默认实现）
 */
@Service
@Primary
public class RolePermissionBasedAdminSecurityServiceImpl implements AdminSecurityService {
    
    @Autowired
    private AdminUserRoleMapper adminUserRoleMapper;
    
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    
    @Autowired
    private AdminRolePermissionMapper adminRolePermissionMapper;
    
    @Autowired
    private AdminPermissionMapper adminPermissionMapper;
    
    @Override
    public boolean isSuperAdmin(Integer userId) {
        QueryWrapper<AdminUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<AdminUserRole> userRoles = adminUserRoleMapper.selectList(wrapper);
        
        for (AdminUserRole userRole : userRoles) {
            AdminRole role = adminRoleMapper.selectById(userRole.getRoleId());
            if (role != null && ("SUPER_ADMIN".equals(role.getRoleCode()) || "超级管理员".equals(role.getRoleName()))) {
                return true;
            }
        }
        return false;
    }
    
    @Override
    public List<String> getUserPermissions(Integer userId) {
        List<String> permissions = new ArrayList<>();
        
        // 检查是否是超级管理员
        if (isSuperAdmin(userId)) {
            permissions.add("*");
            return permissions;
        }
        
        // 查询用户角色
        QueryWrapper<AdminUserRole> userRoleWrapper = new QueryWrapper<>();
        userRoleWrapper.eq("user_id", userId);
        List<AdminUserRole> userRoles = adminUserRoleMapper.selectList(userRoleWrapper);
        
        if (userRoles.isEmpty()) {
            return permissions;
        }
        
        List<Integer> roleIds = userRoles.stream()
                .map(AdminUserRole::getRoleId)
                .collect(Collectors.toList());
        
        // 查询角色权限
        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());
                }
            }
        }
        
        return permissions;
    }
    
    @Override
    public List<String> getUserRoles(Integer userId) {
        List<String> roles = new ArrayList<>();
        
        QueryWrapper<AdminUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<AdminUserRole> userRoles = adminUserRoleMapper.selectList(wrapper);
        
        for (AdminUserRole userRole : userRoles) {
            AdminRole role = adminRoleMapper.selectById(userRole.getRoleId());
            if (role != null && role.getStatus() == 1) {
                roles.add(role.getRoleName());
            }
        }
        
        return roles;
    }
}

