package com.fs.framework.aspectj;

import lombok.extern.slf4j.Slf4j;
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.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

/**
 * 定时任务执行时间切面
 * 记录所有定时任务的执行时间和状态
 *
 * @author zhangqin
 * @date 2025-12-15
 */
@Slf4j
@Aspect
@Component
public class ScheduledTaskAspect {

    @Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled) && execution(* com.fs.app.task..*(..))")
    public void scheduledTaskPointcut() {
    }

    @Around("scheduledTaskPointcut()")
    public Object aroundScheduledTask(ProceedingJoinPoint joinPoint) throws Throwable {
        String taskName = getTaskName(joinPoint);
        StopWatch stopWatch = new StopWatch(taskName);
        stopWatch.start();

        try {
            Object result = joinPoint.proceed();
            stopWatch.stop();
            long executionTime = stopWatch.getTotalTimeMillis();
            log.info("任务执行耗时: {} {}", taskName, executionTime);
            return result;
        } catch (Exception e) {
            stopWatch.stop();
            long executionTime = stopWatch.getTotalTimeMillis();
            log.error("==================== 定时任务执行失败 ====================");
            log.error("任务名称: [{}]", taskName);
            log.error("执行耗时: [{}ms]", executionTime);
            log.error("执行状态: [失败]");
            log.error("错误信息: [{}]", e.getMessage(), e);
            throw e;
        }
    }

    /**
     * 获取任务名称
     */
    private String getTaskName(ProceedingJoinPoint joinPoint) {
        return joinPoint.getSignature().getName();
    }
}

