package com.greenorange.promotion.aop;

import com.greenorange.promotion.annotation.Timeout;
import com.greenorange.promotion.common.ErrorCode;
import com.greenorange.promotion.exception.BusinessException;
import com.greenorange.promotion.exception.ThrowUtils;
import lombok.NoArgsConstructor;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Aspect
@Component
public class TimeoutAspect {


    private final ExecutorService executorService;


    // 构造器注入线程池
    @Autowired
    public TimeoutAspect(ExecutorService executorService) {
        this.executorService = executorService;
    }

    @Around("@annotation(timeout)")
    public Object handleTimeout(ProceedingJoinPoint joinPoint, Timeout timeout) throws Throwable {
        long timeoutMillis = timeout.value();  // 获取超时时间

        // 创建一个线程池来执行任务
        Callable<Object> task = () -> {
            try {
                // 执行目标方法
                return joinPoint.proceed();
            } catch (Throwable e) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, e.getMessage());
            }
        };

        Future<Object> future = executorService.submit(task);  // 提交任务

        try {
            // 在规定时间内等待任务完成
            return future.get(timeoutMillis, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            // 超时后抛出自定义异常
            throw new BusinessException(ErrorCode.TIMEOUT_ERROR, "请求超时，超过最大允许时间 " + timeoutMillis + " 毫秒");
        }
    }
}
