package com.rj.common;

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.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 自定义 LocalDateTime 反序列化器
 * 支持多种时间格式，统一转换为应用配置时区的 LocalDateTime
 * 支持格式：
 * - 2025-11-29T18:13:02.1670603
 * - 2025-11-29T18:13:02.1670603+08:00
 * - 2025-11-29T18:13:02Z
 * - 2025-11-29 18:13:02
 */
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String timeStr = p.getValueAsString();
        if (timeStr == null || timeStr.trim().isEmpty()) {
            return null;
        }
        
        try {
            // 检测是否包含时区信息：以Z结尾，或包含时区偏移格式（+HH:MM 或 -HH:MM）
            boolean hasTimezone = timeStr.endsWith("Z") || 
                                 timeStr.matches(".*[+-]\\d{2}:\\d{2}(?:\\d{2})?$");
            
            if (hasTimezone) {
                // 处理ISO 8601格式，包含时区信息
                ZonedDateTime zonedDateTime;
                if (timeStr.endsWith("Z")) {
                    // UTC时间，转换为应用配置的时区
                    zonedDateTime = ZonedDateTime.parse(timeStr.replace("Z", "+00:00")).withZoneSameInstant(TimeZoneUtils.getZoneId());
                } else {
                    // 带时区偏移的时间，转换为应用配置的时区
                    zonedDateTime = ZonedDateTime.parse(timeStr).withZoneSameInstant(TimeZoneUtils.getZoneId());
                }
                return zonedDateTime.toLocalDateTime();
            } else {
                // 没有时区信息，假设是应用配置时区的时间
                String cleanTimeStr = timeStr;
                if (cleanTimeStr.contains("T")) {
                    cleanTimeStr = cleanTimeStr.replace("T", " ");
                }
                if (cleanTimeStr.contains(".")) {
                    cleanTimeStr = cleanTimeStr.substring(0, cleanTimeStr.indexOf("."));
                }
                if (cleanTimeStr.length() > 19) {
                    cleanTimeStr = cleanTimeStr.substring(0, 19);
                }
                return LocalDateTime.parse(cleanTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        } catch (Exception e) {
            throw new IOException("解析时间字符串失败: " + timeStr, e);
        }
    }
}

