package com.hzs.third.mqcall.service.impl;

import com.hzs.common.core.constant.RabbitMqConstants;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.third.mq.dto.DelayedMessageDTO;
import com.hzs.third.mqcall.service.IDelayedMessageService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 延时队列实现类
 */
@Service
public class DelayedMessageServiceImpl implements IDelayedMessageService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendDelayedMessage(DelayedMessageDTO delayedMessageDTO) {
        if (DateUtils.compareDateTimeAfter(delayedMessageDTO.getEffectDate(), DateUtils.currentDateTime())) {
            // 计算延时时间
            long second = DateUtils.betweenSecond(delayedMessageDTO.getEffectDate()) * 1000;
            rabbitTemplate.convertAndSend(RabbitMqConstants.DELAY_EXCHANGE, RabbitMqConstants.DELAY_ROUTING_KEY,
                    delayedMessageDTO, message -> {
                        message.getMessageProperties().setExpiration(Long.toString(second));
                        return message;
                    });
        }
    }
}
