package com.multictrl.common.handler;

import com.multictrl.common.exception.ExceptionUtils;
import com.multictrl.modules.business.handler.TopicDistributor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;

/**
 * MQTT消息处理器
 */
@Slf4j
@Component
public class Mqtt1MessageHandler implements MessageHandler {
    @Autowired
    @Qualifier("mqttExecutor1")
    private ExecutorService executor;

    @Autowired
    private TopicDistributor topicDistributor;

    @Override
    public void handleMessage(@NotNull Message<?> message) throws MessagingException {
        try {
            executor.submit(() -> {
                String topic = String.valueOf(message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC));
                String payload = message.getPayload().toString();
                try {
//                    log.debug("client1接收到的消息:{} {}", topic, payload);
                    topicDistributor.route(topic, payload);
                } catch (Exception e) {
                    log.error("消费信息异常: {}", ExceptionUtils.getErrorStackTrace(e));
                }
            });
        } catch (Exception e) {
            log.error("handleMessage异常: {}", ExceptionUtils.getErrorStackTrace(e));
        }
    }
}
