package cn.ibizlab.core.extensions.util;

import cn.ibizlab.core.extensions.domain.EngineMQMsg;
import cn.ibizlab.core.extensions.domain.ResultsMQMsg;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * MQ默认发送消息服务
 */
@Slf4j
@Service
public class DefaultMQProducerService {

    @Value("${rocketmq.producer.ruleEngineTopic:DSTMSG}")
    private String ruleEngineTopic;

    @Value("${rocketmq.producer.resultsTopic:DSTRESULTSMSG}")
    private String resultsTopic;

    @Autowired
    @Lazy
    DefaultMQProducer defaultMQProducer;


    public void sendToMQ(EngineMQMsg engineMQMsg, String tags) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        String msg = JSON.toJSONString(engineMQMsg);
        Message sendMsg = new Message(ruleEngineTopic, tags, msg.getBytes());
        SendResult sendResult = defaultMQProducer.send(sendMsg);
        log.info("引擎消息发送响应：" + sendResult.toString());
    }

    public void sendToMQ(ResultsMQMsg resultMQMsg, String tags) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
        String msg = JSON.toJSONString(resultMQMsg);
        Message sendMsg = new Message(resultsTopic, tags, msg.getBytes());
        SendResult sendResult = defaultMQProducer.send(sendMsg);
        log.info("构建消息发送响应：" + sendResult.toString());
    }
}
