package com.crm.rely.backend.configuration;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

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

/**
 * 返回的时间格式格式化
 *
 * @program: user-custom
 * @description: account json converter
 * @author: houn
 * @create: 2019-06-05 17:29
 */
public class CustomJsonHttpMessageConverter extends FastJsonHttpMessageConverter {

    private final static String DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private final static String DEFFAULT_SQL_DATE_FORMAT = "yyyy-MM-dd";
    private final static String DEFFAULT_SQL_TIME_FORMAT = "HH:mm:ss";
    private final static String DEFFAULT_SQL_TIMESTAMP_FORMAT = "yyyy-MM-dd HH:mm:ss";
    //字符编码
    private static final String CHARSET = "UTF-8";

    @Override
    protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        OutputStream out = outputMessage.getBody();
        String text = JSON.toJSONString(obj, getSerializeConfig(), super.getFastJsonConfig().getSerializerFeatures());
        byte[] bytes = text.getBytes(CHARSET);
        out.write(bytes);
    }

    /**
     * @return
     */
    private SerializeConfig getSerializeConfig() {
        SerializeConfig config = new SerializeConfig();
        config.put(java.util.Date.class, new SimpleDateFormatSerializer(DEFFAULT_DATE_FORMAT));
        config.put(java.sql.Date.class, new SimpleDateFormatSerializer(DEFFAULT_SQL_DATE_FORMAT));
        config.put(java.sql.Timestamp.class, new SimpleDateFormatSerializer(DEFFAULT_SQL_TIMESTAMP_FORMAT));
        config.put(java.sql.Time.class, new SimpleDateFormatSerializer(DEFFAULT_SQL_TIME_FORMAT));
        config.put(BigDecimal.class, new BigDecimalSerializer());
        return config;
    }
}
