package cn.reghao.tnb.content.app.aop;

import cn.reghao.tnb.common.web.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import jakarta.servlet.http.HttpServletRequest;

/**
 * @author reghao
 * @date 2023-11-19 23:10:19
 */
@Slf4j
@Component
@Aspect
public class TimeConsumedAspect {
    ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("@annotation(cn.reghao.tnb.content.app.aop.TimeConsumed)")
    public void pointCut(){
    }

    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
    }

    @AfterReturning(returning = "ret", pointcut = "pointCut()")
    public void doAfterReturning(Object ret) {
        HttpServletRequest request = ServletUtil.getRequest();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        if (queryString != null) {
            uri += "?" + queryString;
        }

        log.info("处理请求 {} {} 耗时 {}ms", method, uri, System.currentTimeMillis() - startTime.get());
        //处理完请求后，返回内容
        //log.info("方法返回值:" + ret);
    }
}
