package cn.ysk.cashier.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * json工具类，所有JSON转换通用该JSON工具类，不许直接使用外部JSON转换，后期会封闭掉直接调用JSON转换。
 */
public final class FastJsonUtils {

    private static final List<SerializerFeature> listFeatures = new ArrayList<>();

    static {
        // 输出空置字段
        listFeatures.add(SerializerFeature.WriteMapNullValue);
        // list字段如果为null，输出为[]，而不是null
        listFeatures.add(SerializerFeature.WriteNullListAsEmpty);
        // 数值字段如果为null，输出为0，而不是null
        // SerializerFeature.WriteNullNumberAsZero,
        // Boolean字段如果为null，输出为false，而不是null
        listFeatures.add(SerializerFeature.WriteNullBooleanAsFalse);
        // 字符类型字段如果为null，输出为""，而不是null
        listFeatures.add(SerializerFeature.WriteNullStringAsEmpty);
        // 循环引用
        listFeatures.add(SerializerFeature.DisableCircularReferenceDetect);
    }

    /**
     * 转换对象为JSON字符串
     *
     * @param object 转换对象
     * @return 转换结果
     */
    public static String toJSONString(Object object){
        //不可序列化的类型直接打印其类名称
        if (object instanceof HttpServletRequest
                || object instanceof HttpServletResponse
                || object instanceof MultipartFile
                || object instanceof MultipartFile[]) {
            return "[" + object.getClass().getSimpleName() + "]";
        } else {
            return toJSONString(object, null, "yyyy-MM-dd HH:mm:ss");
        }
    }

    /**
     * JSON 转换出口
     *
     * @param o               转换对象
     * @param serializeConfig 转换配置
     * @param DateFormat      时间格式化
     * @return 转换结果
     */
    private static String toJSONString(Object o, SerializeConfig serializeConfig, String DateFormat) {
        SerializeConfig config;
        SerializerFeature[] features;
        if (serializeConfig != null) {
            config = serializeConfig;
        } else {
            config = new SerializeConfig();
        }
        if (StringUtils.isNotBlank(DateFormat)) {
            // 设置自定义时间
            JSON.DEFFAULT_DATE_FORMAT = DateFormat;
            features = new SerializerFeature[listFeatures.size() + 1];
            features = listFeatures.toArray(features);
            features[features.length - 1] = SerializerFeature.WriteDateUseDateFormat;
        } else {
            features = new SerializerFeature[listFeatures.size()];
            features = listFeatures.toArray(features);
        }
        return JSON.toJSONString(o, config, features);
    }
}