//用户树操作
var zNodes;
var menu = {
	setting: {
		view:{
			fontCss : {"font-family": "微软雅黑","color":"blue"}
		},
		data:{
			simpleData: {
				enable: true,
				idKey: "id",
				pIdKey: "parentId",
				isParent:"isParent"
			},
		},
		callback: { //回调函数
			onClick: zTreeOnClick,
			onExpand: addChildNodes
		}
	},
	//加载树
	loadMenuTree:function(){
		var key = $("#key").val();
		$.ajax({
			type: "post",
			url: path+"/menuPower/getUserPowerTree",
			data:{key:key},
			dataType:"json",
			success:function(data){
				$.fn.zTree.init($("#ztree"), menu.setting, data);
				zTree = $.fn.zTree.getZTreeObj("ztree");
				if(key == ''){
					var nodes = zTree.getNodes();
					zTree.expandNode(nodes[0], true);
				}else{
					zTree.expandAll(true);
				}
				/*
				for (var i = 0; i < nodes.length; i++) { //设置节点展开
					zTree.expandNode(nodes[i], true, false, true);
				}*/
				zNodes = data;
				$('#loadingModal').modal('hide');
			}
		})
	}
};
//加载用户树
$().ready(function(data){
	menu.loadMenuTree();
	//fuzzySearch('ztree','#key',null,true,menu.setting,zNodes); //初始化模糊搜索方法
});
//定义最后一级的树id的前缀
var streeId = 's';
//展开节点添加子节点
function addChildNodes(event, treeId, treeNode){
	var children =  treeNode.children;
	var ztree = $.fn.zTree.getZTreeObj("ztree");
	var level = treeNode.level;
	treeId = treeNode.id;
	var sysFlag = treeNode.sysFlag;
	if(children == undefined) {
		//1.权限系统，加载该医院所有用户
		if (level == 1 && sysFlag == 'power') {
			//获取父节点及医院的医院id
			var hospitalId = treeNode.getParentNode().selfId;
			$.ajax({
				type: 'get',
				url: path + '/menuPower/getUserTreeByHospitalId',
				data: {hospitalId: hospitalId},
				dataType: 'json',
				async: false,
				success: function (data) {
					if (data != null) {
						var sTreeId = 0;
						var treeList = [];
						for (var i = 0; i < data.length; i++) {
							sTreeId++;
							var newNode = {
								id: streeId + sTreeId,
								parentId: treeId,
								name: data[i].name,
								newName: data[i].newName,
								sysFlag: sysFlag,
								selfId: data[i].name.split('-')[0]
							}
							treeList.push(newNode);
						}
						ztree.addNodes(treeNode, treeList);
					}
				}
			})
		}
		//1.其他系统，加载该科室下用户
		if (level == 2) {
			var deptId = treeNode.getParentNode().selfId;
			$.ajax({
				type: 'get',
				url: path + '/menuPower/getUserTreeByDeptId',
				data: {deptId: deptId},
				dataType: 'json',
				async: false,
				success: function (data) {
					if (data != null) {
						var sTreeId = 0;
						var treeList = [];
						for (var i = 0; i < data.length; i++) {
							sTreeId++;
							var newNode = {
								id: streeId + sTreeId,
								parentId: treeId,
								name: data[i].name,
								newName: data[i].newName,
								sysFlag: sysFlag,
								selfId: data[i].name.split('-')[0]
							}
							treeList.push(newNode);
						}
						ztree.addNodes(treeNode, treeList);
					}
				}
			})
		}
	}
}

//关键字搜索树
function reloadTree() {
	var key = $("#key").val();
	if(key.length > 2){
		$('#loadingModal').modal('show');
		menu.loadMenuTree();
	}else{
		toastr.warning("数据较多,搜索内容字符不少于2位");
	}
}


//用户树点击事件
var sysZnodes;
function zTreeOnClick(event, treeId, treeNode) {
	$("#block").empty();
	//系统id
	var sysFlag = treeNode.sysFlag;
	var level = treeNode.level;
	$("#sysFlag").val("");
	if(sysFlag != null && sysFlag != ''  &&
		((sysFlag == 'power' && level == 2)) || (sysFlag != 'power' && level > 2)){
		//设置用户id ==
		var userId = treeNode.selfId;
		$.ajax({
			type: "post",
			url: path+"/menuPower/getMenuBySysIdAndUerIdPowerTree",
			data:{sysFlag:sysFlag,userId:userId},
			dataType:"json",
			success:function(data){
				var menuData = [];
				var methodData = [];
				if(data != null && data != ''){
					for(var i = 0; i < data.length; i++) {
						if(data[i].method == '' || data[i].method == null){
							//菜单
							menuData.push(data[i]);
						}else{
							//方法
							methodData.push(data[i]);
						}
					}
					if(null != menuData){
						sysZnodes = menuData;
						//初始化菜单树
						initSysMenuTree();
						//选中节点的menuId赋值到隐藏域
						var menus = '';
						for(var i = 0; i < menuData.length; i++) {
							if(menuData[i].checked == 'true'){
								menus += menuData[i].menuId + ",";
							}
						}
						$("#userId").val(userId);
						$("#menus").val(menus);
					}
					$("#sysFlag").val(sysFlag);
					//赋值方法区隐藏复选框
					if(null != methodData && methodData.length > 0){
						var html = '';
						var parentIds = [];
						for(var i = 0; i < methodData.length; i++) {
							parentIds.push(methodData[i].parentId);
						}
						//父id去重
						parentIds = array_remove_repeat(parentIds);
						for(var i = 0; i < parentIds.length; i++) {
							var methods = '';
							var method = [];
							for(var j = 0; j < methodData.length; j++) {
								if(methodData[j].parentId == parentIds[i]){
									method.push(methodData[j]);
								}
								//选中节点的方法demenuId赋值到隐藏域
								if(methodData[j].checked == 'true'){
									methods += methodData[j].menuId + ',';
								}
							}
							if(method != null){
								html += appendHtmlTotal(method,treeNode.menuId);
							}
							$("#methods").val(methods);
						}
						$("#block").append(html);
					}
				}else{
					$("#ztree1").empty();
					$("#userId").val('');
				}
			}
		})
	}else{
		toastr.warning("请选中用户！");
	}
};
 //菜单树操作
var setting = {
	view:{
		fontCss : {"font-family": "微软雅黑","color":"blue"}
	},
	check: {
		enable: true
		},
	data:{
		simpleData: {
		enable: true,
		idKey: "menuId",
		pIdKey: "parentId",
	},
	key:{
		name:"menuName"
	}
	},
	callback: { //回调函数
		onClick: menuZTreeOnClick,
		onCheck:onCheck}
};
//菜单点击事件
function menuZTreeOnClick(event, treeId, treeNode) {
	var menuId = treeNode.menuId;
	//原来的divIndex隐藏
	var divIndex = $("#divIndex").val();
	$("#methodDiv"+divIndex).hide();
	//改节点为父节点的方法显示
	$("#methodDiv"+menuId).show();
	$("#divIndex").val(menuId);
}
//菜单树复选框选中事件
function onCheck(e,treeId,treeNode){
	var treeObj=$.fn.zTree.getZTreeObj("ztree1");
	truenodes=treeObj.getCheckedNodes(true);
	falsenodes=treeObj.getCheckedNodes(false);
	var divIndex = $("#divIndex").val();
	var isExist;
	var menus = '';
	if(null != truenodes){
		for(var i=0;i<truenodes.length;i++){
			//获取树选中节点的menu集合
			var menu = truenodes[i].menuId;
			menus += menu + ",";
		}
	}
	childNodeTrue(treeNode.menuId);
	//菜单id集合赋值到隐藏域
	$("#menus").val(menus);
	if(falsenodes != null){
		for(var i = 0; i < falsenodes.length; i++) {
			//方法区全不选
			$("#methodDiv"+falsenodes[i].menuId+" input[type='checkbox']").each(function(){
				$(this).prop("checked",false);
			});
		}
	}
}
//保存用户菜单信息
function addUserMenu(){
	var methods = '';
	 $("input[name='methodId']:checked").each(function(){
		methods += $(this).val() + ",";
	})
	var menus = ztree.getCheckedNodes(true);
	var menu = '';
	for(var i = 0; i < menus.length; i++) {
		menu += menus[i].menuId + ",";
	}
	$("#menus").val(menu+methods);
	var userId = $("#userId").val();
	if(userId != null && userId != ''){
		$.ajax({
			type:'post',
			url:path+"/menuPower/addUserMenu",
			data:{userId:$("#userId").val(),sysFlag:$("#sysFlag").val(),menus:$("#menus").val()},
			dataType:"json",
			success:function(data){
				if(data.code == 100){
					toastr.success("保存成功!");
				}else{
					toastr.error(data.msg);
				}
			}
		})
	}else{
		toastr.warning("请先选中用户！")
	}
}
