var orgTreeData = [];
var roleTreeData = [];
var deleteRoleGroupId = '';
var checkRoleId;
var checkRoleSuperId;
var checkRoleName;

//添加编辑子部门名称(新增修改角色/角色组名称)验证
function childDepartValid(data){
	var chose = data.data.chose;
	if( $(chose).val() == '' ){
		$(chose).addClass("error");
		$(chose).next().text('请输入'+data.data.name+'名称').show();
		return false;
	}else{
		if( $(chose).val().length > 30 ){
			$(chose).addClass("error");
			$(chose).next().text(data.data.name+'名称最多可输入30个字符').show();
			return false;
		}else{
			$(chose).removeClass("error");
			$(chose).next().hide();
			return true;
		}
	}
};

//获取下级部门
function getChildOrgData(parentId,dataArray){
	$.ajax({
		url:'/org/findNodeByParentIdNumber',
		type:'get',
		async:false,
		data:{
			parentId:parentId
		},
		success:function(data){
			for( var i=0;i<data.length;i++  ){
				var orgChildObj = {};
				orgChildObj.title = data[i].name;
				orgChildObj.id = data[i].id;
				if( data[i].isParent ){
					orgChildObj.children = [];
					getChildOrgData(data[i].id,orgChildObj.children);
				}
				dataArray.push(orgChildObj)
			};
			i = null;
		},
		error:function(status){
			new $.zui.Messager('获取下级组织机构错误'+status,{type : 'danger',time : 1500}).show();
		}
	})
};

//获取根组织机构
function getRootOrgData(){
	$.ajax({
		url:'/org/findRootOrgTreeNodeNumber',
		type:'get',
		async:false,
		data:{},
		success:function(data){
			for( var i=0;i<data.length;i++ ){
				var orgRootObj = {};
				orgRootObj.title = data[i].name;
				orgRootObj.id = data[i].id;
				orgRootObj.open = true;
				if( data[i].isParent ){
					orgRootObj.children = [];
					getChildOrgData(data[i].id,orgRootObj.children);
				}
				console.log(orgRootObj, 111)
				orgTreeData.push(orgRootObj);
			};
			i = null;
		},
		error:function(status){
			new $.zui.Messager('获取根组织机构错误'+status,{type : 'danger',time : 1500}).show();
		}
	});
};

//获取角色组
function findGroupRole(){
	$.ajax({
		url:'/role/findGroupRole',
		type:'get',
		async:false,
		data:{},
		success:function(data){
			var toGroupOption = '';
			for( var i=0;i<data.length;i++ ){
				toGroupOption += '<option value="'+data[i].id+'">'+data[i].name+'</option>'
			};
			i = null;
			$("#toGroup").empty().append(toGroupOption)
		},
		error:function(status){
			new $.zui.Messager('获取角色组信息错误'+status,{type:'danger'}).show();
		}
	})
};

//角色树点击事件
function roleTreeClick(event, treeId, treeNode) {
    if( !treeNode.firstCell ){//点击的是角色
    		checkRoleId = treeNode.id;
    		checkRoleName = treeNode.name;
	    	$(".yk_orgContent").load('/org/memberContent',function(){
	    		$(".yk_orgContentTitle span").text(treeNode.name);
	    		if( treeNode.name == '超级管理员' ){
	    			$(".yk_orgContentTitle button,.roleOperateBtn").remove();
	    		}else if( treeNode.name == '子管理员' ){
				$(".yk_orgContentTitle button,.warningtip").remove();
	    		}else if( treeNode.name == '业务超管' ){
	    			$(".roleOperateBtn,.warningtip").remove();
	    		}else{
	    			$(".warningtip").remove();
	    		}
			});
    }else{//点击的是角色组
    		$.fn.zTree.getZTreeObj("roleTree").expandNode(treeNode);
    }
};

//鼠标移入角色组添加显示编辑按钮
function addRoleHoverDom(treeId, treeNode){
	if( !treeNode.firstCell ){
		return;
	};
	if( treeNode.defaults ){
		return
	};
	var roleAObj = $("#" + treeNode.tId + "_a");
	if ($("#editRoleBtn_"+treeNode.id).length>0){
		return;
	};
	var roleEditStr = "<span id='editRoleBtn_space_" +treeNode.id+ "' > </span>"
		+ "<button type='button' class='editRoleBtn' id='editRoleBtn_" + treeNode.id
		+ "' title='"+treeNode.name+"' onfocus='this.blur();'></button>";
		roleAObj.append(roleEditStr);
	var editRoleBtn = $("#editRoleBtn_"+treeNode.id);
	if (editRoleBtn) {
		editRoleBtn.bind("click", function(){
			$("#myModal-addRoleGroup .modal-title").text('编辑角色组');
			$(".addRoleGroupSave").hide();
			$(".updateRoleGroupSave,.deleteRoleGroupSave").show();
			deleteRoleGroupId = treeNode.id;
			$("#myModal-addRoleGroup").modal('show');
			$("#roleGroupName").removeClass('error').val( $(this).parents("a").attr("title") ).next().hide()
			return false;
		});
	}
};

