var menuRId,rootId='9999999999',isAdd=false,gridLeft,gridRight,firstGroupId,detailWindow,detailWindowShow=$.uniqueId() ,menuTree,proName = window.location.pathname.split("/")[1],sysUrl = "http://"+window.location.host+"/"+proName;

$(function() {
//	$.startSync();
//	LoginAction.getCurrentUser(function(user){
//		if(!sysUrl && !top.MainPage){
//			if(!user || !user.isSuper){
//				document.write("<span style='color:red;font-size:14px;'>页面加载超时,请先登录！</span>");
//				return;
//			}
//		} 
//		sysUrl = "http://"+window.location.host+"/"+top.window.location.pathname.split("/")[1];
//		
//	}); 
//	$.endSync();
	initTree();
	initGrid();
});

function initTree(){
	menutree  = $('#rightTree').tree({
	        url : 'commonMenuGroupAction!getAllCommonMenu.do?menuId=root',
	        checkbox:true,
	        lines:false,
			animate: false, 
	    	multiple:false,
	    	editable:false,
	    	border:false,
	    	cascadeCheck:false,
	    	onClick:function(node){
	    		if(node.checked){
	    			$('#rightTree').tree('uncheck', node.target);
	    		}else{
	    			$('#rightTree').tree('check', node.target);
	    		}
	    	},
	    	onCheck:function(node,checked){
		 		if(checked){
		 			var parentNode = $("#rightTree").tree('getParent',node.target);
		 			treeCheck(parentNode);
		 		}
		 	 },
	        onBeforeLoad:function(node,data){
				if(node) $(this).tree('options').url = 'commonMenuGroupAction!getAllCommonMenu.do?menuId=' + node.id; 
			},
			onDblClick:function(node){
			 	$(this).tree(node.state === 'closed' ? 'expand' : 'collapse', node.target);  
			},
			onLoadSuccess:function(node, data){
				$(this).tree('expandAll',node && node.target ? node.target : null);
			},
	        loadFilter: function(data,parent){ 
	 			return $(this).tree('getRoot') ? data : [{text:'权限菜单',id:rootId,children:data}]; 
			} 
	});
}
function treeCheck(parentNode){
	if(parentNode){
			parentNode.checked = true;
			parentNode._checked = true;
			parentNode.checkState = "checked";
			$(parentNode.target).children("span").last().prev().addClass("tree-checkbox1").removeClass("tree-checkbox0");
	  		parentNode = $("#rightTree").tree('getParent',parentNode.target);
	        return treeCheck(parentNode);
	}
}
function goMenuGroupDetail(t){
	var record = $("#searchGrid").datagrid('getData').rows[t];
	if(record && record.groupId){
		 top.$.createWin({
			 id		:	$.uniqueId(),
			 title	: 	'权限菜单',
			 width	:  	800,
			 height	: 	500,
			 onClose:   initGrid,
			 url	:	sysUrl+"/frame/system/systemMenuDetail.jsp?roleId="+record.groupId
		 });
	}
}

function selectAllNode(){ 
	var roots=menutree.tree('getRoots'),children,i,j;
	for(i=0;i<roots.length;i++){
		menutree.tree('check', roots[i].target);
	    children=menutree.tree('getChildren',[].push(roots[i].target));
	    for(j=0;j<children.length;j++){
	    	menutree.tree('check', children[j].target);
	    };
	}
}

function disSelectAllNode(){
	var roots=menutree.tree('getRoots'),children,i,j;
    for(i=0;i<roots.length;i++){
    	menutree.tree('uncheck', roots[i].target);
    	children=menutree.tree('getChildren',[].push(roots[i].target));
    	for(j=0;j<children.length;j++){
    		menutree.tree('uncheck', children[j].target);
    	}
    }
}

function getAllCheckedNodes(){
	var nodes = menutree.tree('getChecked', ['checked','indeterminate']);
	var selRows = $('#searchGrid').datagrid('getSelected');
	var ary = [],aryrt = [];
	$.each(nodes,function(index,node){
		if(node.id != rootId) {
			ary.push(node.id);
			aryrt.push(node.operateRight || '_');
		}
	});
	
	if(ary.length<=0){
		top.$.dlg.alertInfo('请先勾选权限菜单!');
		return;
	}

	
	top.$.dlg.confirm('确定要保存权限吗?',function(){ 
        $.ajax({
	         type:'post',
	         url : 'commonMenuGroupAction!updateCommonMenuGroup.do',
	         data:{
	        	groupId	 :	selRows.groupId,
	        	menuIds	 :	ary.join(','),
	        	rightIds :	aryrt.join(',')
	         },
	         success : function(result){
		        if(result==1){
		        	top.$.dlg.alertInfo('保存成功!');
		        }
	        }
	     });
	});
	
}

function addRoleGroup(title){
	if (!title){
		isAdd=true;
		title="";
	}else{
		isAdd=false;
	}
	detailWindow = top.$.createWin({
		 id		:	$.uniqueId(),
		 title	: 	'编辑权限组',
		 width	:  	260,
		 height	: 	130,
		 url	:	sysUrl+'/frame/system/systemManagerUpdate.jsp?title='+encodeURI(title),
		 buttons:[{
				text:$.fn.textbox.defaults.ok,
				handler:saveRightWin
		}]
	 });
}

