package cn.edu.hactcm.filter;

import cn.edu.hactcm.common.MyThreadLocalForEmployeeId;
import cn.edu.hactcm.common.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

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

@WebFilter("/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //AntPathMatcher匹配请求路径
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        //定义哪些请求不被拦截
        String[] uris = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/login",
                "/user/sendMsg"};

        //对请求uri和uris进行匹配检验，进而判定是否拦截
        boolean check = check(uris, request.getRequestURI());

        log.info("拦截到请求：{}",request.getRequestURI());
        if (check) {
            chain.doFilter(request,response);
            return;
        }
        //管理端判断是否登录
        if (request.getSession().getAttribute("employee") != null) {
            Long id = (Long) request.getSession().getAttribute("employee");
            MyThreadLocalForEmployeeId.setCurrentId(id);
            chain.doFilter(request,response);
            return;
        }
        //用户端判断是否登录
        if (request.getSession().getAttribute("user") != null) {
            Long id = (Long) request.getSession().getAttribute("user");
            MyThreadLocalForEmployeeId.setCurrentId(id);
            chain.doFilter(request,response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    /**
     * 封装一个方法，用于路径匹配检验
     * @param uris
     * @param requestUri
     * @return
     */
    public boolean check(String[] uris,String requestUri){
        for (String uri : uris) {
            boolean match = PATH_MATCHER.match(uri, requestUri);
            if (match) return true;
        }
        return false;
    }
}
