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

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Q20电池数据处理（method: battery）
 * 上报智能电池详细状态：id, full_charge_capacity, charge_remaining, voltage, current,
 * low_volt_warn_value, status(0异常/1开机/2充电中/3需保养), temperature, cycle_index,
 * time_flying, time_remaining, charge_time_remaining, health, flags, uid, version
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/5/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Q20BatteryHandler implements MessageHandler {

    private final InfluxService influxService;

    @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);
            if (data != null) {
                // 以电池id区分多块电池，按id聚合缓存到同一key下，便于在线查询时一次取出全部电池
                Integer batteryId = data.getInt("id");
                cacheBattery(deviceSn, batteryId, data);
                saveToInflux(deviceSn, batteryId, data);
//                log.debug("Q20 battery --> deviceSn: {}, id: {}, charge_remaining: {}%, status: {}",
//                        deviceSn, batteryId, data.getFloat("charge_remaining"), data.getInt("status"));
            }
        } else {
            log.debug("Q20 battery --> payload解析失败，解析后为null");
        }
    }

    /**
     * 将单块电池按id聚合到 {@code q20_battery_{sn}} 缓存项下（LinkedHashMap：id -> 电池数据）
     */
    @SuppressWarnings("unchecked")
    private void cacheBattery(String deviceSn, Integer batteryId, JSONObject data) {
        String cacheKey = Q20Constant.Q20_BATTERY + deviceSn;
        Object cached = CacheUtils.get(cacheKey);
        Map<Integer, JSONObject> batteries = cached instanceof Map
                ? (Map<Integer, JSONObject>) cached
                : new LinkedHashMap<>();
        batteries.put(batteryId, data);
        CacheUtils.set(cacheKey, batteries);
    }

    private void saveToInflux(String deviceSn, Integer batteryId, JSONObject data) {
        Q20BatteryReport report = Q20BatteryReport.builder()
                .deviceSn(deviceSn)
                .battery_id(batteryId != null ? String.valueOf(batteryId) : null)
                .order_id(data.getStr("order_id"))
                .full_charge_capacity(data.getInt("full_charge_capacity"))
                .charge_remaining(data.getFloat("charge_remaining"))
                .voltage(data.getInt("voltage"))
                .current(data.getInt("current"))
                .low_volt_warn_value(data.getInt("low_volt_warn_value"))
                .status(data.getInt("status"))
                .temperature(data.getFloat("temperature"))
                .cycle_index(data.getInt("cycle_index"))
                .time_flying(data.getLong("time_flying"))
                .time_remaining(data.getInt("time_remaining"))
                .charge_time_remaining(data.getInt("charge_time_remaining"))
                .health(data.getInt("health"))
                .flags(data.getInt("flags"))
                .uid(data.getStr("uid"))
                .version(data.getStr("version"))
                .build();
        influxService.addRecord(report);
    }
}
