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

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

/**
 * Q20设备State主题分发器
 * 接收 thing/device/{device_sn}/state 主题消息，根据payload中的method字段分发到对应处理器
 * method: version(固件版本) | notify(设备通知事件) | hms(系统健康状态)
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/5/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Q20StateTopicHandler implements MessageHandler {

    private final Q20VersionHandler q20VersionHandler;
    private final Q20NotifyHandler q20NotifyHandler;
    private final Q20HmsHandler q20HmsHandler;

    @Override
    public void handleMessage(String topic, String payload, String gateway) {
        JSONObject message = JsonUtils.parseObject(payload, JSONObject.class);
        if (message == null) {
            log.debug("Q20 state topic --> payload解析失败，解析后为null");
            return;
        }
        String method = message.getStr(BusinessConstant.METHOD);
        if (method == null) {
            log.debug("Q20 state topic --> method字段缺失, topic: {}", topic);
            return;
        }
        switch (method) {
            case Q20Constant.METHOD_VERSION:
                q20VersionHandler.handleMessage(topic, payload, gateway);
                break;
            case Q20Constant.METHOD_NOTIFY:
                q20NotifyHandler.handleMessage(topic, payload, gateway);
                break;
            case Q20Constant.METHOD_HMS:
                q20HmsHandler.handleMessage(topic, payload, gateway);
                break;
            default:
                log.debug("Q20 state topic --> 未知method: {}", method);
        }
    }
}
