package com.sqx.common.aspect;

import cn.hutool.core.thread.ThreadUtil;
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.sys.controller.SysLoginController).*(..)) " +
            "&& execution(public * (com.sqx.modules.*.controller..*).*(..)))")
    public void pkg() {
    }

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

        // 如果请求参数中包含HttpServletRequest，剔除HttpServletRequest
        for (int i = 0; i < args.length; i++) {
            if (args[i] instanceof HttpServletRequest) {
                args[i] = null;
            }
        }

        String params = new Gson().toJson(args);

        // 执行被拦截的方法
        Object result = pjp.proceed();
        long end = System.currentTimeMillis();
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String method = request.getMethod();
        String requestUrl = request.getRequestURL().toString();
        String requestIp = IPUtils.getIpAddr(request);
        long useTime = end - start;
        ThreadUtil.execAsync(() -> {
            //请求的参数
            String resultJson = new Gson().toJson(result);
            try {
                if (StringUtils.isNotBlank(resultJson) && !"null".equals(resultJson)) {
                    log.info("\n>>>>>> {} {}" +
                                    "\n>>>>>> IP: {} " +
                                    "\n>>>>>> execute time:{}ms " +
                                    "\n>>>>>> Request: {}" +
                                    "\n>>>>>> Response: {}",
                            method, requestUrl, requestIp, useTime,
                            params,
                            resultJson
                    );
                }
            } catch (Exception e) {
                log.error("Request 为空" + e.getMessage());
            }
        });
        return result;
    }
}
