package com.prolog.cs.base.gsp.aspect;

import com.github.pagehelper.util.StringUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 日志和加密
 *
 */
@Aspect
@Component
public class AceAspect {


    private static final Logger logger = LogManager.getLogger("AceAspect");

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

    @Pointcut("execution(public * com.prolog.cs.base.gsp.controller..*.*(..)))")
    public void webLog(){}

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

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint point) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object object= point.proceed();
        if(request.getRequestURL()==null || StringUtil.isEmpty(request.getRequestURL().toString())){//不规范写法，导致url为空
            return object;
        }
        String url = request.getRequestURL().toString();
        //logger.info(" URL:" + request.getRequestURL().toString()+" 入参:" + Arrays.toString(point.getArgs())+" 返回:" + JSON.toJSONString(object));
        return object;
    }

//    @AfterReturning(returning = "ret", pointcut = "webLog()")
//    public void doAfterReturning(Object ret) throws Throwable {
//        // 处理完请求，返回内容
//        logger.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get())+" RESPONSE : " + ret);
//    }


}
