package com.gci.boot.common.util;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.gci.boot.constant.CacheConstant;
import com.gci.boot.constant.CommonConstant;
import com.gci.boot.exception.GciBootException;
import com.gci.boot.modules.system.vo.LimitRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LimitCheckUtil {
    /**
     * 接口每日限制次数
     */
    private static int limitCount = 10;

    public static void putNeedCheck(String username, String token) {
        Object o = RedisUtil.get(CacheConstant.LIMIT_USERNAME + username);
        if (ObjectUtil.isNotEmpty(o)) {
            //清空用户登录Token缓存
            RedisUtil.del(CommonConstant.PREFIX_USER_TOKEN + o);
        }
        RedisUtil.set(CacheConstant.LIMIT_USERNAME + username,token);
    }

    public static void check(HttpServletRequest request, String username, String token) {
        if (token != null) {
            Object u = RedisUtil.get(CacheConstant.LIMIT_USERNAME + username);
            if (ObjectUtil.isEmpty(u)) {
                return;
            } else {
                if (!u.equals(token)) {
                    return;
                }
            }
        }
        DateTime today = new DateTime();
        String uri = request.getRequestURI();
        String pre = CacheConstant.LIMIT_REQUEST + username + ":" + uri;
        Object o = RedisUtil.get(pre);
        if (ObjectUtil.isEmpty(o)) {
            LimitRequest limitRequest = new LimitRequest();
            limitRequest.setCount(1);
            limitRequest.setTime(today.toDateStr());
            RedisUtil.set(pre, JSONUtil.toJsonStr(limitRequest));
        } else {
            LimitRequest limitRequest = JSONUtil.toBean(JSONUtil.toJsonStr(o), LimitRequest.class);
            String time = limitRequest.getTime();
            if (time.equals(today.toDateStr())) {
                //是同一天的话看看次数
                if (limitRequest.getCount() >= limitCount) {
                    throw new GciBootException(uri+"超过每日请求次数限制" + limitCount +"次");
                } else {
                    limitRequest.setCount(limitRequest.getCount() + 1);
                }
            } else {
                limitRequest.setTime(today.toDateStr());
                limitRequest.setCount(1);
            }
            RedisUtil.set(pre,JSONUtil.toJsonStr(limitRequest));
        }
    }
}
