var datenow = new Date();
var detailWindow;
var xzTree = "";
var curDialogId = "";
var treeSelectId="-1";
$(function() {
	initToolBar();
	//initTreePanel();
	initGrid();//加载列表
	doSearch();
	initTree();
});

function initTree() {
	$.ajax({
		type: 'post',
		dataType: 'json',
		url: 'ptxzsAction!query_PtxzsTree.do',
		data: {
			order: " order by jdpx asc "
		},
		success: function (data) {
			var setting = {
				data: {
					key: {title: "name"}
				},
				callback: {
					onClick: zTreeOnClick
				}
			};
			if (data) {
				$.fn.zTree.init($("#xzTree"), setting, data);
			}
		}
	});

}

function initToolBar(){
	$('#tdlx').combobox({
		data : $.obj2ary(CommonData.channelType),
		textField:1,
		valueField:0,
		panelWidth:148,
		value:""
	});
}

function initTreePanel(){
// 	xzTree = $('#xzTree').tree({
// 	        lines:false,
// 			animate: false,
// 	    	multiple:false,
// 	    	editable:false,
// 	    	border:false,
// 	    	parentField:"sjxzbh",
// 	    	textFiled:"xzmc",
// 	    	idFiled:"xzbh",
// 	    	collapse :true,
// 	    	data: [{
// 	    		xzmc: '行政目录' ,
// 				id  	:"-1",
// 				state	:'open',
// 				wholePath:'-1',
// 				xzbh	:'-1'
// 			}],
// //	    	onClick:function(node){
// //	    		$(this).tree(node.state === 'closed' ? 'expand' : 'collapse', node.target);
// //	    		doSearch();
// //		 	},
// 		 	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);
//                 if(node.id == -1){
//                 	$('#menu1').hide(1).fadeIn(1).menu('show',{
//                         left: e.pageX,
//                         top: e.pageY
//                    });
//                 }else{
//                 	$('#menu2').hide(1).fadeIn(1).menu('show',{
//                         left: e.pageX,
//                         top: e.pageY
//                    });
//
//                 }
//              }
// 	});
	$.ajax({
		type:'post',
		dataType : 'json',
		url:'ptxzsAction!query_PtxzsTree.do',
		data:{
			order : " order by jdpx asc "
		},
		success:function(data){
			var setting = {
				data : {
					key : { title : "name"}
				},

				callback: {
					onClick: zTreeOnClick
				}};
			if(data){
				$.fn.zTree.init($("#xzTree"), setting, data);
				//$.fn.zTree.init($("#stree"), setting, zNodes);
			}
		}
	});


	$.ajax({
		type:'post',
		dataType : 'json',
		url:'ptxzsAction!query_Ptxzs.do',
		data:{
			order : " order by jdpx asc "
		},
		success:function(data){
			$.each(data,function(i,o){
				o.state ='closed';
			})
			if(data){
				xzTree.tree('append', {
					parent : xzTree.tree('find', -1).target,
					data   : data
				});
			}
			var node = xzTree.tree('find', -1);
			xzTree.tree('select', node.target);
		}
	});
}
function getTopDialogValue(){
	var obj 	=	{};
	var frame	=	top.$("#"+curDialogId).children('iframe')[0];
	var jq		=	(frame.contentWindow||frame.window)["$"];
	var xzmc 	=   jq("#xzmc").val();
	var wbbh	=	jq("#wbbh").val();
	if(!xzmc || !xzmc.length){
		top.$.dlg.alertError("请填写目录名称!");
		return null ;
	}
	return {
		xzmc : $.trim(xzmc),
		wbbh : wbbh
	};
}
function addChild(){
	//var node = xzTree.tree('getSelected');
	curDialogId  =  top.$.createWin({
		title	: 	'编辑子目录',
		width	:  	300,
		height	: 	160,
		url	:	top.sysUrl+"/yw/ptxztree/ptxzs_editnode.jsp?xzbh="+treeSelectId,
		//onClose:	function(){},
		buttons: [{
			text:$.fn.textbox.defaults.ok,
			handler:saveInfo
		}]
	});
}
function editCurrNode(){
	//var node = xzTree.tree('getSelected');
	curDialogId  =  top.$.createWin({
		title	: 	'编辑子目录',
		width	:  	300,
		height	: 	160,
		url	:	top.sysUrl+"/yw/ptxztree/ptxzs_editnode.jsp?xzmc="+encodeURI(node.xzmc)+"&wbbh="+node.wbbh,
		//onClose:	function(){},
		buttons: [{
			text:$.fn.textbox.defaults.ok,
			handler:editCurrNodeFun
		}]
	});
}
function zTreeOnClick(event,treeid,treeNode){
	treeSelectId=treeNode.id;
	doSearch();
}

