var detailWindow,detailWindowId =$.uniqueId(),roleTree,windowId,proName = window.location.pathname.split("/")[1],sysUrl = "http://"+window.location.host+"/"+proName,toEdit;
var curDialogId = "";
$(function(){
	initDefault();
	$("#treeRegion").on("contextmenu", function(e){
		$('#menu1').hide(1).fadeIn(1).menu('show',{
			left: e.pageX,
			top: e.pageY
		});
		return false;
	});
});
//默认
function initDefault(){
	initGrid();
	initTreePanel();
}

function initTreePanel(){
	$.ajax({
		async:false,
		type:'post',
		dataType : 'json',
		url:'ywalarmeventcodeAction!listYwalarmeventcodeByTree.do',
		data:{
			order : " order by createtime asc "
		},
		success:function(data){
			$.each(data,function(i,o){
				if (i = 0) {
					o.state ='open';
				} else {
					o.state ='closed';
				}
				o.id = o.alarmcode;
		    	
		    	o.wholePath = o.alarmcode;
		    })
		    if(data){
		    	loadtree(data);
		    }
		}
	});
}

function loadtree(data) {
	roleTree = $('#roleTree').tree({
		lines:false,
		animate: false, 
    	multiple:false,
    	editable:false,
    	border:false,
//    	parentField:"sjxzbh",  
//    	textFiled:"xzmc",
//    	idFiled:"xzbh",
    	parentField:"parentcode",
    	textFiled:"alarmname",
    	idFiled:"alarmcode",
    	collapse :true,
    	data: data,
    	onSelect:function(){
    		doSearch();
	 	},
		onDblClick:function(node){
		 	$(this).tree(node.state === 'closed' ? 'expand' : 'collapse', node.target);  
		},
		onContextMenu: function(e,node){
            e.preventDefault();
            $(this).tree('select',node.target);
            $('#menu2').hide(1).fadeIn(1).menu('show',{
            	left: e.pageX,
            	top: e.pageY
            });
         }
	});

	var node = roleTree.tree('find', data[0].alarmcode);
	roleTree.tree('select', node.target);
}

//加载列表
function initGrid(){	
	var toolbar = [{
    	text	:	'查询',
        iconCls	:	'icon-search',
        handler	:	doSearch
    },{
        text	:	'增加',
        iconCls	:	'icon-add',
        handler	:	doAdd
    },{
        text	:	'修改',
        iconCls	:	'icon-cut',
        handler	:	doEdit
    },{
        text	:	'删除',
        iconCls	:	'icon-delete',
        handler	:	doDelete
    }];
	$('#tableGrid').datagrid({
		toolbar : toolbar,
		singleSelect:false,
		rownumbers:true,
		columns : [[
			{
				field: 'A',
				checkbox:'true',
				width:30
			},
			{field:'alarmcodetypeNa',title:'告警代码类型',hidden:false,width:120},
			{field:'alarmcode',title:'告警代码',hidden:false,width:120},
			{field:'alarmname',title:'告警名称',hidden:false,width:120},
			{field:'fullpath',title:'全路径',hidden:false,width:120},
			{field:'faultcause',title:'故障原因',hidden:false,width:120},
			{field:'faultdescription',title:'故障原因描述',hidden:false,width:120},
			{field:'isenable',title:'是否启用',hidden:true,width:120},
			{field:'createaccount',title:'创建人员',hidden:true,width:120},
			{field:'createtime',title:'创建日期',hidden:true,width:120},
			{field:'modifyaccount',title:'修改人员',hidden:true,width:120},
			{field:'modifytime',title:'修改日期',hidden:true,width:120},
			{field:'remarks',title:'备注',hidden:false,width:120},
			{field:'extend1',title:'扩展1',hidden:true,width:120},
			{field:'extend2',title:'扩展2',hidden:true,width:120},
			{field:'extend3',title:'扩展3',hidden:true,width:120},
			{field:'extend4',title:'扩展4',hidden:true,width:120}
		]]
	});
}

//删除
function doDelete(){
	var selRows = $('#tableGrid').datagrid('getSelections'),j=0;
	if(selRows.length==0) {
		$.showMsg('请先选择记录! ');
		return;
	}
	top.$.dlg.confirm('确认删除?',function(){
		for(var i=0;i<selRows.length;i++){
			$.ajax({
				async:false,
				type:'post',
				dataType : 'json',
				url:'ywalarmeventcodeAction!delete_Ywalarmeventcode.do',
				data:{
					alarmcodeid	:	selRows[i].alarmcodeid
				},
				success:function(flag){
					if(flag == 'success') {
						j++;
					}
				}
			});
			if(j == selRows.length) {
				top.$.dlg.alertInfo('删除成功 ');
				$("#tableGrid").datagrid("reload");
			}
		}
	});
}

