package com.bohuikeji.frame.module.admin.component;

import com.bohuikeji.frame.module.admin.base.MqListener;
import com.bohuikeji.frame.module.admin.config.MqConf;
import com.bohuikeji.frame.module.admin.entity.mq.MqMsg;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 消息队列发送工具
 * @author sjh
 */
@Component
@RequiredArgsConstructor
public class MqTool {

    final RabbitTemplate rabbitTemplate;

    /**
     * 发送普通消息
     * @param listenerClass 监听者
     * @param msg 消息体
     */
    public <T> void sendMsg(T msg,Class<? extends MqListener<T>> listenerClass){
        rabbitTemplate.convertAndSend(MqConf.QUEUE_RANCH_ONE_TO_ONE,new MqMsg<T>(msg,listenerClass));
    }

    /**
     * 发送广播消息
     * @param listenerClass 监听者
     * @param msg 消息体
     */
    public <T> void sendMsgToAll(T msg,Class<? extends MqListener<T>> listenerClass){
        rabbitTemplate.convertAndSend(MqConf.EXCHANGE_FANOUT_RANCH,"",new MqMsg<T>(msg,listenerClass));
    }

    /**
     * 发送延迟消息
     * @param msg 消息体
     * @param listenerClass 监听者
     * @param duration 延时时间段
     */
    public <T> void sendDelayMsg(T msg, Class<? extends MqListener<T>> listenerClass, Duration duration){
        rabbitTemplate.convertAndSend(MqConf.EXCHANGE_DELAY_RANCH, MqConf.QUEUE_RANCH_DELAY, new MqMsg<T>(msg,listenerClass), message ->{
            message.getMessageProperties().setHeader("x-delay",duration.toMillis());
            return message;
        });
    }

    /**
     * 发送延时消息
     * @param msg 消息体
     * @param listenerClass 监听者
     * @param appointTime 指定发送时间，如小于当前时间则立即发送
     * @param <T>
     */
    public <T> void sendDelayMsg(T msg, Class<? extends MqListener<T>> listenerClass, LocalDateTime appointTime){
        //间隔时间
        long intervalTime=Duration.between(LocalDateTime.now(),appointTime).toMillis();
        if (intervalTime<1){
            intervalTime=0;
        }
        long finalIntervalTime = intervalTime;
        rabbitTemplate.convertAndSend(MqConf.EXCHANGE_DELAY_RANCH, MqConf.QUEUE_RANCH_DELAY, new MqMsg<T>(msg,listenerClass), message ->{
            message.getMessageProperties().setHeader("x-delay", finalIntervalTime);
            return message;
        });
    }
}
