package com.kym.service.mq.producer;

import com.kym.service.mq.callback.ConfirmCallbackService;
import com.kym.service.mq.callback.ReturnCallbackService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * rabbitmq 消息发送
 */
@Slf4j
@Component
public class MessageSender {


    private final RabbitTemplate rabbitTemplate;

    private final ConfirmCallbackService confirmCallbackService;

    private final ReturnCallbackService returnCallbackService;

    public MessageSender(RabbitTemplate rabbitTemplate, ConfirmCallbackService confirmCallbackService, ReturnCallbackService returnCallbackService) {
        this.rabbitTemplate = rabbitTemplate;
        this.confirmCallbackService = confirmCallbackService;
        this.returnCallbackService = returnCallbackService;
    }

    /**
     *
     * @param exchange
     * @param routingKey
     * @param msg
     * @param delayTime 延迟时间（ms）
     */
    public void send(String exchange, String routingKey, Object msg, int... delayTime) {

        /**
         * 确保消息发送失败后可以重新返回到队列中
         * 注意：yml需要配置 publisher-returns: true
         */
        rabbitTemplate.setMandatory(true);

        /**
         * 消费者确认收到消息后，手动ack回执回调处理
         */
        rabbitTemplate.setConfirmCallback(confirmCallbackService);

        /**
         * 消息投递到队列失败回调处理
         */
        rabbitTemplate.setReturnsCallback(returnCallbackService);

        /**
         * 发送消息
         */
        rabbitTemplate.convertAndSend(exchange, routingKey, msg,
                message -> {
//                    message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    message.getMessageProperties().setDelay(delayTime.length > 0 ? delayTime[0] : 0);
                    return message;
                },
                new CorrelationData(UUID.randomUUID().toString()));
    }
}