//查询
function doSearch(){
//	alert(roleTree.tree("getSelected").alarmcodetype);
	var sParam = {};
//	sParam.alarmcodetype = $('#LIKEalarmcodetype').combobox("getValue");
	sParam.LIKEalarmcode = $('#LIKEalarmcode').textbox("getValue");
	sParam.LIKEalarmname = $('#LIKEalarmname').textbox("getValue");
	sParam.parentcode	= roleTree.tree("getSelected").alarmcode;
	sParam.order = "ORDER BY createtime desc";
	$('#tableGrid').datagrid('options').url = "ywalarmeventcodeAction!listYwalarmeventcodeByPage.do";
	$("#tableGrid").datagrid('load',sParam);
}

//增加
function doAdd(){
	toEdit=false;
	var node = roleTree.tree('getSelected');
	// 根据detailWindowId判断是否已创建了该div，避免创建多余嵌套页面代码
	if(top.$("#" + detailWindowId + "").length > 0) {
		top.$("#" + detailWindowId + "").html("");
	}
	detailWindow = top.$('<div id=' +detailWindowId+'/>');
	createDetailWindow();
	setTimeout(function(){
		detailWindow.children('iframe').attr('src',sysUrl+'/yw/alarmtaskmanage/alarmcode/ywalarmeventcode_show.jsp?alarmcodetype='+node.alarmcodetype);
		detailWindow.dialog('open');
		top.editInfo = {};
	},100);
}

//修改
function doUpdate(index){
	toEdit=true;
	// 根据detailWindowId判断是否已创建了该div，避免创建多余嵌套页面代码
	if(top.$("#" + detailWindowId + "").length > 0) {
		top.$("#" + detailWindowId + "").html("");
	}
	detailWindow = top.$('<div id=' +detailWindowId+'/>');
	createDetailWindow();
	setTimeout(function(){
		var selRows = $('#tableGrid').datagrid('getRows')[index];
		detailWindow.children('iframe').attr('src',sysUrl+'/yw/alarmtaskmanage/alarmcode/ywalarmeventcode_show.jsp');
		top.editInfo = selRows;
		detailWindow.dialog('open');
	},100);
}
//保存
function saveNodeDataInfo(){
	var node = roleTree.tree('getSelected');
	var frame	=	detailWindow.children('iframe')[0],model={};
	var win		=	frame.contentWindow||frame.window;
	var jq		=	win.$;
	// 获取参数
	model.alarmcodetype = jq("#alarmcodetype").combobox("getValue");
	model.alarmcode = jq("#alarmcode").textbox("getValue");
	model.alarmname = jq("#alarmname").textbox("getValue");
	model.faultcause = jq("#faultcause").textbox("getValue");
	model.faultdescription = jq("#faultdescription").textbox("getValue");
	model.remarks = jq("#remarks").textbox("getValue");
	model.isenable = "1";

	if (model.alarmcodetype == "" || model.alarmcodetype == null) {
		top.$.dlg.alertError('请选择告警代码类型! ');
    	return;
	}
	if (model.alarmcode == "" || model.alarmcode == null) {
		top.$.dlg.alertError('告警代码不能为空! ');
    	return;
	}
	if(model.alarmcode != "") {
		var r =/^[0-9]+[0-9]*]*$/;
		if(!r.test(model.alarmcode)){
			top.$.dlg.alertError('告警代码请输入纯数字 ! ');
			return;
		}
	}
	if (model.alarmname == "" || model.alarmname == null) {
		top.$.dlg.alertError('告警名称不能为空! ');
    	return;
	}
	var parent = roleTree.tree('getParent', node.target);
	var str = "";
	if (parent != null) {
		str = "" + parent.alarmcode;
		while(1) {
			parent = roleTree.tree('getParent', parent.target);
			if(parent){
				str = parent.alarmcode + "" + str;
			} else {
				break;
			}
		}
	}
	model.fullpath = str + "" + node.alarmcode + "" + model.alarmcode;
	model.parentcode = node.alarmcode;

	if(toEdit){//修改
		model.XGTJalarmcodeid = jq('#alarmcodeid').val();

		//model.checkparam = " and xh='"+model.xh+"' ";
		$.ajax({
			type:'post',
			dataType : 'json',
			url:'ywalarmeventcodeAction!update_Ywalarmeventcode.do',
			data:model,
			success:function(value){
				if(value=="success"){
					$.showMsg("操作成功！");
					$("#tableGrid").datagrid("reload");
					detailWindow.dialog('close');
				}else if(value=="same"){
					$.showMsg("已存在！");
				}else{
					$.showMsg("操作失败！");
				}
			}
		});
	}else{
		//model.checkparam = " and xh='"+model.xh+"' ";
		$.ajax({
			type:'post',
			dataType : 'json',
			url:'ywalarmeventcodeAction!insert_Ywalarmeventcode.do',
			data:model,
			success:function(value){
				if(value=="success"){
					$.showMsg("操作成功！");
					$("#tableGrid").datagrid("reload");
					detailWindow.dialog('close');
				}else if(value=="same"){
					$.showMsg("已存在！");
				}else{
					$.showMsg("操作失败！");
				}
			}
		});
	}
}
//打开修改
function doEdit(){
	var selRows = $('#tableGrid').datagrid('getSelections');
	if(selRows.length <= 0){
		top.$.dlg.alertInfo('请先选择记录! ');
		return;
	} else if (selRows.length >= 2) {
		top.$.dlg.alertInfo('请先选择单条记录! ');
		return;
	} else {
		var selIndex = $('#tableGrid').datagrid('getRowIndex', $("#tableGrid").datagrid('getSelected'))
		doUpdate(selIndex);
	}
}

