package com.ssm.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ssm.common.SpringInitConfig;
import com.ssm.model.system.JsTree;
import com.ssm.model.system.State;
import com.ssm.model.system.SysMenu;
import com.ssm.model.system.SysRole;
import com.ssm.model.system.SysUser;
import com.ssm.model.validator.SysRoleValidator;
import com.ssm.service.system.SysMenuService;
import com.ssm.service.system.SysRoleService;
import com.ssm.util.page.Helper;
import com.ssm.util.page.PagedResult;
import com.ssm.web.Const;
import com.ssm.web.RoleLimit;

/**
 *角色管理
 */
@RequestMapping(value="sysRole")
@Controller
public class SysRoleController {

	@Autowired
	SysRoleService sysRoleService;
	
	@Autowired
	private SysMenuService sysMenuService;
	
	/**
	 * 查询角色列表
	 */
	@RequestMapping(value="roleInfo")
	@ResponseBody
	@RoleLimit(pid = "sysRole", mid = "roleInfo")
	public ModelAndView roleInfo(HttpServletRequest request,Integer pageNo,Integer pageSizeSelect){
		ModelAndView mv = new ModelAndView("sysrole/role_list");  
		return mv;   
	}
	
	
	@RequestMapping(value="initDataList")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	public String initDataList(HttpServletRequest request,Integer pageNo,Integer pageSizeSelect, Model model){
		String roleName = request.getParameter("roleName");
		PagedResult<SysRole> pageResult = sysRoleService.queryByRoleName(roleName,pageNo, pageSizeSelect);
		if(pageResult !=null){
		    Helper.countStartPageAndEndPage(pageResult);
		    model.addAttribute("list", pageResult);
		}
		return "sysrole/data_list";
	}
	
	
	/**
	 * 校验角色新增
	 * @param binder
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@InitBinder("sysRole")
	public void InitBinder(DataBinder binder){
		binder.setValidator(new SysRoleValidator());
	}
	
	/**
	 * 校验角色修改
	 * @param binder
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@InitBinder("sysRole2")
	public void InitBinder2(DataBinder binder){
		binder.setValidator(new SysRoleValidator());
	}
	
	@RequestMapping(value="addRole")
	@ResponseBody
	@RoleLimit(pid = "sysRole", mid = "addRole")
	public ModelAndView addRole(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("sysrole/role_add"); 
		String parameter = request.getParameter("RoleID");
		if(parameter != null && parameter != ""){
			Integer rolrId = Integer.valueOf(parameter);
			SysRole role = sysRoleService.selectSysRoleByRoleId(rolrId);
			mv.addObject("role",role);
		}
		mv.addObject("sysRole", new SysRole());
		return mv;   
	}
	
	/**
	 * 创建角色
	 */
	@RequestMapping(value="createRole")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@Transactional(value="txManager")
	public String createRole(@Validated @ModelAttribute("sysRole") SysRole sysRole
			,BindingResult result){
		if(result.hasErrors()==false){
			sysRole.setIsDeleted(false);
			sysRole.setIsEnabled(false);
			sysRole.setCreatedDateTime(new Date());
			sysRoleService.insertSysRole(sysRole);
			return "redirect:roleInfo";
		}
		return "role_add";
	}
	
	/**
	 * 更新角色
	 */
	@RequestMapping(value="updateRole")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@Transactional(value="txManager")
	public String updateRole(@Validated @ModelAttribute("sysRole") SysRole sysRole
			,BindingResult result,HttpServletRequest request){
		if(result.hasErrors()==false){
			String parameter = request.getParameter("RoleID");
			sysRole.setIsDeleted(false);
			sysRole.setIsEnabled(false);
			if(parameter != null && parameter != ""){
				Integer rolrId = Integer.valueOf(parameter);
				sysRole.setRoleId(rolrId);
				sysRoleService.updateRoleByRoleId(sysRole);
			}
			return "redirect:roleInfo";
		}
		return "role_add";
	}
	
