package com.xingxi.api.configuration;

import com.xingxi.common.utils.ServletUtils;
import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Map;

/**
 * 操作日志记录处理
 * Around -> Before -> After -> AfterReturning -> AfterThrowing
 *
 * @author xingxi
 */
@Aspect
@Component
@Profile({"env", "local", "druid", "ita"})
@Order(10)
public class ConsoleLogAspect {
    private static final Logger log = LoggerFactory.getLogger(ConsoleLogAspect.class);
    /**
     * 换行符
     */
    private static final String LINE_SEPARATOR = System.lineSeparator();

    // 配置织入点
    @Pointcut("execution(* com.xingxi.api.controller.*Controller.*(..))")
    public void logPointCut() {
    }

    /**
     * 编制切入点
     *
     * @param joinPoint 切入点
     * @throws Throwable 可抛出的异常
     */
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String requestId = (String) request.getAttribute("X-REQUEST-ID");
        // 获取 @WebLog 注解的描述信息
        //String methodDescription = getAspectLogDescription(joinPoint);

        // 打印请求相关参数
        log.info("********************************************** ConsoleLogAspect Request:Start **********************************************");
        // 打印请求 url
        log.info("URL            : {}", request.getRequestURL().toString());
        // 打印描述信息
        //log.info("Description    : {}", methodDescription);
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        log.info("IP             : {}", request.getRemoteAddr());
        // 打印请求入参
        Map<String, String[]> map = ServletUtils.getRequest().getParameterMap();
        String params = JSONObject.toJSONString(map);
        log.info("Request Args   : {}", params);
        log.info("********************************************** ConsoleLogAspect Request:End **********************************************");
    }

    /**
     * 在切点之后织入
     *
     * @throws Throwable 可抛出的异常
     */
    @After("logPointCut()")
    public void doAfter() throws Throwable {
        // 接口结束后换行，方便分割查看
        //log.info("=========================================== ConsoleLogAspect ===========================================" + LINE_SEPARATOR);
    }

    /**
     * 环绕
     *
     * @param proceedingJoinPoint 切入点
     * @return
     * @throws Throwable 可抛出的异常
     */
    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        log.info("********************************************** ConsoleLogAspect Response:Start **********************************************");
        // 打印出参
        log.info("Response Args  : {}", JSONObject.toJSONString(result));
        // 执行耗时
        log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        log.info("********************************************** ConsoleLogAspect Response:End **********************************************");
        return result;
    }
}
