package com.fs.core.aspectj;

import com.fs.common.annotation.QuartzRunnable;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class QuartzRunnableAspect {

    private static final Logger logger = LoggerFactory.getLogger(QuartzRunnableAspect.class);

    // 定义切点：匹配所有带有 @QuartzRunnable 注解的方法
    @Pointcut("@annotation(com.fs.common.annotation.QuartzRunnable)")
    public void quartzRunnablePointcut() {
    }

    // 环绕通知：在方法执行前后进行处理
    @Around("quartzRunnablePointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        // 获取 @QuartzRunnable 注解
        QuartzRunnable quartzRunnable = method.getAnnotation(QuartzRunnable.class);

        // 获取定时任务描述（注解的 desc 属性）
        String taskDescription = quartzRunnable.name();

        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 打印定时任务开始信息
        logger.info("定时任务 [{}] 开始执行...", taskDescription);

        // 执行目标方法
        Object result;
        try {
            result = joinPoint.proceed();
        }catch (Exception e){
            logger.error("定时任务 [{}] 执行失败，异常信息：{}", taskDescription, e.getMessage(), e);
            throw e;
        }

        // 记录结束时间
        long endTime = System.currentTimeMillis();

        // 计算并打印耗时
        long duration = endTime - startTime;
        logger.info("定时任务 [{}] 执行完毕，耗时：{} ms", taskDescription, duration);

        return result;
    }
}
