package com.clx.performance.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.NumberSerializers;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;

@Configuration
public class JsonSerializerConfig {

    final static Long jsTopLimit = 999999999999999L;

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder){
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();

        //全局配置序列化返回json处理
        SimpleModule simpleModule = new SimpleModule();
        //JSON Long ==> String
        simpleModule.addSerializer(Long.class, MslNoToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        return objectMapper;
    }

    static class MslNoToStringSerializer extends JsonSerializer<Object> {

        private static final MslNoToStringSerializer instance = new MslNoToStringSerializer();

        private final ToStringSerializer stringSerializer = ToStringSerializer.instance;

        private final NumberSerializers.LongSerializer longSerializer =  new NumberSerializers.LongSerializer(Long.class);

        @Override
        public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            Long no = (Long) o;
            if (no < jsTopLimit){
                longSerializer.serialize(o, jsonGenerator, serializerProvider);
            }else {
                stringSerializer.serialize(o, jsonGenerator, serializerProvider);
            }
        }
    }
}
