package com.younike.common.utils.repeatsubmit;

import com.alibaba.fastjson.JSON;
import com.younike.common.redis.ICached;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author tianh
 * @date 2022/3/21 14:47
 */
public class SameUrlDataInterceptor extends RepeatSubmitInterceptor {
    public final String REPEAT_PARAMS = "repeatParams";

    public final String REPEAT_TIME = "repeatTime";

    public final String SESSION_REPEAT_KEY = "repeatData";

    /**
     * 间隔时间，单位:秒 默认5秒
     *
     * 两次相同参数的请求，如果间隔时间大于该参数，系统不会认定为重复提交的数据
     */
    private int intervalTime = 2;

    @Resource
    private ICached cached;

    @Resource
    private RedissonClient redissonClient;

    public void setIntervalTime(int intervalTime)
    {
        this.intervalTime = intervalTime;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean isRepeatSubmit(HttpServletRequest request) throws Exception
    {
        // 本次参数
        String nowParams = JSON.toJSONString(request.getParameterMap());

        // 请求地址
        String nowUrl = request.getRequestURI();

        // 从redis中拿到请求参数
        RMap<Object, Object> requestParamMap = cached.pop(SESSION_REPEAT_KEY);
        requestParamMap.expire(2, TimeUnit.SECONDS);
        if (requestParamMap != null && requestParamMap.size() > 0)
        {
            Object url = requestParamMap.get(nowParams);
            if(url != null && nowUrl.equals(url.toString())){
                return true;
            }
        }
        cached.putBySecond(SESSION_REPEAT_KEY,nowParams,nowUrl,intervalTime);
        return false;
    }
}
