package cn.wisenergy.web.config.hanlder;

import cn.wisenergy.common.utils.exception.BASE_RESP_CODE_ENUM;
import cn.wisenergy.common.utils.exception.BaseCustomException;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: nh
 * @create: 2021-04-01 10:44
 **/
@Component
public class LoginFilter implements Filter {

    private final static List<String> URI_LIST = Arrays.asList("/login","/webjars","/swagger-resources",
            "/null","/v2","/swagger-ui.html","/work/collect","/work/order/addOrder","/work/order/examine","/work/order/getDeptNotOrderInfo",
            "/work/order/getExamineApplets","/work/order/getProject","/work/order/noSubmit","/work/order/query","/work/order/reject",
            "/changePassword","getUserInfo","/statistics/getCurrentMonthWorkTimeCollect","/statistics/getMonthlyWorkingHours");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();

        ServletContext application = session.getServletContext();
        Map<String, String> loginMap = (Map<String, String>) application.getAttribute("loginMap");
        // 请求接口不为登录再过滤
        String requestURI = ((HttpServletRequest) request).getRequestURI();
        for (String s : URI_LIST) {
            if (requestURI.startsWith(s)) {
                chain.doFilter(request,response);
                return;
            }
        }
        if (loginMap == null) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.PLEASE_RE_LOGIN);
        }
        Collection<String> values = loginMap.values();
        if (!values.contains(session.getId())) {
            throw new BaseCustomException(BASE_RESP_CODE_ENUM.PLEASE_RE_LOGIN);
        }
    }

    @Override
    public void destroy() {

    }
}
