package com.sqx.modules.app.interceptor;


import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sqx.common.exception.CzgException;
import com.sqx.common.exception.SqxException;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.IPUtils;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.app.utils.JwtUtils;
import com.sqx.modules.redisService.RedisService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
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.util.Date;

/**
 * 权限(Token)验证
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    private static final Logger log = LoggerFactory.getLogger(AuthorizationInterceptor.class);
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserService userService;

    private final RedisService redisService;

    public static final String USER_KEY = "userId";

    public AuthorizationInterceptor(RedisService redisService) {
        this.redisService = redisService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }

        // 获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeader());
        }

        // 凭证为空
        if (StringUtils.isBlank(token)) {
            throw new SqxException(jwtUtils.getHeader() + "不能为空", HttpStatus.UNAUTHORIZED.value());
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
            throw new SqxException(jwtUtils.getHeader() + "失效，请重新登录", HttpStatus.UNAUTHORIZED.value());
        }

        long userId = Long.parseLong(claims.getSubject());
        request.setAttribute(USER_KEY, userId);

        String ip = IPUtils.getIpAddr(request); // 获取用户的 IP 地址
        // 检查用户是否超过限流
        if (redisService.checkIpJumpLimit(userId, ip)) {
            log.warn("用户地址跳动频繁，封禁: {}", userId);
            if (!redisService.isSetUserState(userId)) {
                ThreadUtil.execAsync(() -> {
                    userService.update(null, new LambdaUpdateWrapper<UserEntity>()
                            .eq(UserEntity::getUserId, userId)
                            .set(UserEntity::getStatus, 0));
                });
            }
            throw new CzgException("ip跳动过于频繁，请联系管理员解封");
        }

        ThreadUtil.execAsync(() -> {
            redisService.recordUrlVisitCountWithIp(userId, request.getRequestURI(), ip);
        });

        // 设置 userId 到 request 里，后续根据 userId 获取用户信息
        UserEntity user = userService.selectUserById(userId);
        if (user != null && user.getStatus().equals(0)) {
            throw new CzgException("异常行为用户: {}" + user.getUserId());
        }

        if (redisService.isRecordUserOnLineTime(userId)) {
            ThreadUtil.execAsync(() -> {
                // 记录用户最后一次调用接口的时间
                UserEntity userEntity = new UserEntity();
                userEntity.setUserId(userId);
                userEntity.setOnLineTime(DateUtils.format(new Date()));
                userService.updateById(userEntity);
            });
        }

        return true;
    }
}
