package com.sqx.common.aspect;

import com.google.gson.Gson;
import com.sqx.common.utils.HttpContextUtils;
import com.sqx.common.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 javax.servlet.http.HttpServletRequest;

/**
 * 方法调用统一切面处理
 */
@Aspect
@Component
@Slf4j
public class AppApiMethodAspect {

    @Pointcut("execution(public * (com.sqx.modules.*.controller.*).*(..)) " +
            "&& " +
            "!execution(public * (com.sqx.modules.sys.controller.SysLoginController).*(..))")
    public void pkg() {
    }

    @Around("pkg()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        //避免回填
        Object[] args = pjp.getArgs();
        String params = new Gson().toJson(args);

        // 执行被拦截的方法
        Object result = pjp.proceed();

        //请求的参数
        String resultJson = new Gson().toJson(result);

        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        long end = System.currentTimeMillis();
        if(StringUtils.isNotBlank(resultJson) && !"null".equals(resultJson)){
            log.info("\n>>>>>> {} {}\n>>>>>> IP: {} \n>>>>>> execute time:{}ms \n>>>>>> Request: {}\n>>>>>> Response: {}",
                    request.getMethod(), request.getRequestURL(), IPUtils.getIpAddr(request),end-start,
                    params,
                    resultJson
            );
        }
        return result;
    }
}
