package com.xxfc.platform.universal.biz;

import com.github.wxiaoqi.security.common.config.rabbit.RabbitConstant;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

import static com.github.wxiaoqi.security.common.config.rabbit.RabbitConstant.INTEGRAL_TOPIC;

@Service
@Slf4j
public class MQServiceBiZ {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional(rollbackFor = Exception.class)
    public ObjectRestResponse sendMessage(String exchange, String routKey, String json) {
        log.info("发送消息到消息队列：exchange = {}, routingKey = {}, json = {}", exchange, routKey, json);
        log.info("开始发送消息。。。");
       if(StringUtils.isBlank(exchange)) {
           exchange = INTEGRAL_TOPIC;
       }
       if (StringUtils.isBlank(routKey)) {
           routKey = RabbitConstant.INTEGRAL_ROUTING_KEY;
       }
        Message message = MessageBuilder.withBody(json.getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_JSON).setContentEncoding("utf-8")
                .setMessageId(UUID.randomUUID() + "").build();
        rabbitTemplate.convertAndSend(exchange, routKey, message);
        log.info("发送成功。。。");
        return ObjectRestResponse.succ();
    }
}
