// rabbit-mq.js
const amqp = require('amqplib');
const amqplib_config = require('../../etc/config.json').amqplib_config;

class RabbitMQ {
    constructor() {
        this.connection = null;
        this.config = amqplib_config;
    }

    // 获取连接
    async getConnection() {
        if (!this.connection) {
            this.connection = await amqp.connect(this.config);
        }
        return this.connection;
    }

    // 生产者发送消息
    async producerDirectMsg( msg,exchange = "exchange_system", routingKey = 'new.msg') {
        const connection = await this.getConnection();
        const channel = await connection.createChannel();

        try {
            await channel.assertExchange(exchange, 'direct', { durable: true });
            console.log("生产者发送消息:",exchange,routingKey,msg)
            channel.publish(exchange, routingKey, Buffer.from(JSON.stringify(msg)));
        } catch (error) {
            console.error('发送消息错误:', error);
            throw error;
        } finally {
            await channel.close();
        }
    }

    // 消费者监听消息
    async consumerDirectMsg(callback, exchange = "exchange_system",  routingKey = 'new.msg') {
        const connection = await this.getConnection();
        const channel = await connection.createChannel();

        try {
            await channel.assertExchange(exchange, 'direct', { durable: true });
            
            // 创建一个随机队列名称
            const { queue } = await channel.assertQueue('', { 
                exclusive: true,
                durable: true 
            });

            // 绑定队列到交换机
            await channel.bindQueue(queue, exchange, routingKey);

            // 设置预取数量
            await channel.prefetch(1);

            console.log(`等待接收消息，交换机: ${exchange}, 路由键: ${routingKey}`);

            channel.consume(queue, async (msg) => {
                if (msg) {
                    try {
                        const content = JSON.parse(msg.content.toString());
                        await callback(content);
                        channel.ack(msg);
                    } catch (error) {
                        console.error('处理消息错误:', error);
                        // 消息处理失败，可以选择重新入队或直接确认
                        channel.nack(msg, false, false);
                    }
                }
            });
        } catch (error) {
            console.error('消费者设置错误:', error);
            throw error;
        }
    }

    // 关闭连接
    async close() {
        if (this.connection) {
            await this.connection.close();
            this.connection = null;
        }
    }
}

// 导出单例
module.exports = new RabbitMQ();