package com.ssm.interceptor;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ssm.common.SpringInitConfig;
import com.ssm.model.system.SysMenu;
import com.ssm.model.system.SysRole;
import com.ssm.model.system.SysUser;
import com.ssm.service.system.SysMenuService;
import com.ssm.service.system.SysRoleService;
import com.ssm.util.PackageBeanUtils;
import com.ssm.util.Util;
import com.ssm.web.WithoutUserLogin;


@Component
public class MenuInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private SysMenuService menuService;
	@Autowired
	private SysRoleService sysRoleService;
	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		
		HandlerMethod method = (HandlerMethod)handler;
		if(method.getMethod().isAnnotationPresent(WithoutUserLogin.class))
			return true;
		
		HttpServletRequest hreq = request;
		HttpSession session = hreq.getSession();
		
		String url = hreq.getRequestURI();
        String url2 = url.substring(url.lastIndexOf("/") + 1, url.lastIndexOf("?") == -1 ? url.length() : url.lastIndexOf("?"));
        
        //UserModel userModel = SSOHelper.getUser(request);
        //System.out.println("UserModel:"+userModel.toString());
        //sysUserService.findByEmployeeno(userModel.getLoginName());
        
        SysUser sysUser = Util.getUserSession(request);
        List<SysRole> roles = null;
        if(sysUser != null){
        	//绑定 用户的角色
        	roles = (List<SysRole>) session.getAttribute(sysUser.getUserid().toString());
        	if(roles == null){
        		roles = sysRoleService.findUserRoleByUserId(sysUser.getUserid());
				session.setAttribute(sysUser.getUserid().toString(), roles);
        	}
        } else {
        	roles = new ArrayList<SysRole>();
        }
		
        
        //SysUser sysUser = (SysUser) session.getAttribute(Const.USER_SESSION_KEY);
        List<SysMenu> menuList = new ArrayList<SysMenu>();
        for(SysRole role : roles) {
        	//角色和菜单的  映射关系
        	List<SysMenu> r_m_list = (List<SysMenu>) SpringInitConfig.menuMap.get(role.getRoleId().toString()); 
        	menuList.addAll(r_m_list.isEmpty() ? new ArrayList<SysMenu>() : r_m_list); //包含 重复值
        }
        
        //去除 重复 项
        List<SysMenu> finalMenuList = new ArrayList<SysMenu>();
        for(SysMenu menu : menuList) {
        	if(finalMenuList.contains(menu))
        		continue;
        	else
        		finalMenuList.add(menu);
        }
        
        //排序
        Collections.sort(finalMenuList, new Comparator<SysMenu>() {
			@Override
			public int compare(SysMenu o1, SysMenu o2) {
				return Integer.valueOf(o1.getOrderby())- Integer.valueOf(o2.getOrderby());
			}
		});
        
        //组成 父子 结构的菜单 
        List<SysMenu> lstRoot = new ArrayList<SysMenu>();
        if(!finalMenuList.isEmpty()){
			for (SysMenu sysMenuWithBLOBs : finalMenuList) {
				if(sysMenuWithBLOBs.getLevel() == 1){
					lstRoot.add(sysMenuWithBLOBs);
				}
				
			}
			if(!lstRoot.isEmpty()){
				for (int i = 0; i < lstRoot.size(); i++) {
					PackageBeanUtils.packageChildSysmenus(lstRoot.get(i) , finalMenuList);
				}
			}
        }
        
		/**
		 * 用户的所有权限菜单
		 */
//		session.setAttribute("ValidateMenus",finalMenuList);
		menuService.setCurrentMenu(lstRoot, url2);
		session.setAttribute("menu", lstRoot);
//        if(session.getAttribute(sysUser.getUserid().toString()) != null){
//        	//session.setAttribute("menu", menuService.getMenuList(session,sysUser));
//        } else {
//        	ctx.setAttribute(sysUser.getUserid().toString(), menuService.getMenuList(session,sysUser));
//        }
        
		return true;
		
	}
}