	@RequestMapping(value="updateRole2")
	@ResponseBody
	@RoleLimit(pid = "sysRole", mid = "updateRole2")
	public ModelAndView updateRole2(HttpServletRequest request){
		ModelAndView mv = new ModelAndView("sysrole/roleEdit"); 
		String parameter = request.getParameter("RoleID");
		if(parameter != null && parameter != ""){
			Integer rolrId = Integer.valueOf(parameter);
			SysRole role = sysRoleService.selectSysRoleByRoleId(rolrId);
			mv.addObject("role",role);
		}
		mv.addObject("sysRole", new SysRole());
		return mv;   
	}
	/**
	 * 更新角色是否可用
	 */
	@RequestMapping(value="updateRoleStatus",method=RequestMethod.POST)
	@ResponseBody
	@Transactional(value="txManager")
	@RoleLimit(pid = "sysRole", mid = "updateRoleStatus")
	public Map<String, Object> updateRoleStatus(HttpServletRequest request,Integer pageNo,Integer pageSizeSelect){
	    Map<String, Object> record = new HashMap<String, Object>();
		record.put("success", true);
		String parameter = request.getParameter("RoleID");
		if(StringUtils.isNotBlank(parameter)){
			Integer roleId = Integer.valueOf(parameter);
			SysRole role = sysRoleService.selectSysRoleByRoleId(roleId);
		
				if(role != null) {
					if(role.getIsEnabled()) { 
						role.setIsEnabled(false);
						record.put("roleStatus", false);
					} else {
						role.setIsEnabled(true);
						record.put("roleStatus", true);
					}
					int count = sysRoleService.updateRoleByRoleId(role);
					if(count <= 0)
						record.put("success", false);
					} else {
						//不存在
						record.put("success", false);
					}
		}
		return record;
	}
	
	/**
	 * 删除角色
	 */
	@RequestMapping(value="deleteRole")
	@Transactional(value="txManager")
	@ResponseBody
	@RoleLimit(pid = "sysRole", mid = "deleteRole")
	public Integer deleteRole(HttpServletRequest request,Integer pageNo,Integer pageSizeSelect){
		String parameter = request.getParameter("RoleID");
		Integer data = 0;
		if(parameter != null && parameter != ""){
			Integer roleId = Integer.valueOf(parameter);
			SysRole role = sysRoleService.selectSysRoleByRoleId(roleId);
			role.setIsDeleted(true);
			data = sysRoleService.updateRoleByRoleId(role);
		}
	    return data;
	}
	
	/**
	 * 编辑权限
	 */
	@RequestMapping(value="rolePermission")
	@ResponseBody
	@RoleLimit(pid = "sysRole", mid = "rolePermission")
	public ModelAndView rolePermission(HttpServletRequest request,Integer pageNo,Integer pageSizeSelect){
		ModelAndView mv= new ModelAndView("sysrole/rolePermission");
		String parameter = request.getParameter("RoleID");
		SysRole role = new SysRole();
		if(parameter != null && parameter != ""){
			Integer roleId = Integer.valueOf(parameter);
		    role = sysRoleService.selectSysRoleByRoleId(roleId);
		}
		mv.addObject("role", role);
		return mv;
	}
	
	
	@RequestMapping(value="loadMenuTree")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	public Map<String, Object> loadMenuTree(HttpServletRequest request, @RequestParam("roleId") String roleId){
		Map<String, Object> record = new HashMap<String, Object>();
		
		//页面权限  
		String pageMenu = getTreeDataJson();
		record.put("pageMenu", pageMenu);
		
		//按钮 权限
		String buttonMenu = getButtonDataJson();
		record.put("buttonMenu", buttonMenu);
		
		//查询所有的角色 拥有 菜单
		JSONArray jsonObj = new JSONArray();
		JSONArray jsonObj1 = new JSONArray();
		if(StringUtils.isNotBlank(roleId)){
			List<SysMenu> sysMenuList = sysRoleService.selectPageMenusByRoleId(Integer.valueOf(roleId));
			if(sysMenuList.size() > 0){
				for (SysMenu sysMenu : sysMenuList) {
					JSONObject sysMenu2 = new JSONObject();
					sysMenu2.put("menuId", sysMenu.getMenuid());
					sysMenu2.put("menuName", sysMenu.getMenucnname());
					jsonObj.add(sysMenu2);
				}
			}
			
			List<SysMenu> sysButtonMenuList = sysRoleService.selectButtonMenusByRoleId(Integer.valueOf(roleId));
			if(sysButtonMenuList.size() > 0){
				for (SysMenu sysMenu : sysButtonMenuList) {
					JSONObject sysMenu2 = new JSONObject();
					sysMenu2.put("menuId", sysMenu.getMenuid());
					sysMenu2.put("menuName", sysMenu.getMenucnname());
					jsonObj1.add(sysMenu2);
				}
			}
		}
		//第一棵树的 角色拥有菜单
		record.put("result", jsonObj.toString());
		record.put("result1", jsonObj1.toString());
		return record;
	}
	
	
	
