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

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

/**
 * Q20避障数据处理（method: obs）
 * 上报避障传感器状态：cp_distance(避障距离/m), cp_enable(避障开关),
 * ver_distances(垂直方向[下方,上方]障碍物距离数组/-1表示无障碍物),
 * around_distances(水平方向8方位障碍物距离数组/-1表示无障碍物，从正前方顺时针)
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/5/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Q20ObsHandler 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_OBS + deviceSn, data);
                saveToInflux(deviceSn, data);
//                log.debug("Q20 obs --> deviceSn: {}, cp_distance: {}m, cp_enable: {}",
//                        deviceSn, data.getFloat("cp_distance"), data.getInt("cp_enable"));
            }
        } else {
            log.debug("Q20 obs --> payload解析失败，解析后为null");
        }
    }

    private void saveToInflux(String deviceSn, JSONObject data) {
        JSONArray verDistances = data.getJSONArray("ver_distances");
        JSONArray aroundDistances = data.getJSONArray("around_distances");

        Q20ObsReport report = Q20ObsReport.builder()
                .deviceSn(deviceSn)
                .order_id(data.getStr("order_id"))
                .cp_distance(data.getFloat("cp_distance"))
                .cp_enable(data.getInt("cp_enable"))
                .ver_down(getFloat(verDistances, 0))
                .ver_up(getFloat(verDistances, 1))
                .around_0(getFloat(aroundDistances, 0))
                .around_1(getFloat(aroundDistances, 1))
                .around_2(getFloat(aroundDistances, 2))
                .around_3(getFloat(aroundDistances, 3))
                .around_4(getFloat(aroundDistances, 4))
                .around_5(getFloat(aroundDistances, 5))
                .around_6(getFloat(aroundDistances, 6))
                .around_7(getFloat(aroundDistances, 7))
                .build();
        influxService.addRecord(report);
    }

    private Float getFloat(JSONArray array, int index) {
        if (array == null || array.size() <= index) {
            return null;
        }
        Object val = array.get(index);
        if (val == null) {
            return null;
        }
        return ((Number) val).floatValue();
    }
}
