package com.gyee.wisdom.report.config;

import com.alibaba.fastjson.serializer.NameFilter;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.TimeZone;

/**
 * @description:
 * @auther: Wanghs
 * @date: 2022-04-06
 */
@Configuration
public class MyJsonConfig implements WebMvcConfigurer {
    //springboot 默认通过jackson来转化json,@JSONField(....)是fastjson的注解,因此要添加如下配置
    //Long类型在前端js中会丢失精度

    public FastJsonHttpMessageConverter fastJsonHttpMessageConverters() {
        TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        NameFilter nameFilter = (object, name, value) -> name;
        SerializeConfig serializeConfig = fastJsonConfig.getSerializeConfig();
        // serializeConfig .addFilter(SwaggerWelcomeWebMvc.class, nameFilter);
        // serializeConfig.put(String.class,MyStringSerializer.instance);
        fastJsonConfig.setSerializeConfig(serializeConfig);

        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");    //自定义时间格式
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.DisableCircularReferenceDetect
                ,SerializerFeature.WriteMapNullValue
                ,SerializerFeature.WriteDateUseDateFormat
        );  //关闭循环引用,正常转换null值，格式化

        fastConverter.setFastJsonConfig(fastJsonConfig);
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        // HttpMessageConverter<?> converter = fastConverter;
        return fastConverter;
    }
    public HttpMessageConverter<String> stringConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(
                Charset.forName("UTF-8"));
        return converter;
    }
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {

        // converters.clear();
         converters.add(stringConverter());
//        List<HttpMessageConverter<?>> collect = converters.stream().filter(s ->s instanceof StringHttpMessageConverter).collect(Collectors.toList());
//        converters.removeAll(collect);
        converters.add( fastJsonHttpMessageConverters());

    }

}
