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

/**
 * Q20 RTK数据处理（method: rtk）
 * 上报RTK定位信息：fix_type, latitude, longitude, altitude, ellipsoid_height,
 * satellite_visible, eph, epv, velocity, yaw, cog, horizontal_acc, vertical_acc, velocity_acc
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/5/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Q20RtkHandler 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) {
                CacheUtils.set(Q20Constant.Q20_RTK + deviceSn, data);
                saveToInflux(deviceSn, data);
//                log.debug("Q20 rtk --> deviceSn: {}, fix_type: {}, satellites: {}",
//                        deviceSn, data.getInt("fix_type"), data.getInt("satellite_visible"));
            }
        } else {
            log.debug("Q20 rtk --> payload解析失败，解析后为null");
        }
    }

    private void saveToInflux(String deviceSn, JSONObject data) {
        Q20RtkReport report = Q20RtkReport.builder()
                .deviceSn(deviceSn)
                .order_id(data.getStr("order_id"))
                .fix_type(data.getInt("fix_type"))
                .latitude(data.getDouble("latitude"))
                .longitude(data.getDouble("longitude"))
                .altitude(data.getFloat("altitude"))
                .ellipsoid_height(data.getFloat("ellipsoid_height"))
                .satellite_visible(data.getInt("satellite_visible"))
                .eph(data.getFloat("eph"))
                .epv(data.getFloat("epv"))
                .velocity(data.getFloat("velocity"))
                .yaw(data.getFloat("yaw"))
                .cog(data.getFloat("cog"))
                .horizontal_acc(data.getFloat("horizontal_acc"))
                .vertical_acc(data.getFloat("vertical_acc"))
                .velocity_acc(data.getFloat("velocity_acc"))
                .build();
        influxService.addRecord(report);
    }
}
