package com.union.ai.api.helper;

import com.alibaba.fastjson.JSON;
import com.union.ai.api.util.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
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.common.RemotingHelper;

import java.io.UnsupportedEncodingException;

/**
 * Created by IntelliJ IDEA.
 * Author: xingxin.jing
 * Date: 2019/4/5
 * Time: 下午4:18
 * mq发送
 */
@Slf4j
public class DefaultProducerHelper {

    private DefaultMQProducer producer;

    private static class Holder {
        private static DefaultProducerHelper instance = new DefaultProducerHelper();
    }

    private DefaultProducerHelper() {
        producer = new DefaultMQProducer("union_ai_api");
        String nameSrvAddr = PropertiesUtil.getProperty("name.srv.addr");
        log.info("rocketmq nameSrvAddr is:{}", nameSrvAddr.trim());
        producer.setNamesrvAddr(nameSrvAddr);
        producer.setVipChannelEnabled(false);
        try {
            producer.start();
        } catch (MQClientException e) {
            log.error("rocketmq producer 启动失败",e);
        }
    }

    public static DefaultProducerHelper getSingleton(){
        return Holder.instance;
    }

    public SendResult send(String topic, String tag, String body) {
        Message msg = null;
        try {
            msg = new Message(topic /* Topic */,
                    tag /* Tag */,
                    body.getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );
        } catch (UnsupportedEncodingException e) {
            log.error("不支持的编码",e);
        }
        return send(msg);
    }

    public SendResult send(String topic, String body) {
        Message msg = null;
        try {
            msg = new Message(topic /* Topic */,
                    body.getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );
        } catch (UnsupportedEncodingException e) {
            log.error("不支持的编码",e);
        }
        return send(msg);
    }

    private SendResult send(Message msg) {
        try {
            return producer.send(msg);
        } catch (Exception e) {
            log.error("发送消息失败,内容:" + e.getMessage());
            return null;
        }
    }

}
