package com.ruoyi.imserver.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;

import java.util.Map;

public class LongToStringConverter {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static Map<String, Object> convertLongToString(Object data) {
        // 利用 Jackson 的树模型，将所有数字节点转为字符串
        JsonNode node = MAPPER.valueToTree(data);
        convertNumberNodesToString(node);
        return MAPPER.convertValue(node, new TypeReference<Map<String, Object>>() {});
    }

    private static void convertNumberNodesToString(JsonNode node) {
        if (node.isObject()) {
            ObjectNode obj = (ObjectNode) node;
            obj.fieldNames().forEachRemaining(fieldName -> {
                JsonNode child = obj.get(fieldName);
                if (child.isNumber()) {
                    obj.put(fieldName, child.asText());   // 数字转字符串
                } else if (child.isObject() || child.isArray()) {
                    convertNumberNodesToString(child);
                }
            });
        } else if (node.isArray()) {
            ArrayNode array = (ArrayNode) node;
            for (int i = 0; i < array.size(); i++) {
                JsonNode element = array.get(i);
                if (element.isNumber()) {
                    array.set(i, TextNode.valueOf(element.asText()));   // 数组内数字元素 → 字符串
                } else if (element.isObject() || element.isArray()) {
                    convertNumberNodesToString(element);
                }
            }
        }
    }
}