function editCurrNodeFun(){
	var obj = getTopDialogValue();
	if(obj){
		var node = xzTree.tree('getSelected');
		if(node){
			$.ajax({
				type:'post',
				dataType : 'json',
				url:'ptxzsAction!update_Ptxzs.do',
				data:{
					xzbh	:	node.xzbh,
					xzmc	:	obj.xzmc,
					wbbh	:	obj.wbbh
				},success:function(data){
					if(data){
						//initTreePanel();
						top.$("#"+curDialogId).dialog("close");
					}else{
						$.showMsg("操作失败！");
					}
				}
			});
		}
	}
}

function removeCurrNode(node){
	//var node = xzTree.tree('getSelected');
	top.$.dlg.confirm('你确认要删除吗?',function(){
		//var xzbh = node.xzbh;
		$.ajax({
			type : 'post',
			dataType : 'json',
			url : 'ptxzsAction!count_Ptxzs.do',
			data : {'sjxzbh':treeSelectId},
			success:function(res){
//				console.log("返回结果",res);
				if(res==0){				// 说明是根目录   下面没有节点   可以删除
					$.ajax({
						type : 'post',
						dataType : 'json',
						url : 'ptxzsAction!delete_Ptxzs_ext.do',
						data:{'xzbh':xzbh},
						success:function(res){
//							console.log("删除：",res);
							if(res == 'success'){
								initTreePanel();
								top.$("#"+curDialogId).dialog("close");
								$.showMsg("操作成功！");
							}
						}
					})
				}else{
					top.$.dlg.alertError("请先删除子机构!");
				}
			}
		})
	});
	/*top.$.dlg.confirm('你确认要删除吗?',function(){	 
		var m = new Object();
		m.fatherId=node.xzId;
		m.enterpriseId = node.jiLianCode;
		
		$.ajax({
			 type:'post',
			 dataType : 'json',
			 url:'ptxzsAction!query_Ptxzs.do',
			 data:{
					xzbh	:	node.xzbh,
					xzmc	:	obj.xzmc,
					wbbh	:	obj.wbbh
			 },success:function(data){
				if(data){
					initTreePanel();
					top.$("#"+curDialogId).dialog("close");
				}else{
					$.showMsg("操作失败！");
				}
			 }
		 });
		
		
		var str = "" ,i = 0;
		XzTreeService.select_XzTree(m, function(r) {
			for(i=0;i<r.length;i++) {
				str+=(i+1)+"、"+r[i].roleName+"<br/>";
			}
		});
		$.endSync(); 
		if(str){
			top.$.dlg.alertError("请先删除子机构!");
			return;
		}
		var param = {xzId:node.xzId, jiLianCode:node.jiLianCode}
		XzTreeService.delete_XzTree(param,function(data){
			data = $.parseJSON(data);
			if(data){
				initTreePanel();
				top.$("#"+curDialogId).dialog("close");
			} 
		});
	});*/
}

