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设备通知事件处理（method: notify，state topic）
 * 设备状态变化时触发上报，包含：index, type, level(0紧急/2严重/4告警/6提示),
 * message, timestamp, value(故障码), clear_codes(清除码)
 * 若need_reply=1需回复 state_reply 主题
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/5/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Q20NotifyHandler 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) {
            String deviceSn = message.getStr(BusinessConstant.GATEWAY);
            JSONObject data = message.getJSONObject(BusinessConstant.DATA);
            Integer needReply = message.getInt(BusinessConstant.NEED_REPLY);
            if (needReply != null && needReply == 1) {
                data.clear();
                data.set("result", 0);
                message.remove(BusinessConstant.NEED_REPLY);
                mqttPushService.pushMessageByClient2(topic + BusinessConstant._REPLY, message.toString());
                log.debug("Q20 notify --> 已回复, deviceSn: {}", deviceSn);
            }
            // 重新解析，避免回复时修改了data对象
            message = JsonUtils.parseObject(payload, JSONObject.class);
            if (message == null) {
                return;
            }
            data = message.getJSONObject(BusinessConstant.DATA);
            if (data != null) {
                log.warn("Q20 notify --> deviceSn: {}, type: {}, level: {}, message: {}, value: {}",
                        deviceSn, data.getStr("type"), data.getInt("level"),
                        data.getStr("message"), data.getStr("value"));
            }
        } else {
            log.debug("Q20 notify --> payload解析失败，解析后为null");
        }
    }
}
