package com.zhentao.service;

import com.rabbitmq.client.Channel;
import com.zhentao.constant.ChatConstants;
import com.zhentao.entity.ChatMessage;
import com.zhentao.repository.ChatMessageMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * RabbitMQ消息监听器
 * 异步处理聊天消息的持久化（MySQL版本）
 * 已禁用 - 如需启用请取消注释并启用 RabbitMQConfig
 */
// @Component
public class RabbitMQMessageListener {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    /**
     * 监听聊天消息队列
     * 将消息持久化到MySQL
     */
    @RabbitListener(queues = ChatConstants.RabbitMQ.CHAT_QUEUE)
    public void handleChatMessage(ChatMessage chatMessage, Message message, Channel channel) {
        try {
            System.out.println("收到待保存的消息: " + chatMessage.getMessageId());
            
            // 保存消息到MySQL
            chatMessageMapper.insert(chatMessage);
            
            System.out.println("消息已保存到MySQL: " + chatMessage.getMessageId());
            
            // 手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            
        } catch (Exception e) {
            System.err.println("保存消息到MySQL失败: " + e.getMessage());
            e.printStackTrace();
            
            try {
                // 消息处理失败，拒绝并重新入队（最多重试3次）
                if (chatMessage.getRetryCount() == null) {
                    chatMessage.setRetryCount(0);
                }
                
                if (chatMessage.getRetryCount() < ChatConstants.Limit.MAX_RETRY_COUNT) {
                    chatMessage.setRetryCount(chatMessage.getRetryCount() + 1);
                    // 拒绝消息并重新入队
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
                    System.out.println("消息重新入队，重试次数: " + chatMessage.getRetryCount());
                } else {
                    // 超过重试次数，拒绝并丢弃（进入死信队列）
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                    System.err.println("消息超过最大重试次数，进入死信队列: " + chatMessage.getMessageId());
                }
            } catch (IOException ioException) {
                System.err.println("消息确认失败: " + ioException.getMessage());
            }
        }
    }

    /**
     * 监听死信队列
     * 记录无法处理的消息
     */
    @RabbitListener(queues = ChatConstants.RabbitMQ.CHAT_DLX_QUEUE)
    public void handleDeadLetterMessage(ChatMessage chatMessage, Message message, Channel channel) {
        try {
            System.err.println("收到死信消息: " + chatMessage.getMessageId());
            
            // 可以将失败的消息记录到专门的错误日志表或文件
            // 这里简单打印日志
            System.err.println("消息详情: fromUserId=" + chatMessage.getFromUserId() + 
                              ", toUserId=" + chatMessage.getToUserId() +
                              ", content=" + chatMessage.getContent());
            
            // 确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            
        } catch (Exception e) {
            System.err.println("处理死信消息失败: " + e.getMessage());
        }
    }
}


