package org.springblade.payment.listener.sender;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.constant.OrderConstant;
import org.springblade.payment.entity.SuccessParams;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: Silent
 * @Description
 * @Date: Created in 16:36 2021/11/1
 * @Modified By:
 */
@Component
@Slf4j
public class OrderSend implements RabbitTemplate.ConfirmCallback {
	@Autowired
	private RabbitTemplate rabbitTemplate;

	/**
	 * 发送订单消息
	 * @param successParams
	 * @return
	 */
	public boolean sendOrderMessage(SuccessParams successParams){
		//发送超时队列消息
		rabbitTemplate.convertAndSend(OrderConstant.TTL_ORDER_EXCHANGE, OrderConstant.TTL_ROUTE_KEY, JSONObject.toJSONString(successParams), message->{
			MessageProperties messageProperties = message.getMessageProperties();
			//设置消息延迟发送时间
			//给消息设置延迟毫秒值
			messageProperties.setExpiration(String.valueOf(OrderConstant.ORDER_DELAY_TIME_OUT));
			messageProperties.setDelay((int) OrderConstant.ORDER_DELAY_TIME_OUT);
			return message;
		},new CorrelationData(IdUtil.randomUUID())); //全局唯一ID
		log.info("订单消息发送:{}",successParams);
		return true;
	}

	/**
	 * 确认回调
	 * @param correlationData
	 * @param ack
	 * @param cause
	 */
	@Override
	public void confirm(CorrelationData correlationData, boolean ack, String cause) {
		System.out.println("消息id:" + correlationData.getId());
		if (ack) {
			log.info("消息发送确认成功");
		} else {
			log.error("消息发送确认失败:{}",cause);
		}
	}
}
