package com.ruoyi.framework.aspectj.scop;


import com.ruoyi.framework.annotation.Dynamic;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author : qing
 * @date : 2024/4/21
 * @desc : @Dynamic 注解的 AOP 实现
 */
@Aspect
@Component
public class DynamicAspect {

    @Pointcut("@annotation(com.ruoyi.framework.annotation.Dynamic)")
    public void dynamicPointcut() {
    }
    
    // @Before("dynamicPointcut()")
    // public void beforeDynamic() {
    //     System.out.println("Before dynamic method execution");
    // }
    

    @Around("dynamicPointcut()")
    public Object handleDynamic(ProceedingJoinPoint joinPoint) throws Throwable {
        // 在方法执行前的操作
        System.out.println("Before method execution");

        // Method method = getCurrentMethod(joinPoint);
        // MethodClassKey methodClassKey = new MethodClassKey(method, joinPoint.getTarget().getClass());
        
        // 获取方法上的注解
        Dynamic dynamic = getMethodAnnotation(joinPoint);

        DataPermissionContextHolder.add(dynamic);

        Object result;
        // 执行方法
        try {
            result = joinPoint.proceed();
        } finally {
            DataPermissionContextHolder.clear();
        }

        // 在方法执行后的操作
        System.out.println("After method execution");

        return result;
    }

    private Dynamic getMethodAnnotation(ProceedingJoinPoint joinPoint) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // Class<?> targetClass = joinPoint.getTarget().getClass().getInterfaces()[0];
        // Method targetMethod = ReflectionUtils.findMethod(targetClass, method.getName(), method.getParameterTypes());
        // if (targetMethod == null) {
        //     throw new IllegalArgumentException("Method not found");
        // }
        // return targetMethod.getAnnotation(Dynamic.class);
        return method.getAnnotation(Dynamic.class);
    }
}