package com.ytpm.handle;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * 自定义Date序列化器（输出东八区yyyy-MM-dd HH:mm:ss格式）
 * @author lih
 * @date 2025-10-15 10:21
 */
public class CustomDateSerializer extends StdSerializer<Date> {

    private static String defaultTimeZone;

    public CustomDateSerializer(String timeZone) {
        super(Date.class);
        defaultTimeZone = timeZone;
    }

    // 线程安全的SimpleDateFormat（避免多线程问题）
    private static final ThreadLocal<SimpleDateFormat> SDF_THREAD_LOCAL = ThreadLocal.withInitial(() -> {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone(defaultTimeZone));
        return sdf;
    });


    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (value != null) {
            // 使用线程安全的DateFormat格式化
            gen.writeString(SDF_THREAD_LOCAL.get().format(value));
        }
    }
}
