package com.fuyuanshen.global.mqtt.handler;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fuyuanshen.global.mqtt.base.MqttTopicInfo;
import com.fuyuanshen.global.mqtt.service.IotMqttService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


/**
 * IoT设备MQTT消息处理器
 * 用于处理设备上报的数据和响应消息
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IotMqttMessageHandler {

    private final IotMqttService iotMqttService;

    /**
     * 处理MQTT消息
     *
     * @param topic   主题
     * @param payload 消息内容
     */
    public void handleMessage(String topic, String payload) {
        try {
            // 解析主题
            MqttTopicInfo topicInfo = parseTopic(topic);
            if (topicInfo == null) {
                log.warn("无法解析MQTT主题: topic={}", topic);
                return;
            }

            // 解析消息内容
            JSONObject message = JSON.parseObject(payload);

            // 根据主题类型处理消息
            switch (topicInfo.getOperation()) {
                case "command":
                    // 处理下发指令（设备端不会主动发送command类型消息）
                    log.warn("收到非法的MQTT消息类型: operation={}", topicInfo.getOperation());
                    break;
                case "status":
                    // 处理设备对指令的响应
                    iotMqttService.handleCommandResponse(
                            topicInfo.getTenantCode(),
                            topicInfo.getDeviceType(),
                            topicInfo.getImei(),
                            message);
                    break;
                case "report":
                    // 处理设备主动上报的数据
                    handleDeviceReport(topicInfo, message);
                    break;
                default:
                    log.warn("未知的MQTT主题操作类型: operation={}", topicInfo.getOperation());
                    break;
            }
        } catch (Exception e) {
            log.error("处理MQTT消息时发生错误: topic={}, payload={}", topic, payload, e);
        }

    }

    /**
     * 解析MQTT主题
     *
     * @param topic 主题字符串
     * @return 主题信息对象
     */
    MqttTopicInfo parseTopic(String topic) {
        if (topic == null || topic.isEmpty()) {
            return null;
        }

        String[] parts = topic.split("/");
        if (parts.length != 4) {
            return null;
        }

        MqttTopicInfo info = new MqttTopicInfo();
        info.setOperation(parts[0]);
        info.setTenantCode(parts[1]);
        info.setDeviceType(parts[2]);
        info.setImei(parts[3]);
        return info;
    }

    /**
     * 处理设备上报数据
     *
     * @param topicInfo 主题信息
     * @param message   消息内容
     */
    private void handleDeviceReport(MqttTopicInfo topicInfo, JSONObject message) {
        // 获取时间戳
        Long timestamp = message.getLong("timestamp");

        // 处理批量数据上报
        if (message.containsKey("batch")) {
            JSONObject batchData = message.getJSONObject("batch");
            iotMqttService.handleBatchReport(
                    topicInfo.getTenantCode(),
                    topicInfo.getDeviceType(),
                    topicInfo.getImei(),
                    batchData,
                    timestamp);
        }
        // 处理单个数据上报
        else if (message.containsKey("sensor") && message.containsKey("value")) {
            String sensor = message.getString("sensor");
            Object value = message.get("value");
            iotMqttService.handleSingleReport(
                    topicInfo.getTenantCode(),
                    topicInfo.getDeviceType(),
                    topicInfo.getImei(),
                    sensor,
                    value,
                    timestamp);
        }
        // 处理其他格式的数据
        else {
            // 将整个消息作为批量数据处理
            iotMqttService.handleBatchReport(
                    topicInfo.getTenantCode(),
                    topicInfo.getDeviceType(),
                    topicInfo.getImei(),
                    message,
                    timestamp);
        }
    }
}