package com.cmeeting.ad.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cmeeting.ad.entity.RobotSecurityUser;
import com.cmeeting.ad.util.JwtUtil;
import com.cmeeting.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author 王长伟
 * @Description token过滤器来验证token有效性
 * @Date 00:32 2019-03-17
 * @Param
 * @return
 **/
@Slf4j
@Component
public class RobotJwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private JwtUtil jwtUtil;

    @Value("${jwt.expireTime}")
    private long expireTime;

    @Resource
    private RedisUtils redisUtil;

    // 定义白名单路径（无需JWT验证的接口）
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/user/**",   // 登录接口
            "/agent/auth/**"    // 登录接口
    );

    // 判断路径是否在白名单中（支持Ant风格路径匹配）
    private boolean isWhiteListPath(String requestURI) {
        return WHITE_LIST.stream()
                .anyMatch(pattern -> new AntPathMatcher().match(pattern, requestURI));
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
//        // 检查请求路径是否在白名单中
//        String requestURI = request.getRequestURI();
//        if (isWhiteListPath(requestURI)) {
//            chain.doFilter(request, response); // 放行，不验证JWT
//            return;
//        }

        String token = jwtUtil.getToken(request);
        if (StringUtils.isNotBlank(token)) {
            Object o = redisUtil.get(token);
            RobotSecurityUser securityUser = JSONObject.parseObject(JSONObject.toJSONString(o), RobotSecurityUser.class);
            if (ObjectUtil.isNotNull(securityUser)) {
                UsernamePasswordAuthenticationToken authenticationToken =
                        new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                //延长token时间
                redisUtil.expire(token, expireTime);
            }
        }
        chain.doFilter(request, response);
    }
}
