/*2014-05-30 add by yb
 * describe:菜单管理
 * 
 */
var menutree = null;
var functiontree=null;
var className = "dark";

//PC功能树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
	}
};

//APP功能树setting配置
var setting2 = {
    view: {
        addHoverDom: addAppHoverDom,
        removeHoverDom: removeAppHoverDom,
        selectedMulti: false
    },
    edit: {
        enable: true,
        editNameSelectAll: true,
        showRemoveBtn: showRemoveBtn,
        showRenameBtn: true
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    callback: {
        beforeDrag: beforeDrag,
        beforeEditName: beforeAppEditName,
        beforeRemove: beforeAppRemove,
        beforeRename: beforeAppRename,
        onRemove: onRemove,
        onRename: onRename,
        onClick: onClick_Menuinfo
    }
};

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 name="new code";
		zTree.addNodes(treeNode, {id:'',pId:treeNode.id, name:name});

	});
};

function addAppHoverDom(treeId, treeNode) {
    var sObj = $("#" + treeNode.tId + "_span");
    if (treeNode.editNameFlag || $("#addBtn_app"+treeNode.tId).length>0) return;
    var addStr = "<span class='button add' id='addBtn_app" + treeNode.tId
        + "' title='add node' onfocus='this.blur();'></span>";
    sObj.after(addStr);
    var btn = $("#addBtn_app"+treeNode.tId);
    if (btn) btn.bind("click", function(){
        var zTree = $.fn.zTree.getZTreeObj("appmenutree");
        var name="new code";
        zTree.addNodes(treeNode, {id:'',pId:treeNode.id, name:name});

    });
};

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

function removeAppHoverDom(treeId, treeNode) {
    $("#addBtn_app"+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 + " 的编辑状态吗？");
}

