package com.miaxis.framework.aspectj;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Slf4j
public class LogFileAspect {


    @Pointcut("execution(* com.miaxis.*.controller..*(..))")
//@Pointcut("@annotation(com.miaxis.common.annotation.Log)")
    public void logPoint() {

    }

    @Before("logPoint()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();


        // 记录下请求内容
        log.info("HTTP METHOD : " + request.getMethod());
        log.info("请求地址 : " + request.getRequestURL().toString());
        log.info("IP : " + request.getRemoteAddr());
        //log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
       // log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
        log.info("ARGS_JSON : " + JSONUtil.toJsonStr(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "ret", pointcut = "logPoint()")// returning的值和doAfterReturning的参数名一致
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        //log.info("返回值 : " + JSON.toJSONString(ret));
    }

    @Around("logPoint()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object ob = pjp.proceed();// ob 为方法的返回值
        log.info("耗时 : " + (System.currentTimeMillis() - startTime) + "ms");
        return ob;
    }

}

