package com.xjrsoft.common.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.enums.RoleEnum;
import com.xjrsoft.common.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
public class RateLimitInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (isLimiting()) {
            // 暂停5秒
            Thread.sleep(5000);
            System.out.println("触发限流");
        }
        return true;
    }

    /**
     * 是否满足限流条件
     */
    public boolean isLimiting() {
        if (!StpUtil.isLogin()) return false;
        Long userId = StpUtil.getLoginIdAsLong();
        Long userType = Convert.toLong(StpUtil.getTokenSession().get(GlobalConstant.LOGIN_USER_TYPE), 0L);
        if (userType.equals(RoleEnum.STUDENT.getCode())) {
            Map map = redisUtil.get(GlobalConstant.WHITE_MANAGEMENT_CACHE_KEY, Map.class);
            if(map == null){
                return true;
            }
            return map.get(userId.toString()) == null;
        }
        return false;
    }
}
