package com.ag.log;

import org.apache.commons.beanutils.BeanUtils;
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 java.util.Arrays;
import java.util.Map;


/**
 * Description:
 * Author: shaofq
 * Version: 1.0
 * Create Date: 2020-03-09 17:01:20
 */
@Aspect
@Component
public class AOPConfig {

    //用法,业务方法类添加aop注解    @OperationLog(description = "12321")
    @Around(value = "@annotation(OperationLog)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint){
        Map<String,String> keyValues=null;
        String className = proceedingJoinPoint.getTarget().getClass().getName(); //切入方法所属类名
        String methodName = proceedingJoinPoint.getSignature().getName(); //切入的方法名
        Object[] params = proceedingJoinPoint.getArgs(); //目标方法传入的参数
        String param = "入参为：";
        System.out.println("【"+className+"】:"+methodName);
        if(params != null && params.length > 0){
            for(Object p : params){
                try {
                    keyValues = BeanUtils.describe(p);
                }catch (Exception e){
                    e.printStackTrace();
                }
                System.out.println("===="+p.toString());
                param += p + ",";
            }
            param = param.substring(0,param.lastIndexOf(","));
        }
        System.out.println("方法环绕begin...参数："+ Arrays.toString(proceedingJoinPoint.getArgs()));
        try {
            Object ret= proceedingJoinPoint.proceed();
            System.out.println("方法环绕end...结果："+ret);
            return ret;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }

    @Before(value = "@annotation(OperationLog)")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        System.out.println("方法前");
        //HttpServletRequest req= requestAttributes.getRequest();
       // System.out.println("uri："+req.getRequestURI());
       // System.out.println("执行方法前 : " + Arrays.toString(joinPoint.getArgs()));
    }

    @After(value = "@annotation(OperationLog)")
    public void after(JoinPoint joinPoint){
        System.out.println("执行方法后："+ Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(pointcut = "@annotation(OperationLog)",returning = "ret")
    public void doAfterReturning(Object ret){
        System.out.println("方法的返回值 : " + ret);
    }

    @AfterThrowing(pointcut = "@annotation(OperationLog)",throwing = "ex")
    public void AfterThrowing(JoinPoint joinPoint,Throwable ex){
        System.out.println("方法执行异常 : " + ex);
    }
}
