package com.qmth.boot.api.config;

import com.qmth.boot.api.utils.HttpTraceUtil;
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.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class ApiControllerAspect {

    private HttpTraceUtil httpTraceUtil;

    /**
     * 构造函数
     */
    public ApiControllerAspect(ApiProperties apiProperties) {
        this.httpTraceUtil = new HttpTraceUtil(apiProperties);
    }

    /**
     * 切面注解
     *
     * @author
     */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) "
            + "|| @annotation(org.springframework.web.bind.annotation.GetMapping) "
            + "|| @annotation(org.springframework.web.bind.annotation.PostMapping)"
            + "|| @annotation(org.springframework.web.bind.annotation.DeleteMapping)"
            + "|| @annotation(org.springframework.web.bind.annotation.PutMapping)")
    public void handlerMethods() {

    }

    /**
     * 接口处理
     *
     * @param joinPoint
     * @return
     * @throws Throwable
     * @author
     */
    @Around("handlerMethods()")
    public Object doAroundWebRequests(ProceedingJoinPoint joinPoint) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
                .getRequest();
        MethodSignature method = (MethodSignature) joinPoint.getSignature();
        httpTraceUtil.request(request, method, joinPoint.getArgs());
        Object result = joinPoint.proceed();
        return httpTraceUtil.response(result);
    }
}
