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

/**
 * Q20遥控链路数据处理（method: rc）
 * 上报遥控与链路信息：priority, rc_channel_state, rc_state,
 * link数组(id/type/connected/inuse/sqe/band), up_loss_rate, down_loss_rate, network信息
 *
 * @author 938693313@qq.com
 * @since 1.0.0 2026/5/12
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class Q20RcHandler 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_RC + deviceSn, data);
                saveToInflux(deviceSn, data);
//                log.debug("Q20 rc --> deviceSn: {}, priority: {}, rc_state: {}",
//                        deviceSn, data.getInt("priority"), data.getStr("rc_state"));
            }
        } else {
            log.debug("Q20 rc --> payload解析失败，解析后为null");
        }
    }

    private void saveToInflux(String deviceSn, JSONObject data) {
        // 从link数组中取inuse=1的链路，无则取第一条
        JSONObject inuseLink = null;
        JSONArray links = data.getJSONArray("link");
        if (links != null) {
            for (int i = 0; i < links.size(); i++) {
                JSONObject link = links.getJSONObject(i);
                if (link != null && Integer.valueOf(1).equals(link.getInt("inuse"))) {
                    inuseLink = link;
                    break;
                }
            }
            if (inuseLink == null && !links.isEmpty()) {
                inuseLink = links.getJSONObject(0);
            }
        }
        JSONObject network = data.getJSONObject("network");

        Q20RcReport report = Q20RcReport.builder()
                .deviceSn(deviceSn)
                .order_id(data.getStr("order_id"))
                .priority(data.getInt("priority"))
                .rc_channel_state(data.getStr("rc_channel_state"))
                .rc_state(data.getStr("rc_state"))
                .up_loss_rate(data.getFloat("up_loss_rate"))
                .down_loss_rate(data.getFloat("down_loss_rate"))
                .link_inuse_id(inuseLink != null ? inuseLink.getInt("id") : null)
                .link_inuse_type(inuseLink != null ? inuseLink.getInt("type") : null)
                .link_inuse_sqe(inuseLink != null ? inuseLink.getInt("sqe") : null)
                .link_inuse_band(inuseLink != null ? inuseLink.getInt("band") : null)
                .network_type(network != null ? network.getInt("type") : null)
                .network_quality(network != null ? network.getInt("quality") : null)
                .build();
        influxService.addRecord(report);
    }
}
