package com.ruoyi.web.core.wvp;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.web.core.wvp.domain.ApiResponse;

import java.util.List;
import java.util.Map;

public class JsonParser {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 方法1: 使用TypeReference
    public static <T> ApiResponse<T> parseWithTypeReference(String json, Class<T> dataType) {
        try {
            JavaType type = objectMapper.getTypeFactory()
                    .constructParametricType(ApiResponse.class, dataType);
            return objectMapper.readValue(json, type);
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败: " + json, e);
        }
    }

    // 通用解析方法
    public static <T> ApiResponse<T> parseResponse(String json, JavaType dataType) {
        try {
            JavaType responseType = objectMapper.getTypeFactory()
                    .constructParametricType(ApiResponse.class, dataType);
            return objectMapper.readValue(json, responseType);
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }
    // 解析为指定类型的便捷方法
    public static <T> ApiResponse<T> parseToTypedResponse(String json, Class<T> dataType) {
        return parseResponse(json, objectMapper.getTypeFactory().constructType(dataType));
    }

    // 方法2: 使用JavaType
    public static <T> ApiResponse<T> parseWithJavaType(String json, Class<T> dataType) {
        try {
            JavaType javaType = objectMapper.getTypeFactory()
                    .constructParametricType(ApiResponse.class, dataType);
            return objectMapper.readValue(json, javaType);
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }

    // 方法3: 处理嵌套泛型（如List<T>）
    public static <T> ApiResponse<List<T>> parseListResponse(String json, Class<T> elementType) {
        try {
            JavaType elementJavaType = objectMapper.getTypeFactory()
                    .constructType(elementType);
            JavaType listType = objectMapper.getTypeFactory()
                    .constructCollectionType(List.class, elementType);
            JavaType responseType = objectMapper.getTypeFactory()
                    .constructParametricType(ApiResponse.class, listType);
            return objectMapper.readValue(json, responseType);
        } catch (Exception e) {
            throw new RuntimeException("JSON解析失败", e);
        }
    }

    // 转换为Map
    public static Map<String, Object> parseJsonToMap(String json) throws Exception {
        return objectMapper.readValue(json, new TypeReference<Map<String, Object>>() {});
    }
}