package cn.gov.customs.demo.government.mock;

import cn.gov.customs.cacp.sdks.core.user.annotation.LogonUser;
import cn.gov.customs.cacp.sdks.core.user.pojo.CacpLogonUser;
import java.lang.reflect.Parameter;
import java.util.Objects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * H4A切面
 *
 * @author sunxuewen
 * @since 2024/6/27 15:57
 */
@Aspect
@Component
public class MockUserAspect {

  // execution(public * cn.gov.customs..*.*(..) && @args(cn.gov.customs.cacp.sdks.core.user.annotation.LogonUser)
  // @Pointcut("@target(org.springframework.web.bind.annotation.RestController)")
  @Pointcut("execution(public * cn.gov.customs..*Controller.*(..))")
  public void aspect() {}

  @Around("aspect()")
  public Object execute(ProceedingJoinPoint point) throws Throwable {
    CacpLogonUser mockUser = MockUserHelper.getMockUser();
    if (Objects.isNull(mockUser)) {
      return point.proceed();
    }

    Parameter[] parameters = ((MethodSignature) point.getSignature()).getMethod().getParameters();
    for (int i = 0; i < parameters.length; i++) {
      if (parameters[i].isAnnotationPresent(LogonUser.class)) {
        point.getArgs()[i] = mockUser;
      }
    }
    return point.proceed(point.getArgs());
  }
}
