package com.vctgo.common.mybatisplus.aop;

import com.vctgo.common.security.utils.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Objects;

@Aspect
@Component
public class TemporaryIgnoreTablesAop {

    public static final String POINTCUT_SIGN = "@annotation(com.vctgo.common.mybatisplus.aop.TemporaryIgnoreTables)";

    @Pointcut(POINTCUT_SIGN)
    public void temporaryIgnoreTables() {
    }

    @Before("temporaryIgnoreTables()")
    public void doBefore(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        TemporaryIgnoreTables annotation = signature.getMethod().getAnnotation(TemporaryIgnoreTables.class);
        if (annotation.temporaryIgnoreTables().length > 0) {
            String[] values = annotation.temporaryIgnoreTables();
            SecurityUtils.setTemporaryIgnoreTables(Arrays.asList(values));
        }
    }

    @AfterReturning("temporaryIgnoreTables()")
    public void doAfterReturning(JoinPoint joinPoint) {
        if (Objects.nonNull(SecurityUtils.getTemporaryIgnoreTables())) {
            SecurityUtils.removeTemporaryIgnoreTables();
        }
    }

    @AfterThrowing("temporaryIgnoreTables()")
    public void doAfterThrowing(JoinPoint joinPoint) {
        if (Objects.nonNull(SecurityUtils.getTemporaryIgnoreTables())) {
            SecurityUtils.removeTemporaryIgnoreTables();
        }
    }
}
