package com.philisense.www.utils;

import com.alibaba.fastjson.JSONObject;
import com.philisense.www.constant.Constants;
import com.philisense.www.filter.RepeatedlyRequestWrapper;
import com.philisense.www.utils.http.HttpHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * 判断请求url和数据是否和上一次相同，
 * 如果和上次相同，则是重复提交表单。 有效时间为10秒内。
 *
 * @author
 */
@Component
public class SameUrlDataUtils {

    private static final Logger log = LoggerFactory.getLogger(SameUrlDataUtils.class);

    public final String REPEAT_PARAMS = "repeatParams";

    public final String REPEAT_TIME = "repeatTime";

    @Autowired
    private RedisUtils redisUtils;

    /**
     * @param request
     * @param interval 间隔时间
     * @param header   令牌自定义标识
     * @return
     */
    public synchronized boolean isRepeatSubmit(HttpServletRequest request, Integer interval, String header) {
        String nowParams = "";
        if (request instanceof RepeatedlyRequestWrapper) {
            RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
            nowParams = HttpHelper.getBodyString(repeatedlyRequest);
        }

        // body参数为空，获取Parameter的数据
        if (StringUtils.isEmpty(nowParams)) {
            nowParams = JSONObject.toJSONString(request.getParameterMap());
        }
        Map<String, Object> nowDataMap = new HashMap<String, Object>();
        nowDataMap.put(REPEAT_PARAMS, nowParams);
        nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());
        log.info("SameUrlDataUtils.isRepeatSubmit() 参数：{}", JSONObject.toJSONString(nowDataMap));

        // 请求地址（作为存放cache的key值）
        String url = request.getRequestURI();

        // 唯一值（没有消息头则使用请求地址）
        String submitKey = StringUtils.trimToEmpty(request.getHeader(header));

        // 唯一标识（指定key + url + 消息头）
        String cacheRepeatKey = Constants.REPEAT_SUBMIT_KEY + url + submitKey;

        String sessionObj = redisUtils.get(cacheRepeatKey);
        if (StringUtils.isNotEmpty(sessionObj)) {
            Map<String, Object> sessionMap = JSONObject.parseObject(sessionObj, Map.class);
            if (sessionMap.containsKey(url)) {
                Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
                if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, interval)) {
                    log.info("SameUrlDataUtils.isRepeatSubmit() 不允许重复提交，请稍候再试");
                    return true;
                }
            }
        }
        Map<String, Object> cacheMap = new HashMap<String, Object>();
        cacheMap.put(url, nowDataMap);
        log.info("SameUrlDataUtils.isRepeatSubmit() 【redis】 cacheRepeatKey：{}，参数：{}，有效时间：{}s", cacheRepeatKey, JSONObject.toJSONString(cacheMap), interval / 1000);
        redisUtils.setExpire(cacheRepeatKey, JSONObject.toJSONString(cacheMap), interval / 1000);
        return false;
    }

    /**
     * 判断参数是否相同
     */
    private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap) {
        String nowParams = (String) nowMap.get(REPEAT_PARAMS);
        String preParams = (String) preMap.get(REPEAT_PARAMS);
        return nowParams.equals(preParams);
    }

    /**
     * 判断两次间隔时间
     */
    private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap, int interval) {
        long time1 = (Long) nowMap.get(REPEAT_TIME);
        long time2 = (Long) preMap.get(REPEAT_TIME);
        if ((time1 - time2) < interval) {
            return true;
        }
        return false;
    }

}
