package com.multictrl.modules.business.q20.handler;

import cn.hutool.json.JSONObject;
import com.multictrl.common.constant.BusinessConstant;
import com.multictrl.common.utils.CacheUtils;
import com.multictrl.common.utils.JsonUtils;
import com.multictrl.modules.business.handler.MessageHandler;
import com.multictrl.modules.business.service.MqttPushService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Q20设备拓扑状态处理（topic: sys/device/{device_sn}/status）
 * method: online(设备上线) | heartbeat(心跳维持在线)
 * 两种消息均需回复 sys/device/{device_sn}/status_reply
 * 35s内无消息则缓存过期，视为设备离线
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/5/20
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Q20StatusHandler implements MessageHandler {

    private final MqttPushService mqttPushService;

    @Override
    public void handleMessage(String topic, String payload, String gateway) {
        JSONObject message = JsonUtils.parseObject(payload, JSONObject.class);
        if (message == null) {
            log.debug("Q20 status --> payload解析失败，解析后为null");
            return;
        }
        String deviceSn = message.getStr(BusinessConstant.GATEWAY);
        String method = message.getStr(BusinessConstant.METHOD);
        if (method == null) {
            log.debug("Q20 status --> method字段缺失, topic: {}", topic);
            return;
        }

        switch (method) {
            case Q20Constant.METHOD_ONLINE:
                handleOnline(topic, message, deviceSn);
                break;
            case Q20Constant.METHOD_HEARTBEAT:
                handleHeartbeat(topic, message, deviceSn);
                break;
            default:
                log.debug("Q20 status --> 未知method: {}, deviceSn: {}", method, deviceSn);
        }
    }

    /**
     * 设备上线：刷新在线缓存，回复 status_reply（output为空对象）
     */
    private void handleOnline(String topic, JSONObject message, String deviceSn) {
        CacheUtils.set(Q20Constant.Q20_ONLINE + deviceSn, true, Q20Constant.ONLINE_TTL_MS);
        log.info("Q20 status --> 设备上线, deviceSn: {}", deviceSn);
        Integer needReply = message.getInt(BusinessConstant.NEED_REPLY);
        if (needReply != null && needReply == 1) {
            sendReply(topic, message, new JSONObject());
        }
    }

    /**
     * 心跳：刷新在线缓存TTL，回复 status_reply（output含uplink上行延迟ms）
     */
    private void handleHeartbeat(String topic, JSONObject message, String deviceSn) {
        CacheUtils.set(Q20Constant.Q20_ONLINE + deviceSn, true, Q20Constant.ONLINE_TTL_MS);
//        log.debug("Q20 status --> 心跳, deviceSn: {}", deviceSn);
        Integer needReply = message.getInt(BusinessConstant.NEED_REPLY);
        if (needReply != null && needReply == 1) {
            long uplink = 0;
            Long timestamp = message.getLong("timestamp");
            if (timestamp != null && timestamp > 0) {
                uplink = Math.max(0, System.currentTimeMillis() - timestamp);
            }
            JSONObject output = new JSONObject();
            output.set("uplink", uplink);
            sendReply(topic, message, output);
        }
    }

    private void sendReply(String topic, JSONObject message, JSONObject output) {
        JSONObject data = new JSONObject();
        data.set("result", 0);
        data.set("output", output);
        message.set(BusinessConstant.DATA, data);
        message.set("timestamp", System.currentTimeMillis());
        message.remove(BusinessConstant.NEED_REPLY);
        String replyTopic = topic + Q20Constant.STATUS_REPLY_SUFFIX;
        mqttPushService.pushMessageByClient1(replyTopic, message.toString());
//        log.debug("Q20 status --> 已回复, topic: {}", replyTopic);
    }
}
