package com.qiuguo.iot.data.service.mq;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author simon
 * @date 2023/9/26
 * @description
 **/

@Service
public class MqService {
   private final RabbitTemplate rabbitTemplate;
   private final AtomicBoolean confirmationResult = new AtomicBoolean(false);


   @Autowired
   public MqService(RabbitTemplate rabbitTemplate) {
      this.rabbitTemplate = rabbitTemplate;

      // 设置 ConfirmCallback
      rabbitTemplate.setConfirmCallback((correlation, ack, cause) -> {
         if (ack) {
            // 消息发送成功
            confirmationResult.set(true);
            System.out.println("消息发送成功");
         } else {
            // 消息发送失败
            confirmationResult.set(false);
            System.out.println("消息发送失败");
         }
      });
   }

   public Mono<Boolean> sendMessageWithConfirmation(String exchange, String routingKey, Object message) {
      rabbitTemplate.convertAndSend(exchange, routingKey, message);

      return Mono.defer(() -> {
         boolean result = confirmationResult.get();
         return Mono.just(result);
      });
   }

   public Mono<Object> sendMessage(String exchange, String routingKey, Object message) {
      // 只设置一次确认回调
      rabbitTemplate.setConfirmCallback((correlation, ack, cause) -> {
         if (ack) {
            // 消息发送成功
            System.out.println("Message sent successfully.");
         } else {
            // 消息发送失败
            System.err.println("Message send failed: " + cause);
         }
      });

      return Mono.defer(() -> {
         rabbitTemplate.convertAndSend(exchange, routingKey, message);
         // 返回一个表示异步操作完成的 Mono
         return Mono.empty();
      });
   }
}