function createDetailWindow(){
	detailWindow.append('<iframe frameborder="no" scrolling="no" style="border:none;width:100%;height:100%"></iframe>');
	detailWindow.dialog({
		title:'告警代码信息',
		width:700,
		closed:true,
		height:420,
		modal:true,
		buttons:[{
				text:$.fn.textbox.defaults.ok,
				handler:saveNodeDataInfo
			 },{
				text:$.fn.textbox.defaults.close,
				handler:function(){
				detailWindow.dialog('close');
			 }
		}]
	});
}

// 树形菜单增删改
// 新增
function addChild(){
	var node = roleTree.tree('getSelected');
	curDialogId  =  top.$.createWin({
		 title	: 	'新增子节点',
		 width	:  	300,
		 height	: 	200,
		 url	:	sysUrl+"/yw/alarmtaskmanage/alarmcode/ywalarmeventcode_editnode.jsp",
		 //onClose:	function(){},
		 buttons: [{
			 text:$.fn.textbox.defaults.ok,
			 handler:saveInfo
         }]
	 });
}

// 保存
function saveInfo(){
	var obj = getTopDialogValue();
	var checkparam = " and alarmcode = '" + obj.alarmcode + "'";
	if(obj){
		var node   = roleTree.tree('getSelected');
		var parentcode = node.alarmcode;
		$.ajax({
			 type:'post',
			 dataType : 'json',
			 url:'ywalarmeventcodeAction!insert_Ywalarmeventcode.do',
			 data:{
				 checkparam : checkparam,
				 alarmcodetype : obj.alarmcodetype,
				 alarmcode : obj.alarmcode,
				 alarmname : obj.alarmname,
				 parentcode : parentcode,
				 isenable : "1"
			},
			success:function(data){
				if(data=="success"){
					initTreePanel();
					$.showMsg("操作成功！");
					top.$("#"+curDialogId).dialog("close");
				}else if(data=="same"){
					$.showMsg("已存在！");
				}else{
					$.showMsg("信息添加失败，请核对信息内容！");
				}
			 }
		 });
	}
}

// 新增节点目录
function addNode(){
	var node = roleTree.tree('getSelected');
	curDialogId  =  top.$.createWin({
		 title	: 	'新增子节点',
		 width	:  	300,
		 height	: 	200,
		 url	:	sysUrl+"/yw/alarmtaskmanage/alarmcode/ywalarmeventcode_editnode.jsp",
		 //onClose:	function(){},
		 buttons: [{
			 text:$.fn.textbox.defaults.ok,
			 handler:saveNodeInfo
         }]
	 });
}

// 结构目录
function saveNodeInfo(){
	var obj = getTopDialogValue();
	var checkparam = " and alarmcode = '" + obj.alarmcode + "'";
	if(obj){
		$.ajax({
			 type:'post',
			 dataType : 'json',
			 url:'ywalarmeventcodeAction!insert_Ywalarmeventcode.do',
			 data:{
				 checkparam : checkparam,
				 alarmcodetype : obj.alarmcodetype,
				 alarmcode : obj.alarmcode,
				 alarmname : obj.alarmname,
				 isenable : "1"
			},
			success:function(data){
				if(data=="success"){
					initTreePanel();
					$.showMsg("操作成功！");
					top.$("#"+curDialogId).dialog("close");
				}else if(data=="same"){
					$.showMsg("已存在！");
				}else{
					$.showMsg("信息添加失败，请核对信息内容！");
				}
			 }
		 });
	}
}

