package org.jeecg.config.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttMessageHandler implements MessageHandler {

    private final ApplicationEventPublisher eventPublisher;

    public MqttMessageHandler(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
    }
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        try {
            MessageHeaders headers = message.getHeaders();
            //获取消息Topic
            String receivedTopic = (String) headers.get(MqttHeaders.RECEIVED_TOPIC);
            //获取消息体
            String payload = (String) message.getPayload();
            log.info("[接收消息的topic]：{} - [接收的消息]：{}", receivedTopic,payload);

            // 发布事件
            eventPublisher.publishEvent(new MqttMessageEvent(this, receivedTopic, payload));

        }catch(Exception e){
            log.error("接收的消息处理失败：{}",e.getMessage());
            e.printStackTrace();
        }
    }

}
