package com.usky.iot.service.listener;


import com.usky.iot.service.config.mqtt.MqttInConfig;
import com.usky.iot.service.enums.TopListener;
import com.usky.iot.service.mqtt.SimpleContext;
import com.usky.iot.service.vo.MqttBaseVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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 yq
 * @date 2021/11/3 8:13
 */
@ConditionalOnProperty(prefix = "mqtt", value = {"enabled"}, havingValue = "true")
@Component
public class MqttListener {

    public static final String MESSAGE_NAME = "messageInput";
    private static final Logger logger = LoggerFactory.getLogger(MqttListener.class);

    @Autowired
    private SimpleContext simpleContext;

    /**
     * 处理消息-消费者
     *
     * @return
     */
    @Bean(MESSAGE_NAME)
    @ServiceActivator(inputChannel = MqttInConfig.CHANNEL_NAME_INPUT)
    public MessageHandler handler() {
        return message -> {
            String payload = message.getPayload().toString();
            //进行接口推送
            String[] infoCode1 = TopListener.XFFJ.getCode().split("/");
            Object mqttReceivedTopic = message.getHeaders().get("mqtt_receivedTopic");
            if (null != mqttReceivedTopic) {
                String topic = mqttReceivedTopic.toString();
                MqttBaseVO mqttBaseVO = new MqttBaseVO();
                mqttBaseVO.setTopic(topic);
                if((topic.indexOf(infoCode1[1]) != -1 && topic.indexOf(infoCode1[4]) != -1)) {
                    mqttBaseVO.setDescribe("control");
                    mqttBaseVO.setData(payload);
                }
                //统一处理数据
                simpleContext.getResource(mqttBaseVO);
                logger.info("接收到 mqtt消息，主题:{} 消息:{}", topic, payload);
            }
        };
    }
}
