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

/**
 * Q20负载数据处理（method: mount）
 * 上报挂载负载状态：mount_id, mount_port, mount_type, payload(yaw/pitch/roll/mode/zoom等)
 * 支持ZT30(四光)、Z40T(双光)、A30(三光)、GL60P(探照灯)、4C(抛投器)、SZY/YKX/EayLoad10(索降)、
 * LC(物流箱)、PARACHUTE(降落伞)等各类型负载
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/5/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Q20MountHandler 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_MOUNT + deviceSn, data);
                saveToInflux(deviceSn, data);
//                log.debug("Q20 mount --> deviceSn: {}, mount_type: {}, mount_port: {}",
//                        deviceSn, data.getStr("mount_type"), data.getInt("mount_port"));
            }
        } else {
            log.debug("Q20 mount --> payload解析失败，解析后为null");
        }
    }

    private void saveToInflux(String deviceSn, JSONObject data) {
        JSONObject payload = data.getJSONObject("payload");

        Q20MountReport report = Q20MountReport.builder()
                .deviceSn(deviceSn)
                .order_id(data.getStr("order_id"))
                .mount_id(data.getStr("mount_id"))
                .mount_port(data.getInt("mount_port"))
                .mount_type(data.getStr("mount_type"))
                .payload_yaw(payload != null ? payload.getFloat("yaw") : null)
                .payload_pitch(payload != null ? payload.getFloat("pitch") : null)
                .payload_roll(payload != null ? payload.getFloat("roll") : null)
                .payload_mode(payload != null ? payload.getInt("mode") : null)
                .payload_zoom(payload != null ? payload.getFloat("zoom") : null)
                .build();
        influxService.addRecord(report);
    }
}
