package cn.superdesk.uniorder.common.security.openapi.interceptor.AvoidRepeatableCommit;

import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.constants.ResponseResultConstants;
import cn.superdesk.uniorder.common.mq.redis.constants.BaseRedisConf;
import cn.superdesk.uniorder.common.mq.redis.service.RedisManager;
import cn.superdesk.uniorder.common.rest.request.IpUtils;
import cn.superdesk.uniorder.common.rest.request.holder.RequestHolder;
import cn.superdesk.uniorder.common.rest.response.ResponseResultOuterUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @Description: 重复提交aop
 * @Author: linjinyu
 * @CreateDate: 2021/10/27 下午3:07
 * @UpdateUser: linjinyu
 * @UpdateDate: 2021/10/27 下午3:07
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
public class AvoidRepeatableCommitAspect {

	@Autowired
	private RedisManager redisManager;

	/**
	 * @param point
	 */
	@Around("@annotation(AvoidRepeatableCommit)")
	public Object around(ProceedingJoinPoint point) throws Throwable {

		HttpServletRequest request = RequestHolder.getRequest();

		String ip = IpUtils.getIpAddr(request);

		// 获取注解
		MethodSignature signature = (MethodSignature) point.getSignature();
		Method          method    = signature.getMethod();

		// 目标类、方法
		String className = method.getDeclaringClass().getName();

		String name = method.getName();

		// 得到类名和方法
		String ipKey = String.format("%s#%s", className, name);

		// 转换成HashCode
		int hashCode = Math.abs(ipKey.hashCode());

		String key = String.format("%s:%s_%d", BaseRedisConf.AVOID_REPEATABLE_COMMIT, ip, hashCode);

		log.info("ipKey={},hashCode={},key={}", ipKey, hashCode, key);

		AvoidRepeatableCommit avoidRepeatableCommit = method.getAnnotation(AvoidRepeatableCommit.class);

		long timeout = avoidRepeatableCommit.timeout();

		String value = redisManager.getAvoidRepeatableCommitLock(key);

		if (StrUtil.isNotBlank(value)) {
			log.info("请勿重复提交表单");
			return ResponseResultOuterUtils.createErrorResult(ResponseResultConstants.ERROR, "请勿重复提交表单");
		}

		redisManager.setAvoidRepeatableCommitLock(key, timeout);

		// 执行方法
		Object object = point.proceed();

		return object;
	}

}
