package com.yeejoin.amos.boot.biz.common.aop;

import com.yeejoin.amos.boot.biz.common.annotation.ResubmitCheck;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.util.DigestUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author DELL
 */
@Aspect
@Component
@Slf4j
public class ResubmitCheckAspect {

    @Resource
    HttpServletRequest request;

    @Autowired
    RedisUtils redisUtils;

    @Pointcut(value = "@annotation(com.yeejoin.amos.boot.biz.common.annotation.ResubmitCheck)")
    public void submit() {
    }

    @Before("submit()&&@annotation(resubmitCheck)")
    public void doBefore(JoinPoint joinPoint, ResubmitCheck resubmitCheck) {
        String token = !StringUtils.isEmpty(request.getHeader("token")) ? request.getHeader("token") : RequestContext.getToken();
        StringBuilder md5Builder = new StringBuilder(StringUtils.isEmpty(token) ? "unknown" : token);
        if (joinPoint.getArgs() != null) {
            for (Object obj : joinPoint.getArgs()) {
                md5Builder.append(obj.toString());
            }
        }
        String md5String = DigestUtils.md5DigestAsHex(md5Builder.toString().getBytes());
        Object cache = redisUtils.get(md5String);
        if (cache != null) {
            throw new RuntimeException(resubmitCheck.message());
        }
        redisUtils.set(md5String, 1, resubmitCheck.expireTime());
    }
}
