package com.sqx.common.aspect;

import com.google.gson.Gson;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.HttpContextUtils;
import com.sqx.common.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

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

/**
 * 方法调用统一切面处理
 */
@Aspect
@Component
@Slf4j
public class AppApiMethodAspect {
    @Pointcut("execution(public * (" +
            "com.sqx.modules.*.controller.* " +
            ").*(..)) && " +
            "!execution(public * (" +
            "com.sqx.modules.*.controller.SysLoginController " +
            ").*(..))")
    public void pkg() {
    }

    @Around("pkg()")
//    @SuppressWarnings("unchecked")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        // 执行被拦截的方法
        Object result = pjp.proceed();
        //请求的参数
        Object[] args = pjp.getArgs();
        String params = new Gson().toJson(args);
        String resultJson = new Gson().toJson(result);
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        long end = System.currentTimeMillis();

        log.info("\n>>>>>> {} {}\n>>>>>> IP: {} \n>>>>>> execute time:{}\n>>>>>> Request: {}\n>>>>>> Response: {}",
                request.getMethod(), request.getRequestURL(), IPUtils.getIpAddr(request),end-start,
                params,
                resultJson
        );
        return result;
    }
}
