package cn.pluss.platform.aop;

import cn.pluss.platform.annotation.NoRepeatSubmit;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.exception.MsgException;
import com.google.common.cache.Cache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
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;

/**
 * @功能描述 aop解析注解
 *
 */
@Aspect
@Component
public class NoRepeatSubmitAop {


    @Autowired
    private Cache<String, Integer> cache;

    @Around("execution(* cn.pluss.platform.controller..*Controller.*(..)) && @annotation(nrs)")
    public Object arround(ProceedingJoinPoint pjp, NoRepeatSubmit nrs) {
        try {
            System.out.println("进入了切点：==================================>");
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            String sessionId = RequestContextHolder.getRequestAttributes().getSessionId();
            HttpServletRequest request = attributes.getRequest();
            String key = sessionId + "-" + request.getServletPath();
            if (cache.getIfPresent(key) == null) {// 如果缓存中有这个url视为重复提交
                Object o = pjp.proceed();
                cache.put(key, 0);
                return o;
            } else {
                System.out.println("重复提交！！");
                return null;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            if (e instanceof MsgException) {
                throw (MsgException) e;
            }
            return ResultGenerator.genSuccessResult("验证重复提交时出现未知异常!", null);
        }

    }

}