package com.games.gateway.filters;

import com.games.gateway.enums.BizResultCode;
import com.games.gateway.config.FilterOrderedConfig;
import com.games.gateway.config.GatewayBizConfig;
import com.games.gateway.enums.LimiterTypeEnum;
import com.games.gateway.utils.*;
import lombok.extern.slf4j.Slf4j;
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.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


/**
 * token 限速 过滤器
 */
@Order(FilterOrderedConfig.TokenLimitGlobalFilter)
@Slf4j
@Component
public class TokenLimitGlobalFilter implements GlobalFilter {

    @Autowired
    private GatewayBizConfig globalConfig;

    @Autowired
    private LimitUtils limitUtils;

    @Autowired
    private RedisKeyUtils redisKeyUtils;

    @Autowired
    private LimitCache limitCache;

    /**
     * 限制缓存过期时间,秒
     */
    private static Integer EXPIRE_TIME = 60;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> tokenList = exchange.getRequest().getHeaders().get(Constant.AUTH_TK);
        if (CollectionUtils.isEmpty(tokenList)) {
            return chain.filter(exchange);
        }

        String token = tokenList.get(0);

        //application全局设置速率
        Integer tokenLimiterNum = globalConfig.getTokenLimiter();

        //mock接口单独对ip设置了速率
        Integer tokenLimiter = limitCache.get(LimiterTypeEnum.TOKEN, token);
        if (tokenLimiter > 0) {
            tokenLimiterNum = tokenLimiter;
        }

        //检测是否超过最大访问次数
        String limitKey = redisKeyUtils.tokenLimitCheckKey(token);
        boolean b = limitUtils.limitCheck(limitKey, tokenLimiterNum, EXPIRE_TIME);
        if (b) {
            log.info("token:{} limited", token);
            //设置locale
            MessageUtils.setLocale(exchange);
            BizResultCode.SYS_OPERATOR_FAST_ERROR.check(true);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

}
