package com.vote.system.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @CreateTime: 2024/8/24 下午7:12
 * @Description:
 * @Email: f2965573933@163.com
 * @Author: FanJiaBao
 */
@Aspect
@Component
public class LoggingAspect {
    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
    private static final ObjectMapper objectMapper = new ObjectMapper();


    @Before("execution(* com.vote.system.controller..*(..))")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("================================Start=================================");
        logger.info("进入方法: " + joinPoint.getSignature().getName());
        logger.info("类名: " + joinPoint.getSignature().getDeclaringTypeName());
        try {
            String argsJson = objectMapper.writeValueAsString(joinPoint.getArgs());
            logger.info("参数: " + argsJson);
        } catch (JsonProcessingException e) {
            logger.error("参数序列化为JSON失败", e);
        }
        logger.info("目标类: " + joinPoint.getTarget().getClass().getName());
    }

    @AfterReturning(pointcut = "execution(* com.vote.system.controller..*(..))", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        try {
            String resultJson = objectMapper.writeValueAsString(result);
            logger.info("方法返回值: " + resultJson);
        } catch (JsonProcessingException e) {
            logger.error("返回值序列化为JSON失败", e);
        }
        System.out.println("================================end=================================");
    }

    @AfterThrowing(pointcut = "execution(* com.vote.system.controller..*(..))", throwing = "error")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
        System.out.println("================================异常=================================");
        logger.error("方法 " + joinPoint.getSignature().getName() + "() 抛出异常");
        logger.error("异常原因: " + error.getCause());
        System.out.println("================================end=================================");
    }
}
