package shop.alien.second.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

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

    /**
     * 从JSON字符串中获取指定key的值
     */
    public static String getJsonValue(String jsonString, String key) {
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            JsonNode valueNode = jsonNode.get(key);
            return valueNode != null ? valueNode.asText() : null;
        } catch (Exception e) {
            throw new RuntimeException("解析JSON失败", e);
        }
    }

    /**
     * 获取指定key的值（支持各种数据类型）
     */
    public static <T> T getJsonValue(String jsonString, String key, Class<T> valueType) {
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            JsonNode valueNode = jsonNode.get(key);
            return objectMapper.treeToValue(valueNode, valueType);
        } catch (Exception e) {
            throw new RuntimeException("解析JSON失败", e);
        }
    }


    /**
     * 从图片对象中获取URL（支持多种可能的字段名）
     * 例如：从 banner_image 或 vertical_image 对象中获取 url 或 imgUrl
     *
     * @param jsonString JSON字符串
     * @param imageObjectKey 图片对象的key，如 "banner_image" 或 "vertical_image"
     * @return 图片URL字符串，如果不存在则返回null
     */
    public static String getImageUrlFromObject(String jsonString, String imageObjectKey) {
        try {
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            JsonNode dataNode = jsonNode.get("data");
            if (dataNode == null) {
                return null;
            }
            
            JsonNode imageNode = dataNode.get(imageObjectKey);
            if (imageNode == null || !imageNode.isObject()) {
                return null;
            }
            
            // 尝试常见的URL字段名
            String[] possibleUrlFields = {"url", "imgUrl", "imageUrl", "img_url", "image_url"};
            for (String field : possibleUrlFields) {
                JsonNode urlNode = imageNode.get(field);
                if (urlNode != null && urlNode.isTextual()) {
                    return urlNode.asText();
                }
            }
            
            return null;
        } catch (Exception e) {
            throw new RuntimeException("解析图片URL失败，对象key: " + imageObjectKey, e);
        }
    }

    /**
     * 获取banner图片URL
     *
     * @param jsonString JSON字符串
     * @return banner图片URL
     */
    public static String getBannerImageUrl(String jsonString) {
        return getImageUrlFromObject(jsonString, "banner_image");
    }

    /**
     * 获取竖版图片URL
     *
     * @param jsonString JSON字符串
     * @return 竖版图片URL
     */
    public static String getVerticalImageUrl(String jsonString) {
        return getImageUrlFromObject(jsonString, "vertical_image");
    }
}
