package com.test.musichouduan.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

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

public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

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

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String str = p.getText().trim();
        if (str.isEmpty()) {
            return null;
        }

        try {
            // 尝试解析 "yyyy-MM-dd HH:mm:ss" 格式
            return LocalDateTime.parse(str, FORMATTER_DATETIME);
        } catch (DateTimeParseException e) {
            // 如果失败，尝试解析 "yyyy-MM-dd" 格式
            try {
                LocalDate date = LocalDate.parse(str, FORMATTER_DATE);
                return date.atStartOfDay();
            } catch (DateTimeParseException e2) {
                throw new IOException(e2);
            }
        }
    }
}