package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhentao.entity.Blacklist;
import com.zhentao.entity.User;
import com.zhentao.mapper.BlacklistMapper;
import com.zhentao.mapper.UserMapper;
import com.zhentao.service.BlacklistService;
import com.zhentao.vo.BlacklistVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class BlacklistServiceImpl implements BlacklistService {
    
    @Autowired
    private BlacklistMapper blacklistMapper;
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    private com.zhentao.mapper.UserProfileMapper userProfileMapper;
    
    private static final String BLACKLIST_KEY_PREFIX = "blacklist:";
    private static final long CACHE_EXPIRE_DAYS = 7;
    
    private String getRedisKey(Long userId) {
        return BLACKLIST_KEY_PREFIX + userId;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Blacklist addBlacklist(Long userId, Long blockedUserId, String reason) {
        if (userId == null || blockedUserId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        if (userId.equals(blockedUserId)) {
            throw new RuntimeException("不能拉黑自己");
        }
        
        Blacklist existing = blacklistMapper.selectByUserAndBlocked(userId, blockedUserId);
        if (existing != null) {
            throw new RuntimeException("该用户已在黑名单中");
        }
        
        User blockedUser = userMapper.selectById(blockedUserId);
        if (blockedUser == null) {
            throw new RuntimeException("被拉黑的用户不存在");
        }
        
        Blacklist blacklist = new Blacklist();
        blacklist.setUserId(userId);
        blacklist.setBlockedUserId(blockedUserId);
        blacklist.setReason(reason);
        blacklist.setCreatedAt(LocalDateTime.now());
        blacklist.setUpdatedAt(LocalDateTime.now());
        
        blacklistMapper.insert(blacklist);
        
        // 添加到Redis
        String redisKey = getRedisKey(userId);
        redisTemplate.opsForSet().add(redisKey, blockedUserId);
        redisTemplate.expire(redisKey, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);
        
        return blacklist;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeBlacklist(Long userId, Long blockedUserId) {
        if (userId == null || blockedUserId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        LambdaQueryWrapper<Blacklist> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Blacklist::getUserId, userId)
               .eq(Blacklist::getBlockedUserId, blockedUserId);
        
        int rows = blacklistMapper.delete(wrapper);
        
        if (rows > 0) {
            String redisKey = getRedisKey(userId);
            redisTemplate.opsForSet().remove(redisKey, blockedUserId);
            return true;
        }
        
        return false;
    }
    
    @Override
    public List<BlacklistVO> getBlacklist(Long userId) {
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        List<Blacklist> blacklistList = blacklistMapper.selectByUserId(userId);
        
        List<BlacklistVO> voList = new ArrayList<>();
        for (Blacklist blacklist : blacklistList) {
            BlacklistVO vo = new BlacklistVO();
            vo.setId(blacklist.getId());
            vo.setUserId(blacklist.getUserId());
            vo.setBlockedUserId(blacklist.getBlockedUserId());
            vo.setReason(blacklist.getReason());
            vo.setCreatedAt(blacklist.getCreatedAt());
            vo.setUpdatedAt(blacklist.getUpdatedAt());
            
            // 查询被拉黑用户的基本信息
            User blockedUser = userMapper.selectById(blacklist.getBlockedUserId());
            if (blockedUser != null) {
                vo.setBlockedUserNickname(blockedUser.getNickname());
                
                // 处理头像URL - 如果是MinIO URL且无法访问，则使用默认头像
                String avatarUrl = blockedUser.getAvatarUrl();
                if (avatarUrl != null && avatarUrl.contains("115.190.125.125:9000")) {
                    // MinIO头像可能无法访问，使用默认头像
                    vo.setBlockedUserAvatar("https://via.placeholder.com/100x100/FF8A9B/FFFFFF?text=" + 
                                          (blockedUser.getNickname() != null ? blockedUser.getNickname().substring(0, 1) : "用"));
                } else {
                    vo.setBlockedUserAvatar(avatarUrl);
                }
                
                vo.setBlockedUserGender(blockedUser.getGender());
                
                // 调试日志
                System.out.println("用户ID: " + blockedUser.getUserId() + 
                                 ", 昵称: " + blockedUser.getNickname() + 
                                 ", 原始头像: " + blockedUser.getAvatarUrl() + 
                                 ", 处理后头像: " + vo.getBlockedUserAvatar() +
                                 ", 性别: " + blockedUser.getGender());
                
                // 计算年龄
                if (blockedUser.getBirthDate() != null) {
                    int age = java.time.LocalDate.now().getYear() - blockedUser.getBirthDate().getYear();
                    vo.setBlockedUserAge(age);
                } else {
                    vo.setBlockedUserAge(0);
                }
            }
            
            // 设置性别文字
            if (blockedUser.getGender() != null) {
                switch (blockedUser.getGender()) {
                    case 1:
                        vo.setBlockedUserCity("男");
                        break;
                    case 2:
                        vo.setBlockedUserCity("女");
                        break;
                    default:
                        vo.setBlockedUserCity("未知");
                        break;
                }
            } else {
                vo.setBlockedUserCity("未知");
            }
            
            voList.add(vo);
        }
        
        return voList;
    }
    
    @Override
    public boolean isBlocked(Long userId, Long blockedUserId) {
        if (userId == null || blockedUserId == null) {
            return false;
        }
        
        String redisKey = getRedisKey(userId);
        Boolean isMember = redisTemplate.opsForSet().isMember(redisKey, blockedUserId);
        
        if (isMember != null && isMember) {
            return true;
        }
        
        Blacklist blacklist = blacklistMapper.selectByUserAndBlocked(userId, blockedUserId);
        
        if (blacklist != null) {
            redisTemplate.opsForSet().add(redisKey, blockedUserId);
            redisTemplate.expire(redisKey, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);
            return true;
        }
        
        return false;
    }
    
    @Override
    public List<Long> getBlockedUserIds(Long userId) {
        if (userId == null) {
            return new ArrayList<>();
        }
        
        String redisKey = getRedisKey(userId);
        
        Set<Object> members = redisTemplate.opsForSet().members(redisKey);
        
        if (members != null && !members.isEmpty()) {
            return members.stream()
                    .map(obj -> Long.valueOf(obj.toString()))
                    .collect(Collectors.toList());
        }
        
        List<Long> blockedUserIds = blacklistMapper.selectBlockedUserIds(userId);
        
        if (!blockedUserIds.isEmpty()) {
            for (Long blockedUserId : blockedUserIds) {
                redisTemplate.opsForSet().add(redisKey, blockedUserId);
            }
            redisTemplate.expire(redisKey, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);
        }
        
        return blockedUserIds;
    }
    
    @Override
    public void refreshCache(Long userId) {
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        String redisKey = getRedisKey(userId);
        
        redisTemplate.delete(redisKey);
        
        List<Long> blockedUserIds = blacklistMapper.selectBlockedUserIds(userId);
        
        if (!blockedUserIds.isEmpty()) {
            for (Long blockedUserId : blockedUserIds) {
                redisTemplate.opsForSet().add(redisKey, blockedUserId);
            }
            redisTemplate.expire(redisKey, CACHE_EXPIRE_DAYS, TimeUnit.DAYS);
        }
    }
}


