package com.dashitech.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 路径拦截器
 */
@Aspect
@Order(2)
@Component
public class ApiWeblogFilterConfig {
    private static Log log = LogFactory.getLog(ApiWeblogFilterConfig.class);

    ThreadLocal<Long> startTime = new ThreadLocal<Long>();

    @Pointcut("execution(public * com.dashitech.api..*.*(..))")
    public void webLog() {
        log.info("show()");
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        log.info(Thread.currentThread().getName() + "   ApiLog-URL : " + request.getRequestURL().toString() + "   IP : " + request.getRemoteAddr());
//        log.info(Thread.currentThread().getName() + "   ApiLog-ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        log.info(Thread.currentThread().getName() + "   ApiLog-AVG/MS : " + (System.currentTimeMillis() - startTime.get()) + "/ms ");
    }
}