function saveInfo(){
	var obj = getTopDialogValue();
	if(obj){
		var node   = xzTree.tree('getSelected');
		var pqlj   = node.qlj || roleTree.tree('getParent' ,node.target).qlj || '-1$';
		var currid = $.uniqueId().replace(/-/g, "");
		var qlj    = pqlj + currid +"$";
		$.ajax({
			type:'post',
			dataType : 'json',
			url:'ptxzsAction!insert_Ptxzs.do',
			data:{
				sjxzbh	:	node.xzbh,
				xzmc	:	obj.xzmc,
				wbbh  	: 	obj.wbbh,
				xzbh	:	currid,
				qlj		:	qlj
			},
			success:function(data){
				if(data){
					initTreePanel();
					$.showMsg("操作成功！");
					top.$("#"+curDialogId).dialog("close");
				}else{
					$.showMsg("信息添加失败，请核对信息内容！");
				}
			}
		});
	}
}
//查询条件
//加载列表
function initGrid(){
	var toolbar = [{
		text:'查询',
		iconCls:'icon-search',
		handler:function(){doSearch();}
	},{
		text:'添加通道',
		iconCls:'icon-addEquip',
		handler:function(){showTabPanel();}
	},{
		text:'移除通道',
		iconCls:'icon-delEquip',
		handler:function(){detachLink();}
	},{
		text:'Excel导出',
		iconCls:'icon-export-excel',
		handler:doExport
	}];
	$('#searchGrid').datagrid({
		singleSelect:false,
		toolbar : toolbar,
		cache: false,
		columns : [[
			{
				field: 'A',
				checkbox:'true',
				width:30
			},
			{
				title:"设备编号",
				field: "sbbh",
				width: 160,
			},
			{
				title:"通道编号",
				field:"tdbh",
				width: 80
			},
			{
				title:"通道名称",
				field:"tdmc",
				width: 200
			},
			{
				title:"行政目录",
				field:"xztreename",
				width: 120
			},
			{
				title:"通道状态",
				field:"tdzt",
				width: 80,
				formatter:function(value,record,num){
					if(value ==0 ) return "启用";
					else if(value ==1 ) return "停用";
					else if (value ==2 ) return "废弃";
					else return "未知";
				}
			},
			{
				title:"通道类型",
				field:"tdlx",
				width: 80,
				formatter:function(value,record,num){
					return CommonData.channelType[value] ||"";
				}
			}
		]]
	});
}


//保存
//导出
function doExport(){
	countTotal();
}


//不建议修改的模块
//查询
function doSearch(){
	if(!treeSelectId || treeSelectId === "-1" ) return;
	//channelSmallType
	var param = {
		LIKEsbbh 	: $('#sbbh').textbox('getValue'),
		LIKEtdmc 	: $('#tdmc').textbox('getValue'),
		tdlx 		: $('#tdlx').combobox('getValue'),
		XGTJxzbh	: treeSelectId
	};
	$('#searchGrid').datagrid('options').url = "sbtdspsrAction!query_Sbtdspsr_ext.do";
	$("#searchGrid").datagrid('load',param);
}
//显示窗口
function showWindow(){
	detailWindow.append('<iframe frameborder="no" scrolling="no" style="border:none;width:100%;height:100%"></iframe>');
	detailWindow.dialog({
		title:'设备通道   <注：两个Tab选项可同时保存>',
		width:540,
		closed:true,
		height:400,
		modal:true,
		onBeforeClose:function (){
			detailWindow.dialog('destroy');
		},
		buttons:[{
			text:$.fn.textbox.defaults.ok,
			handler:doSaveXzViChannel
		},{
			text:$.fn.textbox.defaults.close,
			handler:function(){
				detailWindow.dialog('destroy');
			}
		}]
	});
}

