package com.seer.teach.common.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

@Configuration
public class JacksonConfig {

    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jacksonCustomizer() {
        return builder -> {
            // 设置日期时间格式
            builder.simpleDateFormat(DATE_TIME_FORMAT);

            // 设置时区
            builder.timeZone(TimeZone.getTimeZone("Asia/Shanghai"));

            // 配置 Java 8 时间类型的序列化和反序列化
            builder.serializers(
                    new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)),
                    new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT))
            );

            builder.deserializers(
                    new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)),
                    new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT))
            );

            // 其他配置
            builder.featuresToEnable(
                    SerializationFeature.INDENT_OUTPUT,  // 美化输出
                    SerializationFeature.WRITE_DATES_AS_TIMESTAMPS  // 禁用时间戳
            );

            builder.featuresToDisable(
                    SerializationFeature.FAIL_ON_EMPTY_BEANS
            );

            // 设置是否包含 null 值
            builder.serializationInclusion(JsonInclude.Include.ALWAYS);
        };
    }
}