package com.ruoyi.dj.mqtt.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.dj.mqtt.common.CommonFields;
import com.ruoyi.dj.mqtt.common.CommonFieldsVo;

import java.util.HashMap;
import java.util.Map;

public class PayloadUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static String generatePayload(CommonFieldsVo commonFieldsVo, Object data) {
        Map<String, Object> payloadMap = new HashMap<>();
        payloadMap.put("tid", commonFieldsVo.getTid());
        payloadMap.put("bid", commonFieldsVo.getBid());
        if(commonFieldsVo.getMethod()!=null) {
            payloadMap.put("method", commonFieldsVo.getMethod());
        }
        payloadMap.put("gateway", commonFieldsVo.getGateway());
        payloadMap.put("data", data);

        try {
            return objectMapper.writeValueAsString(payloadMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 根据 json 数据 message 解析 data 中的 seq 字段
    public static Long getSeqFromJson(String json) {
        try {
            // 将 JSON 字符串转换为 Map 对象
            Map<String, Object> jsonMap = objectMapper.readValue(json, Map.class);
            // 获取 data 字段的值
            Map<String, Object> dataMap = (Map<String, Object>) jsonMap.get("data");
            // 获取 seq 字段的值
            return (Long) dataMap.get("seq");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String generatePayload(CommonFields commonFields, Object data) {
        Map<String, Object> payloadMap = new HashMap<>();
        payloadMap.put("tid", commonFields.getTid());
        payloadMap.put("bid", commonFields.getBid());
        payloadMap.put("method", commonFields.getMethod());
        payloadMap.put("gateway", commonFields.getGateway());
        payloadMap.put("timestamp", commonFields.getTimestamp());
        payloadMap.put("data", data);

        try {
            return objectMapper.writeValueAsString(payloadMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
