package com.saye.hospitalgd.config;

import com.saye.hospitalgd.commons.string.StringDUtil;
import com.saye.hospitalgd.mapper.system.MenuMapper;
import com.saye.hospitalgd.model.Users;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
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;

public class ShiroFilter extends AuthorizationFilter{
	
	private MenuMapper menuMapper;
	
	static List<String> list= null;
	static {
		list = new ArrayList<String>();
		list.add("/getCode");
		list.add("/toLogin");
		list.add("/login");
		list.add("/logout");
		list.add("/favicon.ico");
		list.add("/image/sgl.png");
		list.add("/js/common.js");
	}
	
	@Override
	protected boolean isAccessAllowed(ServletRequest srequest, ServletResponse sresponse, Object mappedValue)
			throws Exception {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
    protected boolean onAccessDenied(ServletRequest srequest, ServletResponse sresponse) throws IOException {
		
		if(menuMapper == null) {
			ServletContext context = srequest.getServletContext();
			ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
			if(ctx != null) {
				menuMapper= (MenuMapper ) ctx.getBean("menuMapper");
			}
		}
		HttpServletRequest request = (HttpServletRequest) srequest;
		HttpServletResponse response = (HttpServletResponse) sresponse;
		String url = request.getRequestURI();
		System.out.println("this is MyFilter,url :"+url);
		if(!list.contains(url) && url.indexOf("/layui/")==-1 && url.indexOf("/showFile/")==-1) {
			Users user = (Users)SecurityUtils.getSubject().getPrincipal();

			String requestType = StringDUtil.changeNullToEmpty(request.getHeader("X-Requested-With"));
			if(user == null) {
				if(!"".equals(requestType) && requestType.equalsIgnoreCase("XMLHttpRequest")) {
					response.setHeader("sessionstatus", "timeout");
					response.sendError(403, "session timeout.");
				}else{
					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 = this.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 = this.menuMapper.findRoleByUserAndMenu(map);
					if(roleList.isEmpty()) {
						response.sendRedirect("/toNoAuthority");
					}
				}
			}
		}
		return true;
	}

}
