package com.wecloud.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cglib.beans.BeanMap;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * fasterxml 的json工具类
 *
 * @author lixiaozhong
 */
@Slf4j
public class JsonUtils {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    static {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    /**
     * Json格式的字符串向JavaBean转换，传入空串将返回null
     *
     * @param strJsonBody Json格式的字符串
     * @param c           目标JavaBean类型
     * @return JavaBean对象, 如果解析失败返回 null
     */
    public static <T> T decodeJson(String strJsonBody, Class<T> c) {
        if (StringUtils.isEmpty(strJsonBody)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(strJsonBody, c);
        } catch (IOException e) {
            log.warn("解析json字符串失败，原字符串: {}", strJsonBody, e);
            return null;
        }
    }

    /**
     * Json格式的字符串向JavaBean转换，传入空串将返回null （显式抛出异常）
     *
     * @param strJsonBody Json格式的字符串
     * @param c           目标JavaBean类型
     * @return JavaBean对象
     * @throws IOException
     */
    public static <T> T json2Object(String strJsonBody, Class<T> c) throws IOException {
        if (StringUtils.isEmpty(strJsonBody)) {
            return null;
        }
        return OBJECT_MAPPER.readValue(strJsonBody, c);
    }

    /**
     * Json格式的字符串向HashMap转换，传入空串将返回空map （显式抛出异常）
     *
     * @param strJsonBody Json格式的字符串
     * @return HashMap对象
     * @throws IOException
     */
    public static HashMap<String, Object> json2Map(String strJsonBody) throws IOException {
        if (StringUtils.isEmpty(strJsonBody)) {
            return new HashMap<String, Object>();
        }
        return OBJECT_MAPPER.readValue(strJsonBody, HashMap.class);
    }

    /**
     * Json格式的字符串向HashMap转换，传入空串将返回空map
     *
     * @param strJsonBody Json格式的字符串
     * @return HashMap对象
     * @throws IOException
     */
    public static HashMap<String, Object> decodeJson2Map(String strJsonBody) {
        if (StringUtils.isEmpty(strJsonBody)) {
            return new HashMap<String, Object>();
        }
        try {
            return OBJECT_MAPPER.readValue(strJsonBody, HashMap.class);
        } catch (IOException e) {
            log.warn("解析json字符串失败，原字符串: {}", strJsonBody);
            return null;
        }
    }



    /**
     *将json转换成Object对象
     * @param strJsonBody
     * @return
     * @throws IOException
     */
    public static Object json2Object(String strJsonBody) throws IOException {
        if (StringUtils.isEmpty(strJsonBody)) {
            return null;
        }
        // 每个属性的实际类型是string
        return OBJECT_MAPPER.readValue(strJsonBody, Object.class);
    }

    /**
     * Json格式的字符串向JavaBean List集合转换，传入空串将返回空list （显式抛出异常）
     *
     * @param strJsonBody
     * @param c
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> json2List(String strJsonBody, Class<T> c) throws IOException {
        if (StringUtils.isEmpty(strJsonBody)) {
            return Collections.emptyList();
        }
        JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, c);
        return OBJECT_MAPPER.readValue(strJsonBody, javaType);
    }

    /**
     * Json格式的字符串向JavaBean List集合转换，传入空串将返回空list
     *
     * @param strJsonBody
     * @param c
     * @return 对象列表，解析失败返回 null
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> decodeJsonToList(String strJsonBody, Class<T> c) {
        if (StringUtils.isEmpty(strJsonBody)) {
            return Collections.emptyList();
        }
        JavaType javaType = OBJECT_MAPPER.getTypeFactory().constructParametricType(ArrayList.class, c);
        try {
            return OBJECT_MAPPER.readValue(strJsonBody, javaType);
        } catch (IOException e) {
            log.warn("解析json字符串失败，原字符串: {}", strJsonBody);
            return null;
        }
    }

    /**
     * Json格式的字符串向List<String>集合转换，传入空串将返回null
     *
     * @param strJsonBody
     * @return
     * @throws IOException
     */
    public static List<String> json2List(String strJsonBody) throws IOException {
        return json2List(strJsonBody, String.class);
    }

    /**
     * Object转为Json格式字符串的方法（显式抛出异常）
     *
     * @param o
     * @return
     * @throws JsonProcessingException
     */
    public static String object2Json(Object o) throws JsonProcessingException {
        return OBJECT_MAPPER.writeValueAsString(o);
    }

    /**
     * Object转为Json格式字符串的方法
     *
     * @param o
     * @return 对象的json字符串，如果处理过程中出错，返回null
     */
    public static String encodeJson(Object o) {
        try {
            return OBJECT_MAPPER.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.warn("对象转换成json失败");
            return null;
        }
    }

    /**
     * 判断字符也许是JSON
     *
     * @param string
     * @return
     */
    public static boolean maybeJson(String string) {
        return maybeJsonArray(string) || maybeJsonObject(string);
    }

    /**
     * 判断字符也许是JSONArray
     *
     * @param string
     * @return
     */
    public static boolean maybeJsonArray(String string) {
        string = (null == string) ? string : string.trim();
        return string != null && ("null".equals(string) || (string.startsWith("[") && string.endsWith("]")));
    }

    /**
     * 判断字符也许是JSONObject
     *
     * @param string
     * @return
     */
    public static boolean maybeJsonObject(String string) {
        string = (null == string) ? string : string.trim();
        return string != null && ("null".equals(string) || (string.startsWith("{") && string.endsWith("}")));
    }

    /**
     * 将map装换为javabean对象，不支持深度转换，支持深度请看 mapToBeanDeep 方法
     *
     * @param map
     * @param clazz
     * @return
     */
    public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
        T obj = null;
        try {
            obj = clazz.newInstance();
        } catch (Exception e) {
            log.error("mapToBean转换，创建实例对象失败", e);
            return null;
        }
        BeanMap beanMap = BeanMap.create(obj);
        beanMap.putAll(map);
        return obj;
    }

    /**
     * 将一个 Map/javaBean 对象转化为一个 javaBean 深度
     * @param srcObject 要转化的对象，可以是map，bean
     * @param destClass 要转化的类型
     * @return 转化出来的 JavaBean 对象
     */
    public static <T>T beanCopyDeep(Object srcObject, Class<T> destClass) {
        String s = encodeJson(srcObject);
        return decodeJson(s, destClass);
    }

    private static boolean isFinalType(Class clazz) {
        if (clazz == String.class ) {
            return true;
        }
        if (clazz == Boolean.class) {
            return true;
        }
        if (clazz == Long.class) {
            return true;
        }
        if (clazz == Integer.class) {
            return true;
        }
        if (clazz == Double.class) {
            return true;
        }
        if (clazz == Float.class) {
            return true;
        }
        if (clazz == Short.class) {
            return true;
        }
        if (clazz == BigDecimal.class) {
            return true;
        }
        if (clazz == Byte.class) {
            return true;
        }
        if (clazz == int.class) {
            return true;
        }
        if (clazz == long.class) {
            return true;
        }
        if (clazz == float.class) {
            return true;
        }
        if (clazz == double.class) {
            return true;
        }
        if (clazz == byte.class) {
            return true;
        }
        if (clazz == char.class) {
            return true;
        }
        if (clazz == short.class) {
            return true;
        }
        if (clazz == boolean.class) {
            return true;
        }
        return false;
    }

    /**
     * 将javabean对象转换为map
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                Object value = beanMap.get(key);
                map.put(key + "", value);
            }
        }
        return map;
    }
}
