package com.iformall.interceptor;

import com.iformall.utils.IPUtil;
import lombok.Data;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class WebLogAspect {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Data
    private class MethodInfo {
        Long startTime;
        String url;
        String ip;
        String method;
        String classMethod;
    }

    ThreadLocal<MethodInfo> startInfo = new ThreadLocal<>();


    @Pointcut("execution(public * com.iformall.controller..*.*(..))")
    public void webLog() {}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        logger.debug("aspect start");
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        MethodInfo info = new MethodInfo();
        info.setUrl(request.getRequestURL().toString());
        info.setStartTime(System.currentTimeMillis());
        info.setIp(IPUtil.getIpAddr(request));
        info.setMethod(request.getMethod());
        info.setClassMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        startInfo.set(info);
        logger.debug("aspect start ...");
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        logger.debug("aspect after");
        // 处理完请求，返回内容
        MethodInfo info = startInfo.get();
        StringBuilder sb = new StringBuilder();
        sb.append("URL: ").append(info.getUrl())
                .append(", METHOD: ").append(info.getMethod())
                .append(", DO: ").append(info.getClassMethod())
                .append(", IP: ").append(info.getIp())
                .append(", SPEND TIME: ").append(System.currentTimeMillis() -info.getStartTime()).append("ms");
        logger.info(sb.toString());
        logger.debug("aspect after ..");
    }


}