//鼠标移出角色组移除编辑按钮
function removeRoleHoverDom(treeId, treeNode){
	$("#editRoleBtn_"+treeNode.id).unbind().remove();
	$("#editRoleBtn_space_" +treeNode.id).unbind().remove();
};

//左侧角色树的ztree配置项
var roleSetting = {
	callback: {
		onClick: roleTreeClick
	},
	view: {
		addHoverDom: addRoleHoverDom,
		removeHoverDom: removeRoleHoverDom,
		showLine:false,
		autoCancelSelected:false
	}
};

//获取角色树数据
function getRoleData(){
	$.ajax({
		url:'/role/do_list',
		type:'get',
		async:false,
		data:{
			page:1,
			rows:300
		},
		success:function(data){
			 for( var i=0;i<data.rows.length;i++ ){
				 var roleObj = {};
				 roleObj.name = data.rows[i].name;
				 roleObj.id = data.rows[i].id;
				 roleObj.firstCell = true;
				 roleObj.children = [{}];
				 if( i==0 ){
					 //默认角色组始终展开并不可编辑
					 roleObj.open = true;
					 roleObj.defaults = true;
				 };
				 if( data.rows[i].childList!=undefined && data.rows[i].childList.length>0 ){
					 for( var j=0;j<data.rows[i].childList.length;j++ ){
						 if( data.rows[i].childList[j].name=='超级管理员' ){
							 //checkRoleId = data.rows[i].childList[j].id;//这里重置checkRoleId会导致再次编辑角色时id混乱,如果需要是超管的id,重新使用checkRoleSuperId的值即可
							 checkRoleSuperId = data.rows[i].childList[j].id;
						 };
						 //把之前右侧显示的角色所属的角色组展开
						 if( data.rows[i].childList[j].id == checkRoleId ){
							 roleObj.open = true;
						 };
						 roleObj.children.push({
							 name:data.rows[i].childList[j].name,
							 id:data.rows[i].childList[j].id,
							 firstCell:false
						 })
					 };
					 j = null;
				 };
				 roleTreeData.push(roleObj)
			 };
			 i = null;
		},
		error:function(status){
			new $.zui.Messager('获取角色时错误'+status,{type : 'danger',time : 1500}).show();
		}
	})
};

//刷新左侧组织树
function refreshDepartTree(id){
	orgTreeData = [];
	getRootOrgData();
	$('#orgTree').data('zui.tree').reload(orgTreeData);
	//刷新之后选中之前选中的组织
	for( var i=0;i<$('#orgTree li').length;i++ ){
		if( $('#orgTree li').eq(i).attr("data-id")==id ){
			$('#orgTree li').eq(i).find("span").addClass("check");
		}else{
			$('#orgTree li').eq(i).find("span").removeClass("check");
		}
	};
	i = null;
};

//设置原先选中的角色选中状态
function setSelectNode(){
	var filter = function(node){
		return (node.id == checkRoleId);
	};
	$.fn.zTree.getZTreeObj("roleTree").selectNode($.fn.zTree.getZTreeObj("roleTree").getNodesByFilter(filter, true));
};

//刷新左侧角色树
function refreshUserTree(id){
	$("#roleTree").empty();
	roleTreeData = [];
	getRoleData();//其中把原先选中的角色所在的角色组设置展开
	$.fn.zTree.init($("#roleTree"),roleSetting,roleTreeData);
	setSelectNode();//其中设置原先选中的角色选中状态
};

$(function(){
	if( $(".yk_roleBtn button").length<=0 ){
		$("#roleTree").css("top","130px");
	}
	var permissionTreeData = [];
	//对'系统权限'递归处理
	function loopLowerPermission(permissionArray,data){
		for( var j=0;j<data.length;j++ ){
			var permissionArrayObj = {};
			permissionArrayObj.name = data[j].cname;
			permissionArrayObj.id = data[j].id;
			permissionArrayObj.checked = false;
			if( data[j].childPermission!=undefined && data[j].childPermission.length>0 ){
				permissionArrayObj.children = [];
				loopLowerPermission(permissionArrayObj.children,data[j].childPermission)
			}
			permissionArray.push(permissionArrayObj)
		};
		j = null;
	};
	//获取'选择权限'树
	function getPermissionData(){
		$.ajax({
			url:'/permission/findPermisionTree',
			type:'get',
			async:false,
			data:{},
			success:function(data){
				for( var i=0;i<data.length;i++ ){
					var permissionObj = {};
					permissionObj.name = data[i].cname;
					permissionObj.id = data[i].id;
					permissionObj.checked = false;
					if( data[i].childPermission!=undefined && data[i].childPermission.length>0 ){
						permissionObj.children = [];
						loopLowerPermission(permissionObj.children,data[i].childPermission);
					};
					permissionTreeData.push(permissionObj)
				};
				i= null;
			},
			error:function(status){
				new $.zui.Messager('获取权限树信息错误'+status,{type:'danger'}).show();
			}
		})
	};
	getRootOrgData();
	//初始化组织机构树
	$('#orgTree').tree({data: orgTreeData});
	getRoleData();
	//初始化角色树
	$.fn.zTree.init($("#roleTree"),roleSetting,roleTreeData);
	getPermissionData();
	//初始化'权限选择树'
	var permissionSetting = {
		check: {
			enable: true,
			chkStyle: "checkbox",
			chkboxType: { "Y": "ps", "N": "s" }
		},
		view:{
			showLine:false,
			autoCancelSelected:false
		}
	};
	$.fn.zTree.init($("#permissionTree"),permissionSetting,permissionTreeData);
	//点击选择部门加载右侧区域
	$('#orgTree').on('click',"li span",function(){
		var $that = $(this);
		//if( !$(this).hasClass("check") ){
			rightDepartmentId = $that.parent().attr("data-id");
			rightDepartmentTitle = $that.text().split('（')[0];
			$(".yk_orgContent").load('/org/departmentContent',function(){
				backTop('.yk_orgContent');
				$(".yk_orgContentTitle span").text($that.text().split('（')[0]);
				if( $that.parents("li").attr("data-id")=='1' ){//是'长安银科'
					$(".yk_updateDepartment").remove();
					$(".yk_syncDepartment").remove();
				}
			});
			$('#orgTree li span').removeClass("check");
			$that.addClass("check")
		//}
	});
	$('#orgTree li span:first').click();
	//点击'组织机构',右侧默认显示长安银科,直接用上面的 click
	$(".yk_groupBtn .organization").click(function(){
		if( $("#orgTree").is(":hidden") ){
			$("#roleTree,.yk_roleBtn").hide();
			$("#orgTree").show();
			$(".yk_groupBtn div").removeClass("check");
			$(this).addClass("check");
			$('#orgTree li span:first').click();
		}
	});
	//点击'角色',右侧默认显示超级管理员
	$(".yk_groupBtn .role").click(function(){
		if( $("#roleTree").is(":hidden") ){
			checkRoleName = '超级管理员';
			$("#orgTree").hide();
			$("#roleTree,.yk_roleBtn").show();
			$(".yk_groupBtn div").removeClass("check");
			$(this).addClass("check");
			checkRoleId = checkRoleSuperId;
			$(".yk_orgContent").load('/org/memberContent',function(){
		    		$(".yk_orgContentTitle button,.roleOperateBtn").remove();
		    		setSelectNode();//设置选中超级管理员
			});
		}
	});
	//新增角色组
	$(".yk_roleBtn").on('click','.yk_addRoleGroup',function(){
		$("#myModal-addRoleGroup .modal-title").text('新增角色组');
		$(".addRoleGroupSave").show();
		$(".updateRoleGroupSave,.deleteRoleGroupSave").hide();
		$("#myModal-addRoleGroup").modal("show");
		$("#roleGroupName").removeClass('error').val('').next().hide()
	});
	$("#roleGroupName").keyup({'chose':'#roleGroupName','name':'角色组'},childDepartValid);
	$("#roleGroupName").change({'chose':'#roleGroupName','name':'角色组'},childDepartValid);
	//确认新增角色组
	$(".addRoleGroupSave").click(function(){
		if( !childDepartValid({'data':{'chose':'#roleGroupName','name':'角色组'}}) ){
			return
		};
		$.ajax({
			url:'/role/do_add',
			type:'post',
			data:{
				name:$("#roleGroupName").val()
			},
			success:function(data){
				if( data.success ){
					new $.zui.Messager('新增角色组成功',{type:'success'}).show();
					//重新加载左侧角色树
					refreshUserTree();
				}else{
					new $.zui.Messager('新增角色组失败:'+data.msg,{type:'danger'}).show();
				}
			},
			error:function(status){
				new $.zui.Messager('新增角色组错误'+status,{type:'danger'}).show();
			}
		});
		$("#myModal-addRoleGroup").modal("hide");
	});
	//确认修改角色组
	$(".updateRoleGroupSave").click(function(){
		if( !childDepartValid({'data':{'chose':'#roleGroupName','name':'角色组'}}) ){
			return
		};
		$.ajax({
			url:'/role/do_update',
			type:'post',
			data:{
				name:$("#roleGroupName").val(),
				id:deleteRoleGroupId
			},
			success:function(data){
				if( data.success ){
					new $.zui.Messager('修改角色组成功',{type:'success'}).show();
					refreshUserTree();
				}else{
					new $.zui.Messager('修改角色组失败:'+data.msg,{type:'danger'}).show();
				}
			},
			error:function(status){
				new $.zui.Messager('修改角色组错误'+status,{type:'danger'}).show();
			}
		});
		$("#myModal-addRoleGroup").modal("hide");
	});
	//删除角色组
	$(".deleteRoleGroupSave").click(function(){
		$.ajax({
			url:'/role/do_delete',
			type:'post',
			data:{
				id:deleteRoleGroupId
			},
			success:function(data){
				 if( data.success ){
					 new $.zui.Messager('删除角色组成功',{type:'success'}).show();
					 refreshUserTree();
				 }else{
					 new $.zui.Messager('删除角色组失败:'+data.msg,{type:'danger'}).show();
				 }
			},
			error:function(status){
				new $.zui.Messager('删除角色组错误:'+status,{type:'danger'}).show();
			}
		});
		$("#myModal-addRoleGroup").modal("hide");
	});


	//新增角色
	$(".yk_roleBtn").on('click','.yk_addRole',function(){
		findGroupRole();
		$("#myModal-addRole .modal-title").text('新增角色');
		$(".updateRoleSave,.deleteRoleSave").hide();
		$(".addRoleSave").show();
		$("#toGroup").removeClass('error').next().hide();
		$("#roleName").removeClass('error').val('').next().hide();
		//取消所有权限节点选中状态
		$.fn.zTree.getZTreeObj("permissionTree").checkAllNodes(false);
		$("#myModal-addRole").modal("show");
		$('#myModal-addRole tr').eq(1).removeClass('hide');
	});
	$("#roleName").keyup({'chose':'#roleName','name':'角色'},childDepartValid);
	$("#roleName").change({'chose':'#roleName','name':'角色'},childDepartValid);
	$("#toGroup").change(function(){
		if( $("#toGroup").val()==null || $("#toGroup").val()==undefined || $("#toGroup").val()=='' ){
			$("#toGroup").addClass('error').next().show();
		}else{
			$("#toGroup").removeClass("error").next().hide();
		}
	});
	//确认新增角色
	$(".addRoleSave").click(function(){
		if( !childDepartValid({'data':{'chose':'#roleName','name':'角色'}}) ){
			return
		};
		if( $("#toGroup").val()==null || $("#toGroup").val()==undefined || $("#toGroup").val()=='' ){
			$("#toGroup").addClass('error').next().show();
			return;
		};
		var checkedPermissionNodes = $.fn.zTree.getZTreeObj("permissionTree").getCheckedNodes(true);
		if( checkedPermissionNodes.length<=0 ){
			new $.zui.Messager('请选择权限',{type:'danger'}).show();
			return;
		};
		var postRolePermissions = {};
		postRolePermissions.name = $("#roleName").val();
		postRolePermissions['parent.id'] = $("#toGroup").val();
		for( var i=0;i<checkedPermissionNodes.length;i++ ){
			postRolePermissions['permissions['+i+'].id'] = checkedPermissionNodes[i].id;
		};
		i = null;
		$.ajax({
			url:'/role/do_add',
			type:'post',
			data:postRolePermissions,
			success:function(data){
				if( data.success ){
					new $.zui.Messager('新增角色成功',{type:'success'}).show();
					refreshUserTree();
				}else{
					new $.zui.Messager('新增角色失败:'+data.msg,{type:'danger'}).show();
				}
			},
			error:function(status){
				new $.zui.Messager('新增角色时发生错误:'+status,{type:'danger'}).show();
			}
		});
		$("#myModal-addRole").modal("hide");
	});
	//搜索部门/成员
	$("#searchDepart").unbind('keyup').bind('keyup',function(){
		//debugger
		$("#searchResult").empty();
		if( $("#searchDepart").val()=='' ){
			$(".yk_orgMenu #orgTree,.yk_groupBtn").show();
			$("#searchResult,.yk_orgMenu #roleTree,.yk_orgMenu .yk_roleBtn").hide();
			return;
		};
		if( $("#searchDepart").val().indexOf("\'")>-1 || $("#searchDepart").val().indexOf("\_")>-1 ){
			//new $.zui.Messager('请不要输入特殊字符',{type:'danger',time:1000}).show();
			return;
		};
		$.ajax({
			url:'/org/findOrgUserSearch',
			type:'get',
			data:{
				'keyword':$(this).val()
			},
			success:function(data){
				$(".yk_orgMenu .yk_roleBtn,.yk_orgMenu #orgTree,.yk_orgMenu #roleTree,.yk_groupBtn").hide();
				$("#searchResult").show();
				var searchResult = '';
				var searchResultMember = [];
				var searchResultDepart = [];
				var searchResultMemberHtml = '';
				var searchResultDepartHtml = '';
				if( data.length<=0 ){
					searchResult = '<p style="background:#fff;text-align:center;font-size:12px;padding:10px;">未搜索到相关结果</p>';
					$("#searchResult").empty().append(searchResult);
				}else{
					for( var i=0;i<data.length;i++ ){
						if( data[i].type ){//用户
							searchResultMember.push(data[i]);
						}else{//部门
							searchResultDepart.push(data[i]);
						}
					};
					i = null;
					if( searchResultDepart.length>0 ){
						searchResultDepartHtml += '<p class="searchResultTitle">部门列表：</p>';
						for( var i=0;i<searchResultDepart.length;i++ ){
							searchResultDepartHtml += '<div class="searchResultList" type="depart" dataid="'+searchResultDepart[i].id+'"><i class="icon icon-folder-close"></i>'+searchResultDepart[i].name+'</div>'
						};
						i = null;
					};
					if( searchResultMember.length>0 ){
						searchResultMemberHtml += '<p class="searchResultTitle">人员列表：</p>';
						for( var i=0;i<searchResultMember.length;i++ ){
							searchResultMemberHtml += '<div class="searchResultList" type="member" dataid="'+searchResultMember[i].id+'"><i class="icon icon-user"></i>'+searchResultMember[i].name+'</div>'
						};
						i = null;
					};
					$("#searchResult").empty().append(searchResultDepartHtml+searchResultMemberHtml)
				};
			},
			error:function(status){
				new $.zui.Messager('搜索时发生错误'+status,{type:'danger'}).show();
			}
		})
	});
	$(".search-clear-btn").click(function(){
		$("#searchResult").empty();
		$("#searchDepart").val('');
		$(".yk_orgMenu #orgTree,.yk_groupBtn").show();
		$("#searchResult,.yk_orgMenu #roleTree,.yk_orgMenu .yk_roleBtn").hide();
		$(".yk_groupBtn .check").removeClass("check").end().find(".organization").addClass("check")
	});
	//搜索结果点击
	$("#searchResult").on("click",'.searchResultList',function(){
		var $that = $(this);
		if( $(this).attr("type")=='depart' ){
			rightDepartmentId = $(this).attr("dataid");
			rightDepartmentTitle = $that.text().split("-")[$that.text().split("-").length-1]
			$(".yk_orgContent").load('/org/departmentContent',function(){
				backTop('.yk_orgContent');
				$(".yk_orgContentTitle span").text(rightDepartmentTitle);
				if( $(this).attr("dataid")=='1' ){//是'长安银科'
					$(".yk_updateDepartment").remove();
					$(".yk_syncDepartment").remove();
				}
			});
			$('#orgTree li span').removeClass("check");
			//在取消掉搜索结果后,原先的部门树里要选中点击的搜索出来的部门
			//选中之后如果父级没有展开 还需要自动展开(钉钉也没有自动展开,暂不展)
			for( var i=0;i<$('#orgTree li').length;i++ ){
				if( $('#orgTree li').eq(i).attr("data-id")==$(this).attr("dataid") ){
					$('#orgTree li').eq(i).find("span").addClass("check");
				}else{
					$('#orgTree li').eq(i).find("span").removeClass("check");
				}
			};
			i = null;
		}else{
			rightMemberId = $(this).attr("dataid");
			$(".yk_orgContent").load('/org/viewMember',function(){
				backTop('.yk_orgContent');
			});
		}
	})
});
