package com.ruoyi.framework.aspectj;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

@Aspect
@Component
public class SqlLogAspect {

    @Around("execution(* com.zkqy.datamodeling.mapper.*.*(..))") // 匹配所有Mapper接口的方法
    public Object logSql(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取目标对象、方法和参数
        Object target = joinPoint.getTarget();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> returnType = signature.getReturnType();

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 判断结果集类型
        if (result instanceof List) {
            List<?> list = (List<?>) result;
            for (Object item : list) {
                // 遍历结果集中的每一行数据，打印相关信息
                Field[] fields = item.getClass().getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    System.out.println(field.getName() + ": " + field.get(item));
                }
            }
        } else {
            return Class.forName(returnType.toString().split("class ")[1]).newInstance();
        }

        return result;
    }
}
