package com.amms.security;

import com.amms.domain.SysUser;
import com.amms.domain.vo.Result;
import com.amms.util.JsonUtils;
import com.amms.util.RedisUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${token.expireTime}")
    private Long expireTime;

    /**
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("Authorization");
        // 没有token，即未登录，放行，交给下一步处理
        if(token == null) {
            doFilter(request,response,filterChain);
            return;
        }
        // 有token，通过jwt工具类，解析tokenId
        Claims claims = null;
        try {
            claims = jwtUtils.parseToken(token);
        } catch (SignatureException e){
            // 需要返回401，重新登陆
            response.getWriter().write("验签失败！！！");
            return;
        } catch (ExpiredJwtException e) {
            // 需要返回401，重新登陆
            Result result = Result.error(401, "登录失效，请重新登录！");

            response.getWriter().write(JsonUtils.toJson(result));
            return;
        }
        // 在jwt中获取tokenId
        String tokenId = claims.get("tokenId", String.class);

        if (tokenId == null) {
            // 放行
            doFilter(request,response,filterChain);
        }

        // 在redis中根据tokenId获取用户信息
        SysUser sysUser = redisUtils.get(tokenId, SysUser.class);
        if (sysUser != null) {  // 用户已登录
            // 将用户信息放到SecurityContext中
            UsernamePasswordAuthenticationToken authentication =
                    new UsernamePasswordAuthenticationToken(sysUser, null, null);
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 重新将用户信息存储到redis中
            redisUtils.set(tokenId, sysUser, expireTime, TimeUnit.MINUTES);

        } else {  // 用户登录失效
            // 需要返回401，重新登陆
            Result result = Result.error(401, "登录失效，请重新登录！");

            response.getWriter().write(JsonUtils.toJson(result));
            return;
        }
        // 放行
        doFilter(request,response,filterChain);
    }
}
