package com.games.gateway.filters;

import com.games.gateway.enums.BizResultCode;
import com.games.gateway.config.FilterOrderedConfig;
import com.games.gateway.domain.IpPathLimit;
import com.games.gateway.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 路径 限流器
 */
@Order(FilterOrderedConfig.IpPathLimitGlobalFilter)
@Slf4j
@Component
public class IpPathLimitGlobalFilter implements GlobalFilter {

    @Autowired
    private LimitUtils limitUtils;

    @Autowired
    private RedisKeyUtils redisKeyUtils;

    @Autowired
    private IpPathLimitCache ipPathLimitCache;

    @Autowired
    private PathWhiteCache pathWhiteCache;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String ip = IpAddressUtils.getIpAddress(request);
        ip = StringUtils.isNotEmpty(ip) ? ip.replace(":", "-") : ip;

        String path = request.getPath().value();
        //白名单存在path，直接通过
        if (pathWhiteCache.exists(path)) {
            return chain.filter(exchange);
        }

        String key = redisKeyUtils.ipPathLimitCheckKey(ip, path);
        //手动调动接口配置过最大访问次数，过期时间，从缓存存
        IpPathLimit ipPathLimit = ipPathLimitCache.get(path);
        if (ipPathLimit != null && ipPathLimit.getCount() != null && ipPathLimit.getExpireTime() != null) {
            Integer count = ipPathLimit.getCount();
            Integer expireTime = ipPathLimit.getExpireTime();
            //检测是否超过最大访问次数
            boolean b = limitUtils.limitCheck(key, count, expireTime);
            if (b) {
                //设置locale
                MessageUtils.setLocale(exchange);
                BizResultCode.SYS_OPERATOR_FAST_ERROR.check(true);
                return exchange.getResponse().setComplete();
            }
        }
        return chain.filter(exchange);
    }
}
