package com.artfess.rescue.mqtt.config;

import com.artfess.rescue.mqtt.model.MqttServerConfig;
import com.artfess.rescue.mqtt.service.MqttConfigService;
import com.artfess.rescue.video.manager.GpsService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: wsf
 * @Description: MQTT动态配置核心类
 * @DateTime: 2025/3/17 17:45
 **/
@Configuration
@Slf4j
public class MqttDynamicConfig {

    @Resource
    private MqttConfigService configService;
    @Resource
    private GpsService gpsService;

    @EventListener(ApplicationReadyEvent.class)
    public void setupMqttConnections() {
        if (!configService.isMqttEnabled()) {
            log.info("mqtt配置关闭，不监听数据！");
            return;
        }
        List<MqttServerConfig> configs = configService.fetchMqttConfigurations();
        if (configs != null && !configs.isEmpty()) {
            for (MqttServerConfig config : configs) {
                try {
                    MqttClient client = new MqttClient(config.getServerUrl(), config.getClientId());
                    MqttConnectOptions options = new MqttConnectOptions();
                    options.setUserName(config.getUsername());
                    options.setPassword(config.getPassword().toCharArray());
                    options.setCleanSession(false);
                    options.setConnectionTimeout(1800);
                    options.setKeepAliveInterval(20);
                    options.setAutomaticReconnect(true);
                    client.connect(options);

                    client.subscribe(config.getTopic(), config.getQos(), (topic, message) -> {
                        // 处理接收到的消息
                        handleMqttMessage(topic, new String(message.getPayload()));
                    });
                    log.info("MQTT 连接建立成功:{},{} " , config.getServerUrl() , config.getClientId());
                } catch (MqttException e) {
                    e.printStackTrace();
                    log.error("MQTT 连接失败: {},{}", config.getServerUrl(),e.getMessage());
                }
            }
        } else {
            log.error("未获取到 MQTT 服务器配置，无法创建 MQTT 连接！");
        }
    }

    private void handleMqttMessage(String topic, String payload) {
        log.debug("接收到主题 [ {} ]的消息:{} ",topic,payload);
        // 缓存到redis
        gpsService.save(payload);
    }

    @Bean
    @Scope("prototype")
    public MessageHandler mqttMessageHandler() {
        return new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {
                String topic = (String) message.getHeaders().get("mqtt_receivedTopic");
                String payload = (String) message.getPayload();
                if (topic != null && payload != null) {
                    handleMqttMessage(topic, payload);
                } else {
                   log.error("接收到的消息主题或内容为空");
                }
            }
        };
    }

}
