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 com.multictrl.modules.business.service.MqttPushService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Q20设备请求消息处理（topic: thing/device/{device_sn}/requests）
 * <p>method: hangar_charge_control(飞行器请求充电电压电流)。
 * 收到飞行器充电请求后，平台充电器自动回复 requests_reply 主题，
 * 回传充电器实际可提供的电压/电流（当前按请求值原样应答，表示同意按需供电）。
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/6/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Q20RequestsHandler 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 requests --> payload解析失败，解析后为null");
            return;
        }

        String method = message.getStr(BusinessConstant.METHOD);
        if (method == null) {
            log.debug("Q20 requests --> method字段缺失, topic: {}", topic);
            return;
        }

        if (Q20Constant.METHOD_HANGAR_CHARGE_CONTROL.equals(method)) {
            handleHangarChargeControl(topic, message);
        } else {
            log.debug("Q20 requests --> 未知method: {}, gateway: {}", method, gateway);
        }
    }

    /**
     * 飞行器请求充电：自动回复充电器电压/电流。
     * <p>请求 data: {voltage(请求充电电压V*10), current(请求充电电流A*10)}；
     * 回复主题 thing/device/{sn}/requests_reply，data 回传充电器电压/电流（原样应答请求值）。
     */
    private void handleHangarChargeControl(String topic, JSONObject message) {
        JSONObject data = message.getJSONObject(BusinessConstant.DATA);
        int voltage = data != null ? data.getInt("voltage", 0) : 0;
        int current = data != null ? data.getInt("current", 0) : 0;

        // 原样应答 tid/bid/method/gateway，data 回传充电器电压/电流，刷新时间戳
        JSONObject reply = new JSONObject();
        reply.set("voltage", voltage);
        reply.set("current", current);
        message.set(BusinessConstant.DATA, reply);
        message.set("timestamp", System.currentTimeMillis());

        String replyTopic = topic + BusinessConstant._REPLY;
        mqttPushService.pushMessageByClient1(replyTopic, message.toString());
        log.info("Q20 requests --> 飞行器请求充电已自动回复, topic: {}, voltage: {}, current: {}",
                replyTopic, voltage, current);
    }
}