	/**
	 * 初始化加载菜单树
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	public String getTreeDataJson(){
		List<SysMenu> menuList = sysMenuService.selectMenusByPage();//查询全部页面菜单
		List<SysMenu> menuList2 = sysMenuService.selectFirstMenu();//查询第一级菜单
		List<JsTree> treeList = new ArrayList<JsTree>();

		for (SysMenu sysMenu : menuList2) {
			JsTree j = new JsTree();
			j.setId(sysMenu.getMenuid());
			j.setText(sysMenu.getMenucnname());
			j.setIcon(sysMenu.getIcon());
			State state = new State();
			state.setOpened(true);
			j.setState(state);
			j.setChildren(GetSysMenuList(j.getId(),menuList));    //递归
			treeList.add(j);
		}
		StringBuilder sb = new StringBuilder();
		sb.append("{'id':'root','text':'页面权限','state':{'opened':true},'icon':'fa fa-bars','children':[");
		SetMenu(sb,treeList);        //生成json菜单
		sb.append("]}");
		return sb.toString();	
	}
	
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private List<JsTree> GetSysMenuList(int parentId, List<SysMenu> menuList) {
		List<JsTree> list = new ArrayList<JsTree>();
		List<SysMenu> menuList2= new ArrayList<SysMenu>();
		for (SysMenu sysMenu2 : menuList) {
			if(sysMenu2.getParentid() == parentId){
				menuList2.add(sysMenu2);
			}
		}
		for (SysMenu sysMenu : menuList2) {
			JsTree j = new JsTree();
			j.setId(sysMenu.getMenuid());
			j.setText(sysMenu.getMenucnname());
			j.setIcon(sysMenu.getIcon());
			State state = new State();
			state.setOpened(true);
			j.setState(state);
			j.setChildren(GetSysMenuList(j.getId(), menuList));
			list.add(j);
		}
		return list;
	}
	
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private List<JsTree> GetSysMenuList2(int parentId, List<SysMenu> menuList) {
		List<JsTree> list = new ArrayList<JsTree>();
		List<SysMenu> menuList2= new ArrayList<SysMenu>();
		for (SysMenu sysMenu2 : menuList) {
			if(sysMenu2.getParentid() == parentId){
				menuList2.add(sysMenu2);
			}
		}
		for (SysMenu sysMenu : menuList2) {
			JsTree j = new JsTree();
			j.setId(sysMenu.getMenuid());
			j.setText(sysMenu.getMenucnname());
			j.setIcon(sysMenu.getIcon());
			State state = new State();
			state.setOpened(true);
			j.setState(state);
			List<JsTree> child = GetSysMenuList2(j.getId(), menuList);
			if(sysMenu.getLevel() == 2) {
				if(child.isEmpty())
					continue;
			}
			if(sysMenu.getLevel() == 3 && ( "page".equalsIgnoreCase(sysMenu.getMenutype()) 
					|| "group".equalsIgnoreCase(sysMenu.getMenutype())  )) {
				if(child.isEmpty())
					continue;
			}
			j.setChildren(child);
			list.add(j);
		}
		return list;
	}
	

	/**
	 * 生成json的菜单
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private String SetMenu(StringBuilder sb, List<JsTree> treeList) {
		int num = 0;
		for (JsTree tree : treeList) {
			if(num != 0){
				sb.append(",");
			}
			sb.append("{'id':" + tree.getId() +",'text':'" + tree.getText()+ "','state':{'opened':true,'selected':false},'icon':'" + (tree.getIcon() == null ? "none" : tree.getIcon()) + "'");
					if(tree.getChildren().size() > 0){
						sb.append(",'children':[");
						SetMenu(sb,tree.getChildren());
						sb.append("]");
					}
			sb.append("}");
			num++;
		}
		return sb.toString();
	}

	
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	public String getButtonDataJson(){
		SysMenu bloBs = new SysMenu();
		List<SysMenu> menuList = sysMenuService.selectMenus(bloBs);
		List<SysMenu> menuList2 = sysMenuService.selectFirstMenu();
		List<JsTree> treeList = new ArrayList<JsTree>();

		for (SysMenu sysMenu : menuList2) {
			JsTree j = new JsTree();
			j.setId(sysMenu.getMenuid());
			j.setText(sysMenu.getMenucnname());
			j.setIcon(sysMenu.getIcon());
			State state = new State();
			state.setOpened(true);
			j.setState(state);
			List<JsTree> child = GetSysMenuList2(j.getId(), menuList);
			if(child.isEmpty())
				continue;
			j.setChildren(child);
			treeList.add(j);
		}
		StringBuilder sb = new StringBuilder();
		sb.append("{'id':'root','text':'权限按钮事件','state':{'opened':true},'icon':'fa fa-bars','children':[");
		SetMenu(sb, treeList);
		sb.append("]}");
		return sb.toString();
	}
	
	/**
	 * 添加角色所选择菜单
	 */
	@RequestMapping(value="addRoleRelevancePer")
	@Transactional(value="txManager")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	public Map<String, Object> addRoleRelevancePer(HttpServletRequest request, @RequestParam("roleId") Integer roleId){
		Map<String, Object> map = new HashMap<String, Object>();
		//角色 需要设置的菜单
		String menuIDS = request.getParameter("menuIDS");
		//当前角色已有的 菜单
		List<SysMenu> menuList = sysRoleService.selectMenusByRoleId(roleId);
		
		List<String> addList = this.getAddMenuIdList(menuIDS, menuList);
		List<String> delList = this.getDeletedMenuIdList(menuIDS, menuList);
		
		delPageMenu(delList, roleId, map);
		addPageMenu(addList, roleId, map);
		
		//更新初始化的map
		reloadRoleAndMenu();
		map.put("success", true);
		return map;
	}
	/**
	 * 添加角色子菜单关系 
	 * @param menuIdList
	 * @param roleId
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private void addPageMenu(List<String> menuIdList, Integer roleId, Map<String, Object> map){
		List<String> checkedList = new ArrayList<String>();
		List<String> idList = new ArrayList<String>();  //所有要插入 数据的menuId的值， 并且不能重复
		idList.addAll(menuIdList);
		for(String menuId : menuIdList) {
			this.completeIdList(menuId, idList, checkedList);
		
		}
		for(String menuId : idList) {
			sysRoleService.addRoleRelevancePer(roleId, Integer.valueOf(menuId));
		}
		map.put("checked", checkedList);
	}
	
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private void completeIdList(String menuId, List<String> idList, List<String> checkedList){
		List<SysMenu> childList = sysRoleService.selectChildMenusByPageMenuId(Integer.valueOf(menuId));
		if(!childList.isEmpty()){
			for(SysMenu menu : childList){
				if(!"page".equalsIgnoreCase(menu.getMenutype()) && !"group".equalsIgnoreCase(menu.getMenutype())) {
					if(!idList.contains(menu.getMenuid().toString())) {
						idList.add(menu.getMenuid().toString());
						checkedList.add(menu.getMenuid().toString());
					}	
				}
//				completeIdList(menu.getMenuid().toString(), idList, checkedList);
			}
		}
	}
	
	/**
	 * 删除 角色菜单关系 
	 * 删除 一级或二级节点，并删除 
	 * @param menuIdList
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private void delPageMenu(List<String> menuIdList, Integer roleId, Map<String, Object> map) {
		//子菜单也要删除
		List<String> uncheckedList = new ArrayList<String>();
		
		List<String> idList = new ArrayList<String>();  //所有要插入 数据的menuId的值， 并且不能重复
		idList.addAll(menuIdList);
		for(String menuId : menuIdList) {
			this.completeIdList(menuId, idList, uncheckedList);
		
		}
		
		for(String menuId : idList) {
			sysRoleService.deletePerPageByRoleIdAndMenuId(Integer.valueOf(menuId), roleId);
		}
		map.put("unchecked", uncheckedList);
	}
	
	
	//数据里存在,则不需要增加
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private List<String> getAddMenuIdList(String menudIds, List<SysMenu> menuList){
		List<String> addList = new ArrayList<String>();
		String[] menus = menudIds.split(",");
		for(String menuId : menus) {
			boolean flag = false;
			if(org.apache.commons.lang.StringUtils.isNotBlank(menuId)) {
				for( int i = 0; i < menuList.size() ; i++ ){
					SysMenu menu = menuList.get(i);
					if(menuId.equals(menu.getMenuid().toString())) {
						flag = true;//存在 数据库里,表示不需要 增加
						break;
					}
				}
				if(!flag)
					addList.add(menuId);
			}
		}
		return addList;
	}
	
	//得到需要 删除的 
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private List<String> getDeletedMenuIdList(String menudIds, List<SysMenu> menuList){
		List<String> delList = new ArrayList<String>();
		String[] menus = menudIds.split(",");
		for(SysMenu menu : menuList) {
			boolean flag = false;
			String menuId = menu.getMenuid().toString();
			for(int i = 0; i < menus.length; i++) {
				if(menuId.equals(menus[i])) {
					flag = true;  //数据里 存在 要插入的，则不必删除 
					break;
				}
			}
			if(!flag) 
				delList.add(menu.getMenuid().toString());
		}
		return delList;
	}
	
	/**
	 * 当用户 超级管理员 修改 菜单时, 需要 同步 到map中
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	public void reloadRoleAndMenu(){
		//清空所有的菜单和角色
		Iterator<Entry<String, List<SysMenu>>> it = SpringInitConfig.menuMap.entrySet().iterator();  
        while(it.hasNext()){  
           it.next();  
           it.remove();
        }  
        
        List<SysRole> roleList = sysRoleService.selectRoleAndMenuList();
		if( !roleList.isEmpty() ) {
			for(SysRole role : roleList) {
				SpringInitConfig.roleMap.put(role.getRoleId().toString(), role);
				SpringInitConfig.menuMap.put(role.getRoleId().toString(), role.getMenuList());
			}
			
		}
		//下面代码 可以 注释
		for(String key : SpringInitConfig.menuMap.keySet() ){
			System.out.println( "==================================================" );
			SysRole role = SpringInitConfig.roleMap.get(key);
			System.out.print( "角色 :"+ role.getRoleName()  +" 菜单>>>");
			List<SysMenu> menuList = SpringInitConfig.menuMap.get(key);
			if(!menuList.isEmpty()) {
				for(SysMenu menu : menuList) {
					System.out.println(  menu.getMenucnname() );
				}
			}
		}
        
	}
	
	
	/**
	 * 添加角色所选择按钮
	 */
	@RequestMapping(value="addButtonPerByRole")
	@Transactional(value="txManager")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	public Map<String, Object> addButtonPerByRole(HttpServletRequest request, @RequestParam("roleId") Integer roleId){
		Map<String, Object> map = new HashMap<String, Object>();
		//角色 需要设置的菜单
		String menuIDS = request.getParameter("menuIDS");
		//当前角色已有的 菜单 (查  大于 2级的菜单)
		List<SysMenu> menuList = sysRoleService.selectMenusLevelLT2ByRoleId(roleId);
		
		List<String> addList = this.getAddMenuIdList(menuIDS, menuList);
		List<String> delList = this.getDeletedMenuIdList(menuIDS, menuList);
		
		delButtonMenu(delList, roleId);
		addButtonMenu(addList, roleId, map);
		
		//更新初始化的map
		reloadRoleAndMenu();
		map.put("success", true);
		return map;
	}
	
