package com.hs.admin.common.aspect;

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.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

@Aspect
@Component
@Order(2)
@Profile({"test","prod"})
public class RequestMappingAspect {
    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void getMappingAspect() {
    }

    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void postMappingAspect() {
    }

    @Around("getMappingAspect()")
    public Object get(ProceedingJoinPoint joinPoint) throws Throwable {
        return request(joinPoint);
    }

    @Around("postMappingAspect()")
    public Object post(ProceedingJoinPoint joinPoint) throws Throwable {
        return request(joinPoint);
    }

    private Object request(ProceedingJoinPoint joinPoint) throws Throwable {
        Date beginDate = new Date();
        HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        Logger logger = org.slf4j.LoggerFactory.getLogger(joinPoint.getTarget().getClass());
        Object result = joinPoint.proceed();
        String uri = request.getRequestURI();
        Object[] params = joinPoint.getArgs();
        List<Object> paramsList = Arrays.asList(params);
        Date endDate = new Date();
        logger.debug("执行时间：" +
                (endDate.getTime() - beginDate.getTime())
                + ",URL:" + uri + "入参参数：" + paramsList + "返回结果：" + result);
        return result;
    }
}
