package com.usky.issue.service.listener;

import com.usky.issue.service.config.mqtt.MqttInConfig;
import com.usky.issue.service.mqtt.SimpleContext;
import com.usky.issue.service.vo.MqttBaseVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.messaging.MessageHandler;
import org.springframework.stereotype.Component;

/**
 * @author han
 * @date 2025/03/20 14:41
 */
@ConditionalOnProperty(prefix = "mqtt", value = {"enabled"}, havingValue = "true")
@Slf4j
@Component
public class MqttListener {
    public static final String MESSAGE_NAME = "messageInput";

    @Autowired
    private SimpleContext simpleContext;

    /**
     * 处理消息-消费者
     *
     * @return
     */
    @Bean(MESSAGE_NAME)
    @ServiceActivator(inputChannel = MqttInConfig.CHANNEL_NAME_INPUT)
    public MessageHandler handler() {
        return message -> {
            String payload = message.getPayload().toString();
            //进行接口推送
            Object mqttReceivedTopic = message.getHeaders().get("mqtt_receivedTopic");
            if (null != mqttReceivedTopic) {
                String topic = mqttReceivedTopic.toString();
                MqttBaseVO mqttBaseVO = new MqttBaseVO();
                mqttBaseVO.setTopic(topic);
                if (topic.indexOf("info") != -1 ) {
                    mqttBaseVO.setDescribe("info");
                    mqttBaseVO.setData(payload);
                }else if(topic.indexOf("event") != -1 ) {
                    mqttBaseVO.setDescribe("event");
                    mqttBaseVO.setData(payload);
                }
                //统一处理数据
                simpleContext.getResource(mqttBaseVO);
            }
        };
    }
}
