package com.hzs.common.core.aspect;

import com.hzs.common.core.annotation.RepeatSubmit;
import com.hzs.common.core.config.BdConfig;
import com.hzs.common.core.constant.CacheToolsConstants;
import com.hzs.common.core.constant.HttpStatus;
import com.hzs.common.core.constant.MemberFieldConstants;
import com.hzs.common.core.enums.EEnv;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.service.RedisService;
import com.hzs.common.core.web.domain.AjaxResult;
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.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

/**
 * 防止重复提交的切面类
 */
@Aspect
@Component
@Slf4j
public class RepeatSubmitAspectAdvice {

    private RedisService redisService;

    @Autowired
    public void setRedisService(RedisService redisService) {
        this.redisService = redisService;
    }

    @Pointcut("@annotation(com.hzs.common.core.annotation.RepeatSubmit)")
    private void requestRepeatCheck() {
        log.info("进入切点");
    }

    @Around(value = "requestRepeatCheck()")
    public Object handleResubmit(ProceedingJoinPoint joinPoint) {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String token = request.getHeader(MemberFieldConstants.TOKEN) == null ? "" :
                request.getHeader(MemberFieldConstants.TOKEN);

        try {
            if (EEnv.DEV.getValue().equals(BdConfig.getEnv())) {
                // 本地研发环境，不做拦截处理
                return joinPoint.proceed();
            }

            Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
            //获取注解信息
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            int delaySeconds = annotation.delaySeconds();

            //解析参数
            String cacheObject = redisService.getCacheObject(CacheToolsConstants.IDEMPOTENT_TOKEN + token);
            // 验证token是否是由本系统生成的
            // 验证token是否可以加锁，可以加锁说明没有重复提交
            if (!token.equals(cacheObject) || !redisService.lockKeyOnce(cacheObject, delaySeconds)) {
                // 替换翻译
                return AjaxResult.error("请求已经失效，请刷新重试！");
            }
            Object obj = joinPoint.proceed();
            afterReturn(token, obj);
            return obj;
        } catch (Throwable throwable) {
            // 处理异常通知
            log.error("执行异常通知:{}", throwable.getMessage(), throwable);
            redisService.deleteObjectByKey(token);
            throw new ServiceException(throwable.getMessage());
        }
    }

    private void afterReturn(String token, Object obj) {
        if (obj instanceof AjaxResult) {
            AjaxResult ajaxResult = (AjaxResult) obj;
            // 成功删除token
            if ((Integer) ajaxResult.get(AjaxResult.CODE_TAG) == HttpStatus.SUCCESS) {
                redisService.deleteObjectByKey(token);
                redisService.deleteObjectByKey(CacheToolsConstants.IDEMPOTENT_TOKEN + token);
            } else {
                redisService.deleteObjectByKey(token);
            }
        }
    }

}
