package top.imwork.commons.core.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.imwork.commons.core.constants.DateConstants;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

/**
 * Copyright (C), 2015-2021
 * FileName: JacksonConfig
 * Author(作者姓名):   jiangxiaowei
 * CreateDate(创建时间):     2021/8/2 15:35
 * UpdateDate(修改时间):     2021/8/2 15:35
 * Description(功能描述):    JacksonConfig
 * Since(版本号)  1.0.0
 * History:
 */
@Configuration
public class JacksonConfig {
    /**
     * ObjectMapper配置
     * @return objectMapper
     */
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);
        objectMapper.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        objectMapper.setDateFormat(new SimpleDateFormat(DateConstants.DATE_TIME_PATTERN));
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        return  objectMapper;
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> {
            // Long 会自动转换成 String
            builder.serializerByType(Long.class, ToStringSerializer.instance);
        };
    }
}