//编辑按钮的 click 事件
function beforeAppEditName(treeId, treeNode) {
    className = (className === "dark" ? "":"dark");
    var zTree = $.fn.zTree.getZTreeObj("appmenutree");
    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 beforeAppRemove(treeId, treeNode) {
    className = (className === "dark" ? "":"dark");
    var zTree = $.fn.zTree.getZTreeObj("appmenutree");
    zTree.selectNode(treeNode);
    return confirm("确认删除 节点 -- " + treeNode.name + " 吗？");
}

//捕获删除节点之后的事件回调函数
function onRemove(e, treeId, treeNode) {
	var contextPath=$("#contextPath").val();
	$.ajax({
		url :contextPath+"/admin/function/deleteFuncTion",
		type : "POST",
		data : {id:treeNode.id},
		dataType:"json",
		success : function(data) {
			if(data!=null&&data.code=="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;
}

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

//用于捕获节点编辑名称结束之后的事件回调函数
function onRename(e, treeId, treeNode, isCancel) {
	if(!isCancel){
		saveOrUpdateMenu(treeNode,"update");
	}
}

//查询节点基本信息
function onClick_Menuinfo(e, treeId, treeNode, isCancel){

    var treeId = treeNode.id;

	//初始化数据,清空
	$("#functionName").val(treeNode.name);
    $("#funcId").val('');
    $("#orderNumber").val('');
    $("#systemcode").val('');
    $("#url").val('');
    $("#perms").val(treeNode.perms);
    $("#rightType").val(treeNode.rightType);
    $("#isApp").val(treeNode.isApp);

    if (treeId == null || treeId == ''){//新增
        var parentNode = treeNode.getParentNode();
        $("#perms").val(parentNode.perms + ":");
        $("#rightType").val(parentNode.rightType + 1);
        $("#isApp").val(parentNode.isApp);
        return false;
    }

	var contextPath=$("#contextPath").val();

	$.ajax({
		url :contextPath+"/admin/function/getFunction",
		type : "POST",
		data : {funcId:treeNode.id},
		dataType:"json",
		success : function(data) {
			if(data.code == '200'){

				if (data.data == null){//没有节点信息
					return;
				}

                $("#funcId").val(data.data.id);
				//描述信息
				$("#functionName").val(data.data.functionName);
				$("#isApp").val(data.data.isApp);
				$("#orderNumber").val(data.data.orderNumber);
				$("#systemcode").val(data.data.systemcode);
				//url 信息
				$("#url").val(data.data.url);
                $("#perms").val(data.data.perms);
                $("#rightType").val(data.data.rightType);

				// 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 加载PC功能树
function initMenuTree(){
	var contextPath=$("#contextPath").val();
	$.ajax({
		url :contextPath+"/admin/function/funcList",
		data:{isApp:"0"},
		type : "POST",
		dataType:"json",
		success : function(data) {

            //替换返回json数据中的key值 供ztree展示数据
            var jsonData = data.data;
            for(var i = 0; i < jsonData.length; i++) {
                jsonData[i]["name"] = jsonData[i]["functionName"];   //'text'是需要的字段
                jsonData[i]["pId"] = jsonData[i]["parentcode"];
                delete jsonData[i]["functionName"];  //key是要替换为'text'的字段
                delete jsonData[i]["parentcode"];
            }

			$.fn.zTree.init($("#menutree"), setting1, data.data);
			menutree=$.fn.zTree.getZTreeObj("menutree");
			menutree.expandAll(true);
		},
		error : function(data) {
			// alert("系统繁忙,加载失败..");
		}
	});
}

//TODO 加载App功能树
function initFunctionTree(){
	var contextPath=$("#contextPath").val();
	$.ajax({
		url :contextPath+"/admin/function/funcList",
        data:{isApp:"1"},
		type : "POST",
		dataType:"json",
		success : function(data) {

			//替换返回json数据中的key值 供ztree展示数据
			var jsonData = data.data;
            for(var i = 0; i < jsonData.length; i++) {
                jsonData[i]["name"] = jsonData[i]["functionName"];   //'text'是需要的字段
                jsonData[i]["pId"] = jsonData[i]["parentcode"];
                delete jsonData[i]["functionName"];  //key是要替换为'text'的字段
                delete jsonData[i]["parentcode"];
            }

			$.fn.zTree.init($("#appmenutree"), setting2, data.data);
			functiontree=$.fn.zTree.getZTreeObj("appmenutree");
			functiontree.expandAll(true);
		},
		error : function(data) {
			// alert("系统繁忙,加载功能树失败..");
		}
	});
}

function saveOrUpdateMenu(id,systemcode,functionName,url,rightType,treecode,parentcode,orderNumber,isApp,perms){
	var contextPath=$("#contextPath").val();
	$.ajax({
		url :contextPath+"/admin/function/saveOrUpdate",
		type : "POST",
		data :{id:id,systemcode:systemcode,functionName:functionName,
            url:url,rightType:rightType,treecode:treecode,parentcode:parentcode,isApp:isApp,orderNumber:orderNumber,perms:perms},
		dataType:"json",
		success : function(data) {
			if(data.code=="200"){
				alert("保存成功.");
                functiontree.refresh();
                menutree.refresh();
			}
			else{
				alert("保存失败."+data.errcode);
			}
		},
		error : function(data) {
			// alert("系统繁忙,保存失败");
		}
	});
}



$(function() {
	//初始化菜单树
	initMenuTree();
	
	//初始化功能树
	initFunctionTree();
	
	//编辑提交
	$("#btn-save").bind("click", function() {
		var menunode=menutree.getSelectedNodes();            //获取左侧菜单树选中node
		var funId = $("#funcId").val();
		var functionName=$("#functionName").val();
		var orderNumber=$("#orderNumber").val();
		var systemcode=$("#systemcode").val();
		var url=$("#url").val();
        var perms=$("#perms").val();
        var rightType=$("#rightType").val();
		var isApp = document.getElementById('isApp').value;

		
		if(menunode.length==0){
			alert("请选择功能");
			return;
		}

        var parentCode = menunode[0].pId;

		saveOrUpdateMenu(funId,systemcode,functionName,url,rightType,null,parentCode,orderNumber,isApp,perms);
	});
	
	//编辑提交
	$("#btn-reload").bind("click", function() {
		reloadFunctree();
	});
	
});

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

//拼接权限字符串
function concatPerm(action) {

	var tree = null;
	var isApp = $("#isApp").val();
	if (isApp == null || isApp == ''){
		alert("请选择功能");
		return;
	}

	if (isApp == '0'){
		tree = $.fn.zTree.getZTreeObj("menutree");
	}else if(isApp == '1') {
        tree = $.fn.zTree.getZTreeObj("appmenutree");
	}

    var nodes = tree.getSelectedNodes();
    if(nodes.length==0){
        alert("请选择功能");
        return;
    }

    if (nodes[0].level == 0){//顶级节点
    	return;
    }
    var parentNode = nodes[0].getParentNode();

    var permStr =parentNode.perms;
    if (action != null && action != ''){
        permStr = parentNode.perms + ":" + action;
	}

    $("#perms").val(permStr);
}


