package com.jiayue.ssi.aspectj;

import javax.servlet.http.HttpServletRequest;
import com.jiayue.ssi.annotation.InterfaceLimit;
import com.jiayue.ssi.util.InterfaceLimitUtil;
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.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.jiayue.ssi.util.ResponseVO;
import lombok.extern.slf4j.Slf4j;

/**
 * 接口限制实现
 *
 * @author xsl
 * @since 2023/02/23
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class InterfaceLimitAspect {
    /**
     * 层切点
     */
    @Pointcut("@annotation(interfaceLimit)")
    public void controllerAspect(InterfaceLimit interfaceLimit) {
    }

    @Around("controllerAspect(interfaceLimit)")
    public ResponseVO doAround(ProceedingJoinPoint pjp, InterfaceLimit interfaceLimit) throws Throwable {
        // 获得request对象
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        if (!InterfaceLimitUtil.checkInterface(request,interfaceLimit.time(),interfaceLimit.value())){
            log.error("接口拦截：{} 请求超过限制频率【{}次/{}ms】,IP为{}", request.getRequestURI(), interfaceLimit.value(), interfaceLimit.time(), request.getRemoteAddr());
            return ResponseVO.fail("请求过于频繁，请稍后再试");
        }
        // result的值就是被拦截方法的返回值
        ResponseVO result = (ResponseVO)pjp.proceed();
        return result;
    }
}
