package com.hrs.filter;

import com.hrs.model.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**   
* Copyright: Copyright (c) 2026 chinasofti
* 
* @ClassName: LoginFilter.java
* @Description: 登录过滤器/拦截未登录的请求
*
* @version: v1.0.0
* @author: 赵恒
* @date: 2026年4月13日 上午9:36:48 
*
* Modification History:
* Date         Author          Version            Description
*---------------------------------------------------------*
* 2026年4月13日     赵恒           v1.0.0               新建文件
*/
@WebFilter("/*")  // 拦截所有请求
public class LoginFilter implements Filter {
    
    // 不需要登录就能访问的路径
    private static final String[] PUBLIC_PATHS = {
    	    "/user/login",      // 登录页面
    	    "/user/register",   // 注册页面 ✅ 新增
    	    "/css/",            // 静态资源
    	    "/js/",             
    	    "/images/",
    	    "/jsp/common/",     // 公共页面
    	    "/index.jsp"        // 首页
    };
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("登录过滤器初始化");
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        
        // 1. 获取请求路径
        String path = req.getRequestURI().substring(req.getContextPath().length());
        System.out.println("过滤器拦截路径：" + path);
        
        // 2. 判断是否是公开路径
        if (isPublicPath(path)) {
            chain.doFilter(request, response);
            return;
        }
        
        // 3. 检查Session中是否有登录用户
        HttpSession session = req.getSession(false);
        User loginUser = null;
        if (session != null) {
            loginUser = (User) session.getAttribute("loginUser");
        }
        
        // 4. 如果没登录，跳转到登录页
        if (loginUser == null) {
            System.out.println("未登录，拦截请求：" + path);
            resp.sendRedirect(req.getContextPath() + "/user/login");
            return;
        }
        
        // 5. 已登录，继续请求
        chain.doFilter(request, response);
    }
    
    /**
     * 判断是否是公开路径
     */
    private boolean isPublicPath(String path) {
        // 如果是根路径，放行（通常重定向到首页）
        if (path == null || path.equals("/") || path.isEmpty()) {
            return true;
        }
        
        // 检查是否在公开路径列表中
        for (String publicPath : PUBLIC_PATHS) {
            if (path.startsWith(publicPath)) {
                return true;
            }
        }
        
        return false;
    }
    
    @Override
    public void destroy() {
        System.out.println("登录过滤器销毁");
    }
}