package com.ssyf.common.core.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;

import java.util.Map;

/**
 * 
 * @author huwei
 * @date 2023/2/12 13:29
 */
public class TypeEnhanceUtil {
    
    public static boolean isNumber(Object value){
        Class<?> valueClass = value.getClass();
        if (valueClass.isAssignableFrom(byte.class) || valueClass.isAssignableFrom(Byte.class)) {
            return true;
        }
        if (valueClass.isAssignableFrom(short.class) || valueClass.isAssignableFrom(Short.class)) {
            return true;
        }
        if (valueClass.isAssignableFrom(int.class) || valueClass.isAssignableFrom(Integer.class)) {
            return true;
        }
        if (valueClass.isAssignableFrom(long.class) || valueClass.isAssignableFrom(Long.class)) {
            return true;
        }
        if (valueClass.isAssignableFrom(float.class) || valueClass.isAssignableFrom(Float.class)) {
            return true;
        }
        if (valueClass.isAssignableFrom(double.class) || valueClass.isAssignableFrom(Double.class)) {
            return true;
        }
        return false;
    }

    public static boolean isBoolean(Object object){
        return object.getClass().isAssignableFrom(boolean.class) || object.getClass().isAssignableFrom(Boolean.class);
    }

    public static boolean isString(Object object){
        return object.getClass().isAssignableFrom(String.class);
    }

    public static boolean isChar(Object object){
        return object.getClass().isAssignableFrom(char.class) || object.getClass().isAssignableFrom(Character.class);
    }

    public static boolean isBaseType(Object object){
        return isNumber(object) || isBoolean(object) || isChar(object) || isString(object);
    }

    public static String getStringValue(Object value){
        if(value == null){
            return "";
        }
        final String jsonValueKey = "value";
        String json = JSONUtil.toJsonStr(MapUtil.builder().put(jsonValueKey ,value).build());
        return JSONUtil.toBean(json , Map.class).get(jsonValueKey).toString();
    }

    public static Long toLongDefaultNull(Object value){
        return toLong(value ,null);
    }

    public static Long toLong(Object value ,Long defaultValue){
        try {
            return Long.parseLong(value.toString());
        }catch (Exception e){}
        return defaultValue;
    }

    /**
     * 值比较
     * @param obj
     * @param other
     * @return
     */
    public static boolean isValueEquals(Object obj , Object other){
        if(obj == other){
            return true;
        }
        if(obj == null || other == null){
            return false;
        }
        if(obj.toString().equals(other.toString())){
            return true;
        }
        return getStringValue(obj).equals(getStringValue(other));
    }
}
