package com.njcn.common.utils.serializer;

import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;


/**
 * @author hongawen
 * @version 1.0.0
 * @date 2023年04月25日 16:33
 */
@Component
public class InstantDateSerializer extends StdSerializer<Instant> {

    private static final long serialVersionUID = 1L;

    private static DateTimeFormatter format = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);

    public InstantDateSerializer() {
        this(null);
    }

    public InstantDateSerializer(Class<Instant> t) {
        super(t);
    }

    /***
     * 转义为 yyyy-MM-dd HH:mm:ss
     * @author hongawen
     */
    @Override
    public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider provider)
            throws IOException {
        if (instant == null) {
            return;
        }
        String jsonValue = format.format(instant.atZone(ZoneId.of("+00:00")));
        jsonGenerator.writeString(jsonValue);
    }
}