function saveRightWin(){
	var frame	=	top.$("#"+detailWindow).children('iframe')[0];
	var jq		=	(frame.contentWindow||frame.window)["$"];
	var textboxs	=	jq('.easyui-textbox');
	var rightName   = 	jq(textboxs[0]).textbox('getValue') ;
	
	if(!rightName)	return top.$.dlg.alertInfo('请填写权限组名称！ ');
	
	var flag = false;
	var selRows = $('#searchGrid').datagrid('getData');  
	if(selRows && selRows.rows && selRows.rows.length){
		$.each(selRows.rows,function(idx,obj){
		 	var name=obj.roleName;
		 	if(rightName == name){
		 		 flag = true;
		 		 return false;
		 	}
		});
	}
	
	if(flag) return top.$.dlg.alertInfo('权限组名重复！');
	if(!isAdd){
			if(menuRId && menuRId.id){
				$.ajax({
			        type :'post',
			        url  :'commonMenuGroupAction!saveOrUpdateCommonGroup.do',
			        data : {
			        	groupId  : menuRId.id,
			        	groupName:rightName,
			        	add:  false
			        },
			        success : function(result){
			        	initGrid();
			        	top.$.dlg.alertInfo('操作成功！ ');
			        	top.$("#"+detailWindow).dialog("close");
			        }
			    });
				
			}
	}else{
		$.ajax({
	        type :'post',
	        url  :'commonMenuGroupAction!saveOrUpdateCommonGroup.do',
	        data : {
	        	groupId  : "",
	        	groupName:rightName,
	        	add:  true
	        },
	        success : function(result){
	        	initGrid();
	        	top.$.dlg.alertInfo('操作成功！ ');
	        	top.$("#"+detailWindow).dialog("close");
	        }
	    });
	}
}

function modiftRight(){
	var selRows = $('#searchGrid').datagrid('getSelected');  
	if(selRows===null){
		 top.$.dlg.alertInfo('请先选择一行! ');
		 return;
	}else{
		 menuRId = {
					id:selRows.groupId,
					name:selRows.groupName
		 };
		 addRoleGroup(selRows.groupName);
	}
}

function deleteRight(){
	var selRows = $('#searchGrid').datagrid('getSelected');
	if(selRows===null){
		 top.$.dlg.alertInfo('请先选择一行! ');
		 return;
	}else{
		top.$.dlg.confirm('你确认要删除吗?',function(){
			 $.ajax({
			        type:'post',
			        url : 'commonMenuGroupAction!deleteCommonGroup.do?groupId='+selRows.groupId,
			        async:false,
			        success : function(result){
				        if(result==1){
				        	initGrid();
				        }
			        }
			  });
		});
	}
}  

//修改之后的方法
function initGrid(){
	$("#searchGrid").datagrid({
		singleSelect:true,
		pagination:false,
		url:'commonMenuGroupAction!getCommonGroup.do',
		border:false,
		columns : [[ 
		{
			title: "",
			field: "groupId",
			hidden:true
		},
		{
			title: "权限组列表",
			field: "groupName",
			sortable: false,
			align:'left',
			width:109
		},{
			title: "成员列表",
			field: "userCount",
			sortable: false,
			align:'left',
			width:107,
			formatter:function(value,record,num){
				return "<a href='javascript:goMenuGroupDetail("+num+");' class='ahref'> 成员列表("+(value||0)+")</a>";
			}
		}] ],
		onLoadSuccess:function(data){
			if(data && data.rows){
				$("#searchGrid").datagrid("selectRow",0);
				setTimeout(function(){
					var selRows = $('#searchGrid').datagrid('getSelected');
					checkRoleTree(selRows.groupId);
				},500);
			}
		},
		onClickRow:function(index,row){
			checkRoleTree(row.groupId);
		}
	});
}
 

function checkRoleTree(rId){
	var tree =  menutree;
	var child  =tree.tree('getChildren');
	tree.tree('expandAll');
	$.each(child,function(m,o){
   		tree.tree('uncheck',o.target);
   	});	
	
	$.ajax({
	        type:'post',
	        url : 'commonMenuGroupAction!getCommonMenuGroup.do?groupId='+rId,
	        async:false,
	        success : function(result){
		        setchecked(result);
	        }
	});
}


function setchecked(listIds){
	var tree =  $('#rightTree');
    tree.tree('expandAll',$("#rightTree").tree('getRoot').target);
    var child  =tree.tree('getChildren');
   
    $.each(child,function(m,o){
   		tree.tree('uncheck',o.target);
   	});
    if(child && child.length && listIds.length ){
   		$.each(listIds,function(i,obj){
   			$.each(child,function(m,o){
   					if(obj.menuId == o.id ){
   						tree.tree('check',o.target);
   					} 
   			});
   		});
    } 
}