package com.persagy.adm.server.custom.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.persagy.adm.server.custom.common.AdmMessageConst;
import com.persagy.dmp.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class AdmMessageHelper {

//    @Autowired
//    private RabbitMessageSender messageSender;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void sendMessage(Object messageData, String routing, boolean syncFlag) {
        // 同步消息
        try {
//            String msg = objectMapper.writeValueAsString(messageData);
            if(syncFlag) {
//                messageSender.sendAndReceive(AdmMessageConst.ADM_EXCHANGE, routing, msg);
                rabbitTemplate.sendAndReceive(AdmMessageConst.ADM_EXCHANGE, routing, buildMessage(messageData));
            } else {
                // 异步消息
//                messageSender.send(AdmMessageConst.ADM_EXCHANGE, routing, msg);
                rabbitTemplate.send(AdmMessageConst.ADM_EXCHANGE, routing, buildMessage(messageData));
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new BusinessException("消息格式有误！");
        }
    }

    private Message buildMessage(Object messageData) throws IOException{
        byte[] body = objectMapper.writeValueAsBytes(messageData);
        return new Message(body, new MessageProperties());
    }

}
