package com.ruoyi.common.utils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.List;

public class JsonUtil {
    private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public JsonUtil() {
    }

    public static String toJson(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    public static <T> T toModel(String json, TypeReference<T> reference) {
        try {
            T obj = objectMapper.readValue(json, reference);
            return obj;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    public static <T> T toModel(String json, Class<T> type) {
        try {
            return objectMapper.readValue(json, type);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage());
        }
    }

    public static <T> List<T> toModel(String jsonStr, Class<?> collectionClass, Class<T> elementClasses) {
        try {
            JavaType type = objectMapper.getTypeFactory().constructParametricType(collectionClass, new Class[]{elementClasses});
            return (List) objectMapper.readValue(jsonStr, type);
        } catch (Exception var4) {
            throw new IllegalStateException(var4.getMessage());
        }
    }

    static {
        objectMapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
        objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
        objectMapper.setSerializationInclusion(Include.NON_EMPTY);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy/MM/dd - HH:mm:ss Z"));
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(new JavaTimeModule());
    }
}
