package com.fuyuanshen.global.mqtt.handler;

import com.alibaba.fastjson2.JSON;
import com.fuyuanshen.global.mqtt.base.MqttMessage;
import com.fuyuanshen.global.mqtt.service.MqttMessageService;
import com.fuyuanshen.global.mqtt.utils.MqttTopicUtils;
import com.fuyuanshen.global.mqtt.base.MqttTopicInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * MQTT消息处理器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class MqttMessageHandler {
    
    private final MqttMessageService mqttMessageService;

    
    /**
     * 处理MQTT消息
     * @param topic 主题
     * @param payload 消息内容
     */
    public void handleMessage(String topic, String payload) {
        try {
            // 解析主题
            MqttTopicInfo topicInfo = MqttTopicUtils.parseTopic(topic);
            if (topicInfo == null) {
                log.warn("无法解析MQTT主题: topic={}", topic);
                return;
            }
            
            // 解析消息内容
            MqttMessage message = JSON.parseObject(payload, MqttMessage.class);
            
            // 根据主题类型处理消息
            switch (topicInfo.getOperation()) {
                case "command":
                    // 处理下发指令（设备端不会主动发送command类型消息）
                    log.warn("收到非法的MQTT消息类型: operation={}", topicInfo.getOperation());
                    break;
                case "status":
                    // 处理设备对指令的响应
                    mqttMessageService.handleCommandResponse(
                            topicInfo.getTenantCode(),
                            topicInfo.getDeviceType(),
                            topicInfo.getImei(),
                            message);
                    break;
                case "report":
                    // 处理设备主动上报的数据
                    mqttMessageService.handleDeviceReport(
                            topicInfo.getTenantCode(),
                            topicInfo.getDeviceType(),
                            topicInfo.getImei(),
                            message);
                    break;
                default:
                    log.warn("未知的MQTT主题操作类型: operation={}", topicInfo.getOperation());
                    break;
            }
        } catch (Exception e) {
            log.error("处理MQTT消息时发生错误: topic={}, payload={}", topic, payload, e);
        }
    }

}