package com.sikey.wa04.business.infrastructure.adapter;

import com.sikey.wa04.business.infrastructure.configuration.MessagingRabbitmqConfig;
import com.sikey.wa04.common.constants.HeaderConstant;
import com.sikey.wa04.common.dto.header.GenericManufacturerHeader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

/**
 * RabbitMQ消息发送
 *
 * @author luoyangwei
 */
@Slf4j
@Component
public class RabbitMQMessaging {
    private final RabbitTemplate rabbitTemplate;
    private final MessagingRabbitmqConfig messagingRabbitmqConfig;

    public RabbitMQMessaging(RabbitTemplate rabbitTemplate, MessagingRabbitmqConfig messagingRabbitmqConfig) {
        this.rabbitTemplate = rabbitTemplate;
        this.messagingRabbitmqConfig = messagingRabbitmqConfig;
    }

    /**
     * 发送消息到RabbitMQ
     *
     * @param headers 消息头
     * @param message 消息体
     */
    public void publish(GenericManufacturerHeader headers, Object message) {
      //  log.info("发送消息: {}, headers: {}", message, headers);
        MessagePostProcessor messagePostProcessor = messagePost -> {
            messagePost.getMessageProperties().setHeader(HeaderConstant.SYSTEM, headers.getSystem());
            messagePost.getMessageProperties().setHeader(HeaderConstant.SYSTEM_VERSION, headers.getSystemVersion());
            messagePost.getMessageProperties().setHeader(HeaderConstant.SOFTWARE_VERSION, headers.getSoftWareVersion());
            messagePost.getMessageProperties().setHeader(HeaderConstant.MANUFACTURER, headers.getManufacturer());
            messagePost.getMessageProperties().setHeader(HeaderConstant.TIME_ZONE, headers.getTimeZone());
            messagePost.getMessageProperties().setHeader(HeaderConstant.TIMESTAMP, headers.getTimestamp());
            messagePost.getMessageProperties().setHeader(HeaderConstant.REQUEST_ID, headers.getRequestId());
            return messagePost;
        };
        rabbitTemplate.convertAndSend(
                messagingRabbitmqConfig.getExchangeName(), messagingRabbitmqConfig.getRoutingKey(), message, messagePostProcessor);
    }
}
