package com.fufan.mtsaas.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.*;
import org.apache.commons.collections.KeyValue;

import java.util.List;
import java.util.Map;

/**
 * Json工具类
 * @author hasee
 */
public class JSonUtil {


    private static final SerializeConfig config;

    static {
        config = new SerializeConfig();
        //对JSON中日期进行格式化处理 zhangjinye
        config.put(java.util.Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); // 使用和json-lib兼容的日期输出格式
        config.put(java.sql.Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); // 使用和json-lib兼容的日期输出格式
    }

    private static final SerializerFeature[] features = {SerializerFeature.WriteMapNullValue, // 输出空置字段
            SerializerFeature.WriteNullListAsEmpty, // list字段如果为null，输出为[]，而不是null
            //SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null，输出为0，而不是null
            //SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null，输出为false，而不是null
            SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null，输出为""，而不是null
    };


    public static String toJSONString(Object object) {

        String  ret= "";

        if(object == null)
        {
            return ret;
        }

       try {
           ret = JSON.toJSONString(object, config, features);
       }catch (Exception e)
       {
           ret = "toJSONString转异常：[入参：" + object.toString() +"]  message= "+ e.getMessage();
       }
        return ret;
    }

    public static String toJSONNoFeatures(Object object) {
        return JSON.toJSONString(object, config);
    }

//    public static Object toBean(String text) {
//        return JSON.parse(text);
//    }

    public static <T> T toBean(String text, Class<T> clazz) {
        return JSON.parseObject(text, clazz);
    }

    // 转换为数组
    public static <T> Object[] toArray(String text) {
        return toArray(text, null);
    }

    // 转换为数组
    public static <T> Object[] toArray(String text, Class<T> clazz) {
        return JSON.parseArray(text, clazz).toArray();
    }

    // 转换为List
    public static <T> List<T> toList(String text, Class<T> clazz) {
        return JSON.parseArray(text, clazz);
    }

    /**
     * 将javabean转化为序列化的json字符串
     *
     * @param keyvalue
     * @return
     */
    public static Object beanToJson(KeyValue keyvalue) {
        String textJson = JSON.toJSONString(keyvalue);
        Object objectJson = JSON.parse(textJson);
        return objectJson;
    }

    /**
     * 将string转化为序列化的json字符串
     *
     * @param text
     * @return
     */
    public static Object textToJson(String text) {
        Object objectJson = JSON.parse(text);
        return objectJson;
    }

    /**
     * json字符串转化为map
     *
     * @param s
     * @return
     */
    public static Map<?,?> stringToCollect(String s) {
        JSONObject m = JSONObject.parseObject(s);
        Map<String,Object> map= (Map)m;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if(!(entry.getValue() instanceof String)){
                map.put(entry.getKey(),entry.getValue() + "");
            }
            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

        }
        return map;
    }

    /**
     * 将map转化为string
     *
     * @param m
     * @return
     */
    public static String collectToString(Map<?,?> m) {
        String s = JSONObject.toJSONString(m);
        return s;
    }

    public static String toJsonStringWithoutNonString(Object object)
    {
        SerializeWriter sw = null;
        JSONSerializer jsonSerializer = null;
        try
        {
            PropertyFilter propertyFilter = new PropertyFilter()
            {
                @Override
                public boolean apply(Object o, String s, Object o1)
                {
                    if ("".equals(o1))
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
            };
            sw = new SerializeWriter();
            jsonSerializer = new JSONSerializer(sw);
            jsonSerializer.getPropertyFilters().add(propertyFilter);
            jsonSerializer.write(object);
            return sw.toString();
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            if (jsonSerializer != null)
            {
                jsonSerializer.close();
            }
        }

    }
}
