package com.huimv.employment.service.common.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * 兼容日期/日期时间字符串：yyyy-MM-dd、yyyy-MM-dd HH:mm、yyyy-MM-dd HH:mm:ss、ISO（含 T）。
 */
public class FlexibleLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    private static final DateTimeFormatter DT_SEC = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DT_MIN = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String text = p.getValueAsString();
        if (!StringUtils.hasText(text)) {
            return null;
        }
        String value = text.trim().replace('T', ' ');
        try {
            if (value.length() == 10) {
                return LocalDate.parse(value).atStartOfDay();
            }
            if (value.length() == 16) {
                return LocalDateTime.parse(value, DT_MIN);
            }
            if (value.length() >= 19) {
                return LocalDateTime.parse(value.substring(0, 19), DT_SEC);
            }
            return LocalDateTime.parse(value, DT_SEC);
        } catch (DateTimeParseException ex) {
            throw ctxt.weirdStringException(text, LocalDateTime.class,
                    "期望 yyyy-MM-dd 或 yyyy-MM-dd HH:mm[:ss]");
        }
    }
}
