package com.fuyuanshen.global.mqtt.config;


import cn.hutool.core.lang.UUID;
//import com.fuyuanshen.global.mqtt.receiver.NewReceiverMessageHandler;
import com.fuyuanshen.global.mqtt.receiver.RegisEquipReceiverMessageHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;


@Configuration
@Slf4j
public class RegisEquipMqttInboundConfiguration {
    @Autowired
    private MqttPropertiesConfig mqttPropertiesConfig;
    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;
    @Autowired
    private RegisEquipReceiverMessageHandler receiverMessageHandler3;
    //消息通道
    @Bean
    public MessageChannel messageInboundChannel3(){
        return new DirectChannel();
    }
 
    /**
     * 配置入站适配器
     * 作用： 设置订阅主题，以及指定消息的通道 等相关属性
     * */
    @Bean
    public MessageProducer messageProducer3(){
        // 生成一个不重复的随机数
        String clientId = mqttPropertiesConfig.getSubClientId() + "_" + UUID.fastUUID();
        String subTopic = mqttPropertiesConfig.getSubTopic2();
        log.info("订阅主题：{}", subTopic);
        MqttPahoMessageDrivenChannelAdapter mqttPahoMessageDrivenChannelAdapter = new MqttPahoMessageDrivenChannelAdapter(
                mqttPropertiesConfig.getUrl(),
                clientId,
                mqttPahoClientFactory,
                subTopic.split(",")
        );
        mqttPahoMessageDrivenChannelAdapter.setQos(1);
        mqttPahoMessageDrivenChannelAdapter.setConverter(new DefaultPahoMessageConverter());
        mqttPahoMessageDrivenChannelAdapter.setOutputChannel(messageInboundChannel3());
        return mqttPahoMessageDrivenChannelAdapter;
    }
    /**  指定处理消息来自哪个通道 */
    @Bean
    @ServiceActivator(inputChannel = "messageInboundChannel3")
    public MessageHandler messageHandler3(){
        return receiverMessageHandler3;
    }

    // @Bean
    // @ServiceActivator(inputChannel = "messageInboundChannel") // 确保通道名称正确
    // public MessageHandler deviceAlarmMessageHandler() {
    //     return new DeviceAlrmMessageHandler();
    // }
}