	/**
	 * 添加 角色菜单  三级 菜单 ，先判断父菜单 是否存在， 若不存在，则新增 父菜单
	 * @param menuIdList
	 * @param roleId
	 * @param map
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private void addButtonMenu(List<String> menuIdList, Integer roleId, Map<String, Object> map){
		List<String> checked = new ArrayList<String>();
		for(String menuId : menuIdList) {
			SysMenu menu = sysMenuService.selectByMenuId(Integer.valueOf(menuId));
			if(menu.getLevel() > 2) {
				Integer parentId = menu.getParentid();
				if(parentId != null) {
					Integer count = sysRoleService.selectReByMenuIdAndRoleId(parentId, roleId);
					if(count == 0) {
						//添加 父菜单
						sysRoleService.addRoleRelevancePer(roleId, parentId);
						checked.add(parentId.toString());
					}
				}
				sysRoleService.addRoleRelevancePer(roleId, Integer.valueOf(menuId));
			} 
		}
		map.put("checked", checked);
	}
	
	
	/**
	 * 删除  角色菜单  三级菜单(大于二级)
	 * @param menuIdList
	 * @param roleId
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	private void delButtonMenu(List<String> menuIdList, Integer roleId) {
		for(String menuId : menuIdList) {
			SysMenu menu = sysMenuService.selectByMenuId(Integer.valueOf(menuId));
			if(menu.getLevel() > 2) {
				//直接删除
				sysRoleService.deletePerPageByRoleIdAndMenuId(Integer.valueOf(menuId), roleId);
			} 
		}
	}
	
	
	/**
	 * 查询角色已关联用户
	 */					  
	@RequestMapping(value="selectUserByRoleId")
	@ResponseBody
	@RoleLimit(pid = "sysRole", mid = "selectUserByRoleId")
	public ModelAndView selectUserByRoleId(HttpServletRequest request,Integer pageNo,Integer pageSizeSelect){
		ModelAndView mv = new ModelAndView("sysrole/roleUser");
		String parameter = request.getParameter("RoleID");
		mv.addObject("roleId", parameter);
		return mv;
	}
	
	@RequestMapping(value="loadRoleUsers")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	public String loadRoleUsers(HttpServletRequest request,Integer pageNo,Integer pageSizeSelect, Model model){
		String parameter = request.getParameter("RoleID");
		String userName = request.getParameter("UserName");
		String employeeNo = request.getParameter("EmployeeNo");
		SysUser sysUser = new SysUser();
		sysUser.setUsername(userName);
		sysUser.setEmployeeno(employeeNo);
		if(StringUtils.isNotBlank(parameter)){
			Integer roleId = Integer.valueOf(parameter);
			PagedResult<SysUser> pagedResult = sysRoleService.selectUserByRoleId(roleId,pageNo,pageSizeSelect,userName,employeeNo);
			if(pagedResult != null){
			    Helper.countStartPageAndEndPage(pagedResult);
			    model.addAttribute("list", pagedResult);
			}
		}
		return "sysrole/user_list";
	}
	
	/**
	 * 删除角色关联的用户
	 */					  
	@RequestMapping(value="deleteUserByRole")
	@ResponseBody
	@Transactional(value="txManager")
	@RoleLimit(pid = "sysRole", mid = "deleteUserByRole")
	public Integer deleteUserByRole(HttpServletRequest request){
		String roleID = request.getParameter("roleId");
		String userID = request.getParameter("userId");
		Integer data = 0;
		if(StringUtils.isNotBlank(roleID) && StringUtils.isNotBlank(userID)){
			Integer roleId = Integer.valueOf(roleID);
			Integer userId = Integer.valueOf(userID);
				data = sysRoleService.deleteUserByRole(roleId,userId);
		}
		return data;
	}
}