function detachLink() {
	var selRows = $('#searchGrid').datagrid('getSelections');
	if(selRows===null || !selRows.length){
		$.showMsg('请先选择记录! ');
		return;
	}
	//var node  = xzTree.tree('getSelected');
	if(!treeSelectId || treeSelectId=="-1" ){
		$.showMsg('请重新选择节点! ');
		return;
	}
	top.$.dlg.confirm('确认删除?',function(){
		var idArray = [];
		for(var i=0;i<selRows.length;i++){
			idArray.push(selRows[i].xh);
		}

		if(idArray.length){
			$.ajax({
				type:'post',
				dataType : 'json',
				data:{
					xzbh:node.xzbh,
					xhs:idArray.join(",")
				},
				url:'sbtdspsrAction!batch_delete_Sbtdspsr_xh.do',
				success:function(value){
					$.showMsg("操作成功！");
					doSearch();
					top.$("#"+windowId).dialog("close");
				}
			});
		}

	});
}


function showTabPanel() {
	windowId = top.$.createWin({
		id		:	$.uniqueId(),
		title	: 	'增加信息',
		width	:  	550,
		height	: 	500,
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:doSaveXzViChannel
		}],
		url	:	top.sysUrl+"/yw/ptxztree/ptxzs_show.jsp"
	});
}
function doSaveXzViChannel(){
	var win		=	$.getTopWindowById(windowId);
	var jq		=	win.$;
	var selRows_no = win.$('#noCodeSearch').datagrid('getSelections');
	var selRows_out = win.$('#outCodeSearch').datagrid('getSelections');

	if(selRows_no.length <= 0  &&  selRows_out.length <= 0 ){
		$.showMsg('请先选择记录! ');
		return;
	}

	//var node  = xzTree.tree('getSelected');

	if(!treeSelectId|| treeSelectId=="-1" ){
		$.showMsg('请重新选择节点! ');
		return;
	}
	var idArray = [];

	if(selRows_no.length > 0){
		for(var i=0;i<selRows_no.length;i++){
			idArray.push(selRows_no[i].xh);
		}
	}

	if(selRows_out.length > 0){
		for(var i=0;i<selRows_out.length;i++){
			idArray.push(selRows_out[i].xh);
		}
	}
	if(idArray.length){
		$.ajax({
			type:'post',
			dataType : 'json',
			data:{
				xzbh:node.xzbh,
				xhs:idArray.join(","),

			},
			url:'sbtdspsrAction!batch_update_Sbtdspsr_xh.do',
			success:function(value){
				$.showMsg("操作成功！");
				doSearch();
				top.$("#"+windowId).dialog("close");
			}
		});
	}

}
//查询条件
function getQueryParams(){
	var model = {};
	var tableparam = "";
	//model.xzId = xzTree.tree("getSelected").xzId;
	if("-1"!=treeSelectId) {
		model.xzId = treeSelectId;
	}
	model.LIKEvdId = $('#vdId').textbox('getValue');
	model.LIKEchannelName = $('#channelName').textbox('getValue');
	model.channelSmallType = $('#channelSmallType').combobox('getValue');
	model.tableparam = tableparam;
	return model;
}
//统计数据总量
function countTotal(){
	var model = getQueryParams();
	if("-1"==treeSelectId) model = {};
	ViChannelService.query_ViChannel_ext(model,function(data){
		if(data.totalSize){
			exportTj(data.totalSize);
		}
	});
}
//导出传参条件
function exportTj(totalSize){
	var model = getQueryParams();
	if("-1"==treeSelectId) model = {};
	var tableparam = "";
	var start = 0;
	var limit = 5000;
	if(totalSize>5000){
		tableparam += " limit "+start+","+limit;
		model.tableparam = tableparam;
		var qd = confirm("记录过多支持前5000条,确定要将记录导出Excel为表格吗？");
		if(qd){
			downloadExcel(model);
		}
	}else{
		model.tableparam = tableparam;
		var qd = confirm("确定要将记录导出Excel为表格吗？");
		if(qd){
			downloadExcel(model);
		}
	}
}
//调用后台
function downloadExcel(model){
	ViChannelService.exp_ViChannel(model, function(data) {
		dwr.engine.openInDownload(data);
	});
}