package easydo.technology.config;

import com.google.gson.Gson;

import easydo.technology.annotation.WebLog;

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

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @date 2023/10/6
 * @time 下午9:19
 * @discription
 **/
@Aspect
@Component
@Profile({ "dev", "test" })
public class WebLogAspect {

    private final static Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
    /** 换行符 */
    private static final String LINE_SEPARATOR = System.lineSeparator();

    /** 以自定义 @WebLog 注解为切点 */
    @Pointcut("@annotation(easydo.technology.annotation.WebLog)")
    public void webLog() {
    }

    /**
     * 在切点之前织入
     * 
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印请求 url
        logger.info("URL======>{},Class Method======>{}.{},Request Args======>{},Ip======>{}", request.getRequestURL().toString(),
                joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(),
                new Gson().toJson(joinPoint.getArgs()),request.getRemoteAddr());
       
    }

    /**
     * 在切点之后织入
     * 
     * @throws Throwable
     */
    // @After("webLog()")
    // public void doAfter() throws Throwable {
    //      // 开始打印请求日志
    //      ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    //      HttpServletRequest request = attributes.getRequest();
    //      Object result = proceedingJoinPoint.proceed();
    //      logger.info("URL======>{},Class Method======>{}.{},Request Args======>{},Response Args======>{}", request.getRequestURL().toString(),
    //      joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(),
    //      new Gson().toJson(joinPoint.getArgs()),new Gson().toJson(result));
    // }

    /**
     * 环绕
     * 
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    // @Around("webLog()")
    // public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    //     long startTime = System.currentTimeMillis();
    //     Object result = proceedingJoinPoint.proceed();
    //     // 打印出参
    //     logger.info("Response Args  : {}", new Gson().toJson(result));
    //     // 执行耗时
    //     logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        // return null;
    // }

    /**
     * 获取切面注解的描述
     *
     * @param joinPoint 切点
     * @return 描述信息
     * @throws Exception
     */
    public String getAspectLogDescription(JoinPoint joinPoint)
            throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder("");
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description.append(method.getAnnotation(WebLog.class).description());
                    break;
                }
            }
        }
        return description.toString();
    }

}
