package com.hzs.common.core.aspect;

import cn.hutool.json.JSONUtil;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.constant.Constants;
import com.hzs.common.core.constant.TokenConstants;
import com.hzs.common.core.exception.base.BaseException;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

/**
 * @Description: 防止表单重复提交处理
 * @Author: jiang chao
 * @Time: 2023/6/15 9:24
 * @Classname: RepeatSubmitOldAspectAdvice
 * @PackageName: com.hzs.common.core.aspect
 */
@Slf4j
@Aspect
@Component
public class RepeatSubmitSimpleAspectAdvice {

    private final String REPEAT_PARAMS = "repeatParams";

    private final String REPEAT_TIME = "repeatTime";

    @Autowired
    private RedisService redisService;

    /**
     * 定义切点Pointcut
     */
    @Pointcut("@annotation(com.hzs.common.core.annotation.RepeatSubmitSimple)")
    private void RepeatSubmitSimplePointCut() {
    }

    /**
     * 请求执行前进行处理
     *
     * @param joinPoint
     * @param repeatSubmitSimple 定义的防重复注解
     */
    @Before(value = "RepeatSubmitSimplePointCut() && @annotation(repeatSubmitSimple)")
    public void RepeatSubmitSimpleBefore(JoinPoint joinPoint, RepeatSubmitSimple repeatSubmitSimple) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 获取body参数
        String nowParams = JSONUtil.toJsonStr(joinPoint.getArgs());
        if (StringUtils.isEmpty(nowParams)) {
            // body参数为空，获取Parameter的数据
            nowParams = JSONUtil.toJsonStr(request.getParameterMap());
        }

        Map<String, Object> nowDataMap = new HashMap<>();
        nowDataMap.put(REPEAT_PARAMS, nowParams);
        nowDataMap.put(REPEAT_TIME, System.currentTimeMillis());

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

        // 唯一值（没有消息头则使用请求地址）
        String submitKey = request.getHeader(TokenConstants.AUTHENTICATION);
        if (StringUtils.isEmpty(submitKey)) {
            submitKey = url;
        }

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

        Object sessionObj = redisService.getCacheObject(cacheRepeatKey);
        if (sessionObj != null) {
            Map<String, Object> sessionMap = (Map<String, Object>) sessionObj;
            if (sessionMap.containsKey(url)) {
                Map<String, Object> preDataMap = (Map<String, Object>) sessionMap.get(url);
                if (compareParams(nowDataMap, preDataMap) && compareTime(nowDataMap, preDataMap, repeatSubmitSimple.intervalTime())) {
                    // 参数相同，需要拦截返回
                    throw new BaseException("不允许重复提交，请稍后再试");
                }
            }
        }
        Map<String, Object> cacheMap = new HashMap<>();
        cacheMap.put(url, nowDataMap);
        redisService.setCacheObject(cacheRepeatKey, cacheMap, repeatSubmitSimple.intervalTime(), TimeUnit.SECONDS);
    }

    /**
     * 判断参数是否相同
     *
     * @param nowMap 当前参数
     * @param preMap 缓存参数
     * @return
     */
    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);
    }

    /**
     * 判断两次间隔时间
     *
     * @param nowMap       当前参数
     * @param preMap       缓存参数
     * @param intervalTime 间隔时间
     * @return
     */
    private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap, long intervalTime) {
        long time1 = (Long) nowMap.get(REPEAT_TIME);
        long time2 = (Long) preMap.get(REPEAT_TIME);
        return (time1 - time2) < (intervalTime * 1000L);
    }

}
