package com.ematou.wxservice.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author lhm
 * @version 1.0
 * 2021-04-30 16:30
 */
@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    // TODO
    @Pointcut("execution(* com.ematou.wxservice.*.*Service.*(..)) ||" +
              "execution(* com.ematou.wxservice.*.*RestTemplate.*(..)) || " +
              "execution(* com.ematou.wxservice.*.*Handler.*(..))")
    public void targetMethod() {}

    @Around("targetMethod()")
    public Object around(ProceedingJoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature ms = (MethodSignature) signature;
        String targetMethodName = ms.getMethod().getName();
        String className = joinPoint.getTarget().getClass().getName();

        ObjectMapper objectMapper = new ObjectMapper();

        Object proceed = null;
        try {
            logger.info("----------------方法: " + className + "." + targetMethodName + "的参数为: " + objectMapper.writeValueAsString(joinPoint.getArgs()) + "----------------");
            long start = System.currentTimeMillis();
            proceed = joinPoint.proceed();
            long end = System.currentTimeMillis();
            logger.info("----------------方法: " + className + "." + targetMethodName + "执行的返回值为: " + proceed + "----------------");
            logger.info("----------------方法: " + className + "." + targetMethodName + "执行的时间为: " + (end-start) + "毫秒----------------");
        } catch (Throwable throwable) {
            logger.error("----------------方法: " + className + "." + targetMethodName + "执行出现异常，错误信息为：" + throwable + "----------------");
        }
        return proceed;
    }

}
