package com.games.gateway.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @description: ip+path限制工具
 * @author: mzc
 * @date: 2022-09-16 15:44
 **/
@Slf4j
@Component
public class LimitUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * redis key不存在的过期时间值
     */
    private Integer NULL_KEY_EXP_TIME_VALUE = -2;

    /**
     * redis key永不过期的过期时间值
     */
    private Integer NEVER_EXPIRES_VALUE = -1;


    public boolean limitCheck(String redisKey, int count, int time) {
        //用户操作某个话题的点赞，超过4次就提示，锁定5s
        int num;
        Long expTime = stringRedisTemplate.getExpire(redisKey);
        if (!stringRedisTemplate.hasKey(redisKey)) {
            num = 1;
            stringRedisTemplate.opsForValue().setIfAbsent(redisKey, "1", time, TimeUnit.SECONDS);
        } else {
            num = stringRedisTemplate.opsForValue().increment(redisKey, 1).intValue();
        }

        //处理获取过期时间如果为-1的话直接将限流redis删掉
        if (expTime != null && expTime.intValue() == NEVER_EXPIRES_VALUE) {
            //删除redis并返回false
            stringRedisTemplate.delete(redisKey);
            return false;
        }

        if (num >= count) {
            log.info("===>超过了限定的次数[{}],{}", count, redisKey);
            return true;
        }
        return false;
    }


    public Integer getCacheNum(String redisKey, int time) {
        //用户操作某个话题的点赞，超过4次就提示，锁定5s
        int num;
        Long expTime = stringRedisTemplate.getExpire(redisKey);
        if (!stringRedisTemplate.hasKey(redisKey)) {
            num = 1;
            stringRedisTemplate.opsForValue().setIfAbsent(redisKey, "1", time, TimeUnit.SECONDS);
        } else {
            num = stringRedisTemplate.opsForValue().increment(redisKey, 1).intValue();
        }

        //处理获取过期时间如果为-1的话直接将限流redis删掉
        if (expTime != null && expTime.intValue() == NEVER_EXPIRES_VALUE) {
            //删除redis并返回false
            stringRedisTemplate.delete(redisKey);
            return 0;
        }
        return num;
    }
}
