package com.duiba.tuia.youtui.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.SendResult;
import com.duiba.tuia.youtui.web.constant.OnsMQProperties;
import com.duiba.tuia.youtui.web.service.BaseService;
import com.duiba.tuia.youtui.web.service.OnsMQService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * ons消息实现类
 * Created by wubo on 2017/6/5.
 */
@Service
@EnableConfigurationProperties(OnsMQProperties.class)
public class OnsMQServiceImpl extends BaseService implements OnsMQService {

    @Autowired
    private Producer onsProducer;
    @Autowired
    private OnsMQProperties onsMQProperties;

    @Override
    public void sendCPAAdvertMQ(JSONObject json) {
        this.sendOneway(this.onsMQProperties.getTopic().getRoiCvr(),"cvr", json.toJSONString());
    }

    @Override
    public SendResult send(String topic,String tag, String message) {
        try {
            Message msg = new Message(topic, tag, message.getBytes("UTF-8"));
            return this.onsProducer.send(msg);
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
        } catch (Exception e) {
            logger.error("发消息异常,topic=" + topic, e);
        }

        return null;
    }

    @Override
    public void sendOneway(String topic,String tag, String message) {
        try {
            Message msg = new Message(topic, tag, message.getBytes("UTF-8"));
            this.onsProducer.sendOneway(msg);
        } catch (UnsupportedEncodingException e) {
            logger.error("", e);
        }catch (Exception e) {
            logger.error("发消息异常,topic=" + topic, e);
        }
    }

}
