package com.ruoyi.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.ruoyi.common.exception.ServiceException;

import java.io.IOException;
import java.math.BigDecimal;

/**
 * 类型转换工具
 */
public class ClassConvertUtils {

    public static Long objToLong(Object value) {
        return Long.valueOf(String.valueOf(value));
    }

    public static Integer objToInteger(Object value) {
        return Integer.valueOf(String.valueOf(value));
    }

    public static Boolean objToBoolean(Object value) {
        return Boolean.valueOf(String.valueOf(value));
    }

    public static BigDecimal objToBigDecimal(Object value) {
        return BigDecimal.valueOf(Double.valueOf(String.valueOf(value)));
    }


    public static <T> T stringToClassSnake(String value, TypeReference<T> reference) throws IOException {
        return stringToClass(value, reference, PropertyNamingStrategy.SNAKE_CASE);
    }

    public static <T> T stringToClass(String value, TypeReference<T> reference, PropertyNamingStrategy strategy) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setPropertyNamingStrategy(strategy);
        return objectMapper.readValue(value, reference);

    }


    public static String transformJSON(Object object, PropertyNamingStrategy strategy) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(strategy);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException var3) {
            throw new ServiceException(var3.getOriginalMessage());
        }
    }

    public static String transformJSONToSnake(Object object) {
        return transformJSON(object, PropertyNamingStrategy.SNAKE_CASE);
    }
}