function getTopDialogValue(){
	var obj 	=	{}; 
	var frame	=	top.$("#"+curDialogId).children('iframe')[0];
	var jq		=	(frame.contentWindow||frame.window)["$"];
	var alarmcode 	=   jq("#alarmcode").val();
	var alarmname	=	jq("#alarmname").val();
	var alarmcodetype	=	jq("#alarmcodetype").val();

	if(!alarmcode || !alarmcode.length){
		top.$.dlg.alertError("请填写告警代码!");
		return null ;
	}
	if(alarmcode != "") {
		var r =/^[0-9]+[0-9]*]*$/;
		if(!r.test(alarmcode)){
			top.$.dlg.alertError('告警代码请输入纯数字 ! ');
			return;
		}
	}
	if(!alarmname || !alarmname.length){
		top.$.dlg.alertError("请填写目录名称!");
		return null ;
	}
	if(!alarmcodetype || !alarmcodetype.length){
		top.$.dlg.alertError("请填写告警类型!");
		return null ;
	}
	if(alarmcodetype != "") {
		var r =/^[0-9]+[0-9]*]*$/;
		if(!r.test(alarmcodetype)){
			top.$.dlg.alertError('告警类型请输入纯数字 ! ');
			return;
		}
	}

	return {
		alarmname : $.trim(alarmname),
		alarmcode : alarmcode,
		alarmcodetype : alarmcodetype
	};
}

// 修改
function editCurrNode(){
	var node = roleTree.tree('getSelected');
	curDialogId  =  top.$.createWin({
		 title	: 	'编辑子目录',
		 width	:  	300,
		 height	: 	200,
		 url	:	sysUrl+"/yw/alarmtaskmanage/alarmcode/ywalarmeventcode_editnode.jsp?alarmcode="+node.alarmcode+"&alarmname="+encodeURI(node.alarmname)+"&alarmcodetype="+node.alarmcodetype,
		 //onClose:	function(){},
		 buttons: [{
			 text:$.fn.textbox.defaults.ok,
			 handler:editCurrNodeFun
         }]
	 });
}

// model.XGTJalarmcodeid = jq('#alarmcodeid').val();
function editCurrNodeFun(){
	var obj = getTopDialogValue();
	var node = roleTree.tree('getSelected');
	var checkparam = "";
	if(obj.alarmcode != node.alarmcode){
		checkparam = " and alarmcode = '" + obj.alarmcode + "'";
	}

	if(obj){
		if(node){
		$.ajax({
			 type:'post',
			 dataType : 'json',
			 url:'ywalarmeventcodeAction!update_Ywalarmeventcode.do',
			 data:{
				 checkparam : checkparam,
				 XGTJalarmcodeid : node.alarmcodeid,
				 alarmcodetype : obj.alarmcodetype,
				 alarmcode : obj.alarmcode,
				 alarmname : obj.alarmname,
				 isenable : "1"
			 },success:function(data){
				 if(data=="success"){
					 initTreePanel();
					 $.showMsg("操作成功！");
					 top.$("#"+curDialogId).dialog("close");
				 }else if(data=="same"){
					 $.showMsg("已存在！");
				 }else{
					 $.showMsg("信息添加失败，请核对信息内容！");
				 }
			 }
		 });
		}
	}
}

// 删除
function removeCurrNode(node){
	var node = roleTree.tree('getSelected');
	top.$.dlg.confirm('你确认要删除吗?',function(){
		var str = "" ,i = 0;
		$.ajax({
			async:false,
			type:'post',
			dataType : 'json',
			url:'ywalarmeventcodeAction!listYwalarmeventcodeByTree.do',
			data:{
				parentcode : node.alarmcode
			},
			success:function(data){
				for(i=0;i < data.length;i++) {
					str += (i+1)+"、"+data[i].alarmname+"<br/>";
				}
			}
		});
		if(str){
			top.$.dlg.alertError("请先删除子节点目录!");
			return;
		}
		$.ajax({
			type:'post',
			dataType : 'json',
			url:'ywalarmeventcodeAction!deleteYwalarmeventcodeTreeNode.do',
			data:{
				alarmcodeid : node.alarmcodeid,
				parentcode : node.alarmcode
			},
			success:function(data){
				if(data){
					initTreePanel();
					top.$("#"+curDialogId).dialog("close");
				}
			}
		});
	});
}