package com.backendsys.modules.common.config.rabbitmq;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.io.IOException;

import org.springframework.amqp.rabbit.connection.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.GetResponse;

/**
 * 自定义监听器
 */
@Component
@Lazy(false)
public class DemoRabbitListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

//    // [监听] 自动 ACK
//    @ComfyuiRabbitListener(id = "demoContainer", queues = "demo.queue", autoStartup = "false" )
//    public void receive(SysUser sysUser) {
//        System.out.println("收到消息: " + sysUser);
//    }


//    // [监听] 手动 ACK
//    @RabbitListener(id = "demoContainer", queues = "demo.queue", ackMode = "MANUAL")
//    public void receive(Message message, Channel channel) throws IOException, InterruptedException {
//        try {
//            // 1. 模拟耗时业务
//            Thread.sleep(8000);
//
//            // 2. 业务处理
//            String body = new String(message.getBody(), StandardCharsets.UTF_8);
//            System.out.println("处理消息 (8s): " + body);


//            // 外部调用ACK (消耗队列)：
//            try {
//                Connection connection = rabbitTemplate.getConnectionFactory().createConnection();
//                Channel channel = connection.createChannel(false);
//                GetResponse resp = channel.basicGet("demo.queue", false);
//                if (resp != null) {
//                    channel.basicAck(resp.getEnvelope().getDeliveryTag(), false);
//                }
//                channel.close();
//                connection.close();
//            } catch (Exception e) {
//                System.out.println(e.getMessage());
//            }


//            // 3. 手动确认（deliveryTag + 是否批量）
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
//        } catch (Exception e) {
//            System.err.println("(RabbitListener) 处理失败: " + e.getMessage());
//            // 拒绝并重新入队
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
//        }
//    }

    // [监听] 死信队列
    @RabbitListener(id = "demoDlxContainer", queues = "demo.dlx.queue", ackMode = "MANUAL")
    public void handleDemoDlx(Message message, Channel channel) throws IOException {
        System.out.println("[Demo][RabbitMQ-死信队列]收到：" + new String(message.getBody()));

        // 业务：记录日志 / 重发 / 报警 / 人工补偿
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }


    // 4. 并发消费（一条队列多线程）
    /*
    @ComfyuiRabbitListener(queues = "demo.queue", concurrency = "5-10")
    public void receive(String msg) { ... }
     */



}
