package com.cusc.nirvana.user.rnr.fp.common.config;

import com.alibaba.fastjson.JSON;
import com.cusc.nirvana.user.rnr.fp.common.FpIgnoreBase64ImgJsonSerializeFilter;
import com.cusc.nirvana.user.util.CuscStringUtils;
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;

/**
 * Description: mvc日志输出
 * <br />
 * CreateDate 2021-11-12 10:26
 *
 * @author yuyi
 **/
@Aspect
@Component
public class WebLogAspect {

    private final static Logger LOGGER = LoggerFactory.getLogger(WebLogAspect.class);

    /**
     * 以 controller 包下定义的所有请求为切入点
     */
    @Pointcut("execution(* com.cusc.nirvana.user.rnr.fp.controller.*.*(..))")
    public void webLog() {
    }

    /**
     * 环绕
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String requestId = CuscStringUtils.generateUuid();

        ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();

        String params =  "";
        //获取请求参数集合并进行遍历拼接
        if ("POST".equals(method)) {
            Object[] args = proceedingJoinPoint.getArgs();
            params = JSON.toJSONString(args, new FpIgnoreBase64ImgJsonSerializeFilter());
        } else if ("GET".equals(method)) {
            params = request.getQueryString();
        }

        LOGGER.info("requestId:{} , request url:{} , method:{} , params:{}", requestId, url, method, params);
        // result的值就是被拦截方法的返回值
        Object result = proceedingJoinPoint.proceed();
        LOGGER.info("requestId:{} , response url:{} , result:{} , cost:{} ms", requestId, url,
                JSON.toJSONString(result, new FpIgnoreBase64ImgJsonSerializeFilter()),
                System.currentTimeMillis() - startTime);
        return result;
    }
}
