package net.educoder.ecsonar.config;

import com.alibaba.fastjson.JSONObject;
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.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.Enumeration;

/**
 * @author youys
 * @data 2019/8/13
 * @description 请求日志打印
 */
@Aspect
@Component
public class RequestAop {

    private Logger log = LoggerFactory.getLogger(RequestAop.class);
    /**
     * 声明一个切点，controller包下和子包下的所有类所有方法
     */
    @Pointcut("execution(* net.educoder.ecsonar.controller.*.*(..))")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object pintLog(ProceedingJoinPoint pjp) throws Throwable {
        Long startTime = System.currentTimeMillis();

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String requestUrl = request.getRequestURL().toString();

        // 打印请求内容
        log.info("|===============请求内容 start ==============================|");
        log.info("|请求地址:" + requestUrl);
        log.info("|请求方式:" + request.getMethod());
        log.info("|请求类方法:" + pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName());

        //获取所有参数
        Enumeration<String> enu = request.getParameterNames();
        StringBuilder params = new StringBuilder("【");
        while (enu.hasMoreElements()) {
            String paraName = enu.nextElement();
            params.append(paraName).append("=").append(request.getParameter(paraName)).append(";");
        }
        params.append("】");
        log.info("|请求方法参数:" + params.toString());

        Enumeration<String> headersEnu = request.getHeaderNames();
        StringBuilder headersParams = new StringBuilder("【");
        while (headersEnu.hasMoreElements()) {
            String headerName = headersEnu.nextElement();
            headersParams.append(headerName).append("=").append(request.getHeader(headerName)).append(";");
        }
        headersParams.append("】");

        log.info("|请求Header信息:{}", headersParams.toString());
        log.info("|===============请求内容 end ================================|");

        Object result = pjp.proceed();
        long endTime = System.currentTimeMillis();

        log.info("调用方法: {},返回结果response==>>{}", requestUrl, JSONObject.toJSONString(result));
        log.info("调用方法: {},请求耗时==>> {} ms", requestUrl, endTime - startTime);
        return result;
    }
}