/*2014-05-30 add by yb
 * describe:菜单管理
 * 
 */
var menutree = null;
var functiontree=null;
var treecodeStart=0;
var newCount = 1;
var className = "dark";
//菜单树setting配置
var setting1 = {
	view: {
		addHoverDom: addHoverDom,
		removeHoverDom: removeHoverDom,
		selectedMulti: false
	},
	edit: {
		enable: true,
		editNameSelectAll: true,
		showRemoveBtn: showRemoveBtn,
		showRenameBtn: true
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		beforeDrag: beforeDrag,
		beforeEditName: beforeEditName,
		beforeRemove: beforeRemove,
		beforeRename: beforeRename,
		onRemove: onRemove,
		onRename: onRename,
		onClick: onClick_Menuinfo
	}
};
//系统功能树setting配置
var setting2 = {
	check: {
		enable: true,
		chkStyle: "radio",
		radioType: "all"
	},
	data: {
		simpleData: {
			enable: true
		}
	},
	callback: {
		onCheck: onCheck_appFunc,
		onClick: onClick_appFunc
	}
};

function beforeDrag(treeId, treeNodes) {
	return false;
}

function addHoverDom(treeId, treeNode) {
	var sObj = $("#" + treeNode.tId + "_span");
	if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
	var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
		+ "' title='add node' onfocus='this.blur();'></span>";
	sObj.after(addStr);
	var btn = $("#addBtn_"+treeNode.tId);
	if (btn) btn.bind("click", function(){
		var zTree = $.fn.zTree.getZTreeObj("menutree");
		var treeid=treecodeStart + newCount;
		var name="new code" + (newCount++);
		zTree.addNodes(treeNode, {id:treeid, pId:treeNode.id, name:name});
		
		var newNode={id:treeid, pId:treeNode.id, name:name};
		var formdata = new FormData();/*treeNode,actType*/
		// formdata.append("treeCode", newNode);
        formdata.append("treeCode", treeid);
        formdata.append("parentCode", treeNode.id);
		formdata.append("actType","add" );
		saveOrUpdateMenu(formdata);
		return false;
	});
};

function removeHoverDom(treeId, treeNode) {
	$("#addBtn_"+treeNode.tId).unbind().remove();
};

function showRemoveBtn(treeId, treeNode) {
	if(treeNode.isParent||treeNode.id=="0"){
		return false;
	}
	else{
		return true;
	}
	//return !treeNode.isFirstNode;
}

//编辑按钮的 click 事件
function beforeEditName(treeId, treeNode) {
	className = (className === "dark" ? "":"dark");
	var zTree = $.fn.zTree.getZTreeObj("menutree");
	zTree.selectNode(treeNode);
	return confirm("进入节点 -- " + treeNode.name + " 的编辑状态吗？");
}

//捕获节点被删除之前的事件
function beforeRemove(treeId, treeNode) {
	className = (className === "dark" ? "":"dark");
	var zTree = $.fn.zTree.getZTreeObj("menutree");
	zTree.selectNode(treeNode);
	return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
}

//捕获删除节点之后的事件回调函数
function onRemove(e, treeId, treeNode) {
	var contextPath=$("#contextPath").val();
	$.ajax({
		url :contextPath+"/admin/ajax/deleMenu",
		type : "POST",
		data : {treeCode:treeNode.id, parentCode:treeNode.pId},
		dataType:"json",
		success : function(data) {
			if(data!=null&&data.errcode=="200"){
				alert("菜单 -"+treeNode.name+" 删除成功");
			}
			else{
				alert("删除失败."+data.errcode +" 请刷新");
			}
		},
		error : function(data) {
			alert("删除失败."+data.errcode +" 请刷新");
		}
	});
}

//捕获节点编辑名称结束（Input 失去焦点 或 按下 Enter 键）
function beforeRename(treeId, treeNode, newName, isCancel) {
	className = (className === "dark" ? "":"dark");
	if (newName.length == 0) {
		alert("节点名称不能为空.");
		var zTree = $.fn.zTree.getZTreeObj("menutree");
		setTimeout(function(){zTree.editName(treeNode)}, 10);
		return false;
	}
	return true;
}

//用于捕获节点编辑名称结束之后的事件回调函数
function onRename(e, treeId, treeNode, isCancel) {
	if(!isCancel){
		var formdata = new FormData();
		formdata.append("treeCode", treeNode.id);
        formdata.append("parentCode",treeNode.pId);
		formdata.append("actType", "update");
		saveOrUpdateMenu(formdata);
	}
}

//查询节点基本信息
function onClick_Menuinfo(e, treeId, treeNode, isCancel){
	$("#menuName").val(treeNode.name);
	var contextPath=$("#contextPath").val();
	$.ajax({
		url :contextPath+"/admin/ajax/getMenu",
		type : "POST",
		data : {treeCode:treeNode.id, parentCode:treeNode.pId},
		dataType:"json",
		success : function(data) {
			if(data!=null&&data!=""){
				//描述信息
				$("#description").val(data.description);
				$("#isApp").val(data.isApp);
				$("#iconUrl").val(data.iconUrl);
				$("#menuCode").val(data.menuCode);
				
				//url 信息
				$("#url").val(data.url);
				if(data.appfunctionId!=null){
					//关联右侧功能菜单
					var nodes=functiontree.getNodes();
					//获取所有的节点(包括子节点)
                    nodes = functiontree.transformToArray(nodes);
					$.each(nodes,function(index,node){
						if(node.id==data.appfunctionId){
							node.checked=true;
						}
						else{
							node.checked=false;
						}
					});
				}
				else{
					$("#url").val("");
					reloadFunctree();
				}
				functiontree.refresh();
			}
		},
		error : function(data) {
		}
	});
	
}

//勾选功能菜单
function onCheck_appFunc(e, treeId, treeNode){
	$("#url").val(treeNode.url);
}

function onClick_appFunc(e, treeId, treeNode){
	var contextPath=$("#contextPath").val();
	window.open(contextPath+"/"+treeNode.operateStr);
}

//TODO 加载菜单树
function initMenuTree(){
	var contextPath=$("#contextPath").val();
	$.ajax({
		url :contextPath+"/admin/ajax/menutree",
		type : "POST",
		dataType:"json",
		success : function(data) {
			$.fn.zTree.init($("#menutree"), setting1, data);
			menutree=$.fn.zTree.getZTreeObj("menutree");
			menutree.expandAll(true);
		},
		error : function(data) {
			// alert("系统繁忙,加载失败..");
		}
	});
}

//TODO 加载功能树
function initFunctionTree(){
	var contextPath=$("#contextPath").val();
	$.ajax({
		url :contextPath+"/admin/ajax/functiontree",
		type : "POST",
		dataType:"json",
		success : function(data) {
			$.fn.zTree.init($("#functiontree"), setting2, data);
			functiontree=$.fn.zTree.getZTreeObj("functiontree");
			functiontree.expandAll(true);
		},
		error : function(data) {
			// alert("系统繁忙,加载功能树失败..");
		}
	});
}

function saveOrUpdateMenu(data){
	var contextPath=$("#contextPath").val();
	$.ajax({
		url :contextPath+"/admin/ajax/addOrUpdateMenu",
		type : "POST",
		data :data, 
		cache: false,
		processData: false,  // 告诉jQuery不要去处理发送的数据
		contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
		success : function(data) {
			if(data.errcode=="200"){
				alert("保存成功.");
			}
			else{
				alert("保存失败."+data.errcode);
			}
		},
		error : function(data) {
			// alert("系统繁忙,保存失败");
		}
	});
}

$(function() {
	//初始化菜单树
	initMenuTree();
	
	//初始化功能树
	initFunctionTree();
	
	var menutreeCount=$("#totalcount").val();
	if(menutreeCount!=null&&menutreeCount!=""){
		treecodeStart= parseInt(menutreeCount);
	}
	
	//编辑提交
	$("#btn-save").bind("click", function() {
		var menunode=menutree.getSelectedNodes();            //获取左侧菜单树选中node
		var nodes = functiontree.getCheckedNodes(true);      //获取右侧菜单树勾选node
		var description=$("#description").val();
		var menuName=$("#menuName").val();
		var iconUrl=$("#iconUrl").val();
		var menuCode=$("#menuCode").val();
		var funcId="";
		var isApp = document.getElementById('isApp').value;
		var menuIcon = $("#menuIcon")[0].files[0];
		$.each(nodes,function(index,node){
			funcId=node.id;
		});
		
		if(menunode.length==0){
			alert("请选择菜单");
			return;
		}
		var formdata = new FormData();
		formdata.append("treeCode", menunode[0].id);
		formdata.append("parentCode", menunode[0].pId);
		formdata.append("actType", "update");
		formdata.append("description", description);
		formdata.append("ordernum", "");
		formdata.append("funcId", funcId);
		formdata.append("menuName", menuName);
		formdata.append("isApp", isApp);
		formdata.append("iconUrl", iconUrl);
		formdata.append("menuCode", menuCode);
		formdata.append("menuIcon", menuIcon);
		saveOrUpdateMenu(formdata);
	});
	
	//编辑提交
	$("#btn-reload").bind("click", function() {
		reloadFunctree();
	});
	
});

function reloadFunctree(){
	var nodes = functiontree.getCheckedNodes(true);
	$.each(nodes,function(index,node){
		node.checked =false;
	});
	functiontree.refresh();
}
