package com.saye.hrs.config;

import com.saye.hrs.commons.getBean.BeanUtil;
import com.saye.hrs.commons.string.StringDUtil;
import com.saye.hrs.mapper.system.MenuMapper;
import com.saye.hrs.model.Users;
import org.apache.catalina.User;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class LoginFilter implements Filter {

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

    }
    static List<String> list= null;
    static {
        list = new ArrayList<String>();
        list.add("/getCode");
        list.add("/toLogin");
        list.add("/login");
        list.add("/logout");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        MenuMapper menuMapper = BeanUtil.getBean(MenuMapper.class);
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURI();
        System.out.println("this is MyFilter,url :"+url);
        if(!list.contains(url) && url.indexOf("/layui/")==-1 && url.indexOf("/showFile/")==-1 && url.indexOf("/js")==-1 && url.indexOf("/css")==-1 && url.indexOf("/image")==-1 && url.indexOf("/api")==-1 && url.indexOf("/showImg")==-1) {
            Users user = (Users) request.getSession().getAttribute("user");
            if(user == null) {
                response.sendRedirect("/toLogin");
            }else {
                //判断用户是否有此菜单权限
                HashMap<Object,Object> map = new HashMap<Object,Object>();
                map.put("userid", user.getUserId());
                map.put("url", url);
                List<HashMap<Object,Object>> menuList = menuMapper.findMenuByUrl(map);
                if(!menuList.isEmpty()) {
                    String menu_id = StringDUtil.changeNullToEmpty(menuList.get(0).get("MENU_ID"));
                    map.put("menu_id", menu_id);
                    List<HashMap<Object,Object>> roleList = menuMapper.findRoleByUserAndMenu(map);
                    if(roleList.isEmpty()) {
                        response.sendRedirect("/toNoAuthority");
                    }else{
                        filterChain.doFilter(request, response);
                    }
                }else{
                    filterChain.doFilter(request, response);
                }
            }
        }else{
            filterChain.doFilter(request, response);
        }

    }

    @Override
    public void destroy() {

    }
}
