package cn.com.poc.common.aspect;

import cn.com.yict.framemax.core.i18n.I18nMessageException;
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;

import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
public class RateLimitAspect {

    private Map<String, Long> accessMap = new ConcurrentHashMap<>();

    @Around("execution(public * cn.com.poc.common.rest.SmsRest.smsDelivered(..))")
    public Object limitAccess(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        String phone = String.valueOf(args[0]);
        // 检查访问计数和时间
        if (isLimitExceeded(phone)) {
            throw new I18nMessageException("exception/sms.limit.message");
        }

        Object result = joinPoint.proceed();

        // 更新访问计数和时间
        updateAccess(phone);

        return result;
    }

    private boolean isLimitExceeded(String phone) {
        long now = System.currentTimeMillis();
        //获取上次访问时间（phone作为key,上一次访问的时间作为value）
        long lastAccessTime = accessMap.getOrDefault(phone, 0L);
        long interval = now - lastAccessTime;
        long limitInterval = 60000; // Example: 限制每1分钟调用一次
        return interval < limitInterval;
    }

    private void updateAccess(String phone) {
        accessMap.put(phone, System.currentTimeMillis());
    }
}

