package com.webchat.config.annotation;

import com.webchat.common.constants.WebConstant;
import com.webchat.common.exception.AuthException;
import com.webchat.common.exception.BusinessException;
import com.webchat.common.helper.SessionHelper;
import com.webchat.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * 异常点击事件拦截
 */
@Slf4j
public class SafeClickInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisService redisService;
    /**
     * 在调用方法之前执行拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        SafeClick safeClick = method.getAnnotation(SafeClick.class);
        if (safeClick == null) {
            return true;
        }
        // 操作人
        String userId = SessionHelper.getCurrentUserId();
        if (StringUtils.isBlank(userId)) {
            throw new AuthException("未登录！");
        }
        // 事件
        String action = safeClick.event().name();
        // 允许多长时间操作一次
        long liveTime = safeClick.time();
        String key = action.concat("-").concat(userId);
        boolean installLockResult = redisService.installLockForMS(key, WebConstant.CACHE_NONE, liveTime);
        if (installLockResult) {
            return true;
        }
        log.error("<<<< {} >>>>, userId: {}, action: {}", safeClick.message(), userId, action);
        throw new BusinessException(safeClick.message());
    }
}