package com.artfess.rescue.open.aop;

import com.artfess.base.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;

/**
 * @Author: wsf
 * @Description: 自动注入当天开始结束时间切面
 * @DateTime: 2025/3/29 10:56
 **/
@Aspect
@Component
@Slf4j
public class AutoSetNowTimeAspect {

    @Around("execution(* com.artfess..*(..))") // 作用于所有 Controller 和 Service 方法
    public Object processAutoSetNowTime(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        LocalDate now = LocalDate.now();

        for (Object arg : args) {
            if (arg != null && arg.getClass().isAnnotationPresent(AutoSetNowTime.class)) {
                try {
                    // 1. 获取type和month字段值
                    String type = getFieldValue(arg, "type", String.class);
                    LocalDate month = getFieldValue(arg, "month", LocalDate.class);
                    LocalDate referenceDate;
                    // 确定参考日期（优先使用month字段的值）
                     referenceDate = (month != null) ? month : now;
                    // 确定参考日期（优先使用month字段的值）
                    if ((StringUtil.isNotEmpty(type)&&type.equals("day"))){
                        referenceDate=now;
                    }
                    // 2. 处理时间字段
                    Field[] fields = arg.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        if ("startTime".equals(field.getName()) || "endTime".equals(field.getName())) {
                            field.setAccessible(true);
                            if (field.get(arg) == null) {
                                LocalDateTime defaultValue = calculateDefaultValue(field.getName(), type, referenceDate);
                                field.set(arg, defaultValue);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("处理AutoSetNowTime时出错: {}", e.getMessage(), e);
                }
            }
        }
        return joinPoint.proceed(args);
    }

    // 辅助方法：获取字段值
    private <T> T getFieldValue(Object obj, String fieldName, Class<T> clazz) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return clazz.cast(field.get(obj));
        } catch (Exception e) {
            return null;
        }
    }

    // 辅助方法：计算默认值
    private LocalDateTime calculateDefaultValue(String fieldName, String type, LocalDate referenceDate) {
        if (StringUtil.isNotEmpty(type) && !type.equals("day")) {
            switch (type) {
                case "year":
                    int year = referenceDate.getYear();
                    return "startTime".equals(fieldName) ? LocalDate.of(year, 1, 1).atStartOfDay() : LocalDate.of(year, 12, 31).atTime(23, 59, 59);
                case "all":
                    return null;
                case "month":
                    YearMonth yearMonth = YearMonth.from(referenceDate);
                    return "startTime".equals(fieldName) ? yearMonth.atDay(1).atStartOfDay() : yearMonth.atEndOfMonth().atTime(23, 59, 59);  // 当月最后一天 23:59:59
            }
        } else {
            return "startTime".equals(fieldName) ? LocalDate.now().atStartOfDay() : LocalDate.now().atTime(23, 59, 59);
        }
        return null;
    }
}