package com.gxwebsoft.common.core.aspect;

import com.gxwebsoft.common.core.annotation.IgnoreTenant;
import com.gxwebsoft.common.core.context.TenantContext;
import lombok.extern.slf4j.Slf4j;
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.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 忽略租户隔离切面
 * 
 * 自动处理 @IgnoreTenant 注解标记的方法，临时禁用租户隔离
 * 
 * @author WebSoft
 * @since 2025-01-26
 */
@Slf4j
@Aspect
@Component
@Order(1) // 确保在其他切面之前执行
public class IgnoreTenantAspect {
    
    @Around("@annotation(com.gxwebsoft.common.core.annotation.IgnoreTenant)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        IgnoreTenant ignoreTenant = method.getAnnotation(IgnoreTenant.class);
        
        // 记录原始状态
        boolean originalIgnore = TenantContext.isIgnoreTenant();
        
        try {
            // 设置忽略租户隔离
            TenantContext.setIgnoreTenant(true);
            
            // 记录日志
            if (ignoreTenant.logAccess()) {
                String className = joinPoint.getTarget().getClass().getSimpleName();
                String methodName = method.getName();
                String reason = ignoreTenant.value();
                
                if (reason.isEmpty()) {
                    log.debug("执行跨租户操作: {}.{}", className, methodName);
                } else {
                    log.debug("执行跨租户操作: {}.{} - {}", className, methodName, reason);
                }
            }
            
            // 执行目标方法
            return joinPoint.proceed();
            
        } finally {
            // 恢复原始状态
            TenantContext.setIgnoreTenant(originalIgnore);
        }
    }
}
