var treeObj = null;
        var setting = {
        		check : {
        			enable : true,
        			chkDisabledInherit : true
        		},
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                view: {
                    fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
                },
            	callback : {
            		beforeCheck : beforeCheck,
            		onCheck : onCheck,
            		onClick: zTreeOnClick
            	}
        };
        
// tree节点选中之前进行判断
var className = "dark";
function beforeCheck(treeId, treeNode) {
	className = (className === "dark" ? "" : "dark");
	return (treeNode.doCheck !== false);
}

//计算tree选中的节点，for循环去除计算父节点在内
var treecheck = [];
function onCheck() {
	var checkCount = 1, totalcount = 4;
	var zTree = jQuery.fn.zTree.getZTreeObj("tree1");
	if (zTree != null) {
		checkCount = zTree.getCheckedNodes(true).length;
		var nodes = zTree.getCheckedNodes(true);
		totalcount = checkCount;
		treecheck = [];

		for ( var i = 0; i < totalcount; i++) {
			if (nodes[i].id > 4000) {
				treecheck.push(nodes[i].id);
				/*********************************
				 * 设置加载实时数据界面 add by yexb -----start
				 *********************************/
				//实时谐波频谱，实时数据列表，实时矢量图
				if(blrealharmonic){
					window.main_right.refreshRealHarmoinc();
					blrealharmonic=false;
				}
				else if(blrealdatalist){
					window.main_right.refreshRealDatalist();
					blrealdatalist=false;
				}
				else if(blrealvector){
					window.main_right.refreshRealVector();
					blrealvector=false;
				}
			} else {
				checkCount--;
			}
		}

		if (number != 0) {
			if (checkCount >= number) {
				disabledNode(true);
			} else {
				disabledNode(false);
			}
		}
	}
}

function zTreeOnClick() {
    var zTree = $.fn.zTree.getZTreeObj("tree1");
    
    if (zTree != null) {
        var nodes = zTree.getSelectedNodes();   //获取树控件选中对象集合
        // 关闭所有节点的高亮
        var allNodes = treeObj.transformToArray(treeObj.getNodes());
        for (var i = 0; i < allNodes.length; i ++) {
            allNodes[i].highlight = false;
            treeObj.updateNode(allNodes[i]);
        }
        
        // 高亮并展开搜索到的节点
        for (var i = 0; i < nodes.length; i ++) {
            nodes[i].highlight = true;
            treeObj.updateNode(nodes[i]); // 更新节点，让高亮生效
        }
        if (nodes[0].level == 2) {    //如果选中变电站信息则进行处理，其他信息不处理
//            var point = new BMap.Point(nodes[0].lon, nodes[0].lat);
//            map.panTo(point, false);
//            obj.lon = nodes[0].lon;
//            obj.lat = nodes[0].lat;
//            obj.state = nodes[0].state;
//            obj.name = nodes[0].name;
            //修改选中监测点的信息展示
        	var bdname = nodes[0];
            var gdname = nodes[0].getParentNode();
            var dkname = nodes[0].getParentNode().getParentNode();
            $('#pointInfo').text(dkname.name + '->' +gdname.name + '->' + bdname.name);
            $("#subIndex").val(bdname.nodeIndex);
        	var line_index = nodes[0].nodeIndex;
            $("#lineIndex").val(line_index);
            $("#lineName").val(nodes[0].name);
            
            var status = nodes[0].status;
            var state = nodes[0].state;
            if(state == 2){
            	$("#image").val("gray");
            }else if(state == 1){
            	$("#image").val("yellow");
            }else{
            	if(status == 1){
            		$("#image").val("green");
            	}else{
            		$("#image").val("red");
            	}
            }
           
        }else if(nodes[0].level == 3){      //如果选中变压器信息则进行处理，其他信息不处理
        	var name = nodes[0].name;
            queryInfo(name);
        }
        
    }
}
 
function  zTreeOnAsyncSuccess(pastIndex){
    var zTree = $.fn.zTree.getZTreeObj("tree1");
    
    var nodes = zTree.getNodes();    
    zTree.expandNode(nodes[0], true);    
   
    var childNodes = zTree.transformToArray(nodes[0]);    
    if(pastIndex.length==0){
    	
	    var i=0;
	    for(i=0;i<childNodes.length;i++){
	    	var type=childNodes[i].level;
	    	if(type==5){
	            var bdname = childNodes[i].getParentNode().getParentNode().getParentNode();
	            var gdname = childNodes[i].getParentNode().getParentNode().getParentNode().getParentNode();
	            var dkname = childNodes[i].getParentNode().getParentNode().getParentNode().getParentNode().getParentNode();
	            zTree.expandNode(dkname,true);
	            zTree.expandNode(gdname,true);
	            zTree.expandNode(bdname,true);
	            $('#pointInfo').text(dkname.name + '->'+gdname.name + '->' + bdname.name);
	        	var line_index = childNodes[i].nodeIndex;
	            $("#lineIndex").val(line_index);
	            $("#lineName").val(childNodes[i].name);
	            
	            var status = childNodes[i].status;
	            var state = childNodes[i].state;
	            if(state == 2){
	            	$("#image").val("gray");
	            }else if(state == 1){
	            	$("#image").val("yellow");
	            }else{
	            	if(status == 1){
	            		$("#image").val("green");
	            	}else{
	            		$("#image").val("red");
	            	}
	            }
	            
	            //传递参数给相应界面
	            var tjsrc="tongji?line_index="+lineIndex;
	            var fxsrc="analyze?line_index="+lineIndex;
				var sbsrc="manage?line_index="+lineIndex;
				$("#tjsrc").val(tjsrc);
				$("#fxsrc").val(fxsrc);
				$("#sbsrc").val(sbsrc);
//				document.getElementById("tj").src = tjsrc;
//				document.getElementById("fx").src = fxsrc;
//				document.getElementById("sb").src = sbsrc;
				
				var endTime=getEndTime();
				var startTime=getStartTime("年份", endTime);
//			    getEventDensity(line_index,startTime,endTime);
//			    getEventTime(line_index,startTime,endTime);
//			    getEventData(line_index,startTime,endTime);
//			    getEventType(line_index,startTime,endTime);
//			    getEventCause(line_index,startTime,endTime);
				// 关闭所有节点的高亮
	            var allNodes = treeObj.transformToArray(treeObj.getNodes());
	            for (var n = 0; n < allNodes.length; n ++) {
	                allNodes[n].highlight = false;
	                treeObj.updateNode(allNodes[n]);
	            }
	            
	            // 高亮并展开搜索到的节点
	            childNodes[i].highlight = true;
	            treeObj.updateNode(childNodes[i]); // 更新节点，让高亮生效
	            
	    		break;
	    	}
	    }
    }else{
    	var i=0;
	    for(i=0;i<childNodes.length;i++){
	    	var index=childNodes[i].nodeIndex;
	    	if(index==pastIndex && childNodes[i].level == 5){
	    		var bdname = childNodes[i].getParentNode().getParentNode().getParentNode();
	            var gdname = childNodes[i].getParentNode().getParentNode().getParentNode().getParentNode();
	            var dkname = childNodes[i].getParentNode().getParentNode().getParentNode().getParentNode().getParentNode();
	            zTree.expandNode(dkname,true);
	            zTree.expandNode(gdname,true);
	            zTree.expandNode(bdname,true);
	            $('#pointInfo').text(dkname.name + '->'+gdname.name + '->' + bdname.name);
	        	var line_index = childNodes[i].nodeIndex;
	            $("#lineIndex").val(line_index);
	            $("#lineName").val(childNodes[i].name);
	            
	            var status = childNodes[i].status;
	            var state = childNodes[i].state;
	            if(state == 2){
	            	$("#image").val("gray");
	            }else if(state == 1){
	            	$("#image").val("yellow");
	            }else{
	            	if(status == 1){
	            		$("#image").val("green");
	            	}else{
	            		$("#image").val("red");
	            	}
	            }
	            
	            //传递参数给相应界面
	            var tjsrc="tongji?line_index="+lineIndex;
	            var fxsrc="analyze?line_index="+lineIndex;
				var sbsrc="manage?line_index="+lineIndex;
				$("#tjsrc").val(tjsrc);
				$("#fxsrc").val(fxsrc);
				$("#sbsrc").val(sbsrc);
//				document.getElementById("tj").src = tjsrc;
//				document.getElementById("fx").src = fxsrc;
//				document.getElementById("sb").src = sbsrc;
				
				var endTime=getEndTime();
				var startTime=getStartTime("年份", endTime);
//			    getEventDensity(line_index,startTime,endTime);
//			    getEventTime(line_index,startTime,endTime);
//			    getEventData(line_index,startTime,endTime);
//			    getEventType(line_index,startTime,endTime);
//			    getEventCause(line_index,startTime,endTime);
				// 关闭所有节点的高亮
	            var allNodes = treeObj.transformToArray(treeObj.getNodes());
	            for (var n = 0; n < allNodes.length; n ++) {
	                allNodes[n].highlight = false;
	                treeObj.updateNode(allNodes[n]);
	            }
	            
	            // 高亮并展开搜索到的节点
	            childNodes[i].highlight = true;
	            treeObj.updateNode(childNodes[i]); // 更新节点，让高亮生效
	            
	    		break;
	    	}
	    }
    }
    	
}


        function getTree() {
        	jQuery.ajax({
        		type : 'POST',
        		dataType : "json",
        		url : '/pqs9200/device/transtree',
        		data : {},
        		async:false,
        		error : function() {
        			console.log("获取终端树请求发送失败！");
        		},
        		success : function(data) {
        			var datalist = [];
        			for ( var i = 0; i < data.length; i++) {
        				var str = '';

        				str += '{' + "id:" + data[i].id;
        				str += ',' + "name:'" + data[i].name + "'";
        				str += ',' + "nodeIndex:" + data[i].nodeIndex;
        				str += ',' + "nodeType:" + data[i].nodeType;
        				str += ',' + "ppId:" + data[i].ppId;
        				if(data[i].nodeType == "2"){
        					str += ',' + "open:" + true;
        				}else{
        					str += ',' + "open:" + false;
        				}
        				str += ',' + "state:" + data[i].state;
        				str += ',' + "status:" + data[i].status;
        				str += ',' + "pId:" + data[i].pId + '}';
        				datalist.push(str);
        			}
        			datalist = eval('[' + datalist + ']');// string->json数组

        			var zNodes = datalist;
        			var k = 0;
        			for ( var index = 0; index < zNodes.length; index++) {
        				console.log(zNodes[index].nodeType)
        				if (zNodes[index].nodeType == 0) {
        					zNodes[index].icon = "../images/img/base.png";
        				}else if (zNodes[index].nodeType == 1) {
        					zNodes[index].icon = "../images/img/power.png";
        				} else if (zNodes[index].nodeType == 2) {
        					zNodes[index].icon = "../images/img/substation.png";
        				} else if (zNodes[index].nodeType == 3) {
        					zNodes[index].icon = "../images/img/device.png";
        				} 
        			}

        			treeObj = $.fn.zTree.init($("#tree1"), setting, zNodes);
        			var treeObj1 = $.fn.zTree.getZTreeObj("tree1"); 
        			treeObj1.expandAll(true);
        		}
        	});
        	
//
//            $(document).ready(function(){
//                treeObj = $.fn.zTree.init($("#tree"), setting, zNodes);
//            });
        }


        $(document).ready(function(){
        	getTree();
        	var pastIndex=$("#lineIndex").val();
    		zTreeOnAsyncSuccess(pastIndex);
        });
        
        
        // 模糊搜索name满足条件的节点
        function searchNode(value) {
            if (value == "") return;
            
            // 获取搜索的节点
            var nodes = treeObj.getNodesByParamFuzzy("name", value);
            // 关闭所有节点的高亮
            var allNodes = treeObj.transformToArray(treeObj.getNodes());
            for (var i = 0; i < allNodes.length; i ++) {
                allNodes[i].highlight = false;
                treeObj.updateNode(allNodes[i]);
            }
            // 展开第一层节点
            treeObj.expandAll(false);
            treeObj.expandNode(treeObj.getNodes()[0],true);
            // 高亮并展开搜索到的节点
            for (var i = 0; i < nodes.length; i ++) {
                nodes[i].highlight = true;
                treeObj.updateNode(nodes[i]); // 更新节点，让高亮生效
                treeObj.expandNode(nodes[i].getParentNode(),true);
            }
        }
        
        // 设置高亮字体
        function setHighlight(treeId, treeNode) {
            return (!!treeNode.highlight) ? {color:"#000000", "font-weight":"bold"} : {color:"#666", "font-weight":"normal"};
        }
        
        // 延时搜索，用于输入框的按键事件，如果不延时，树就会不断的跳动
        var timeoutId = null;
        function searchNodeLazy(value) {
            if (timeoutId) {
                clearTimeout(timeoutId);
            }
            timeoutId = setTimeout(function(){
                searchNode(value);  
            }, 500);
        }
        
        //根据传入的json对象，更新终端图表
        function updateIcon(json){
        	var lineIndex = $("#lineIndex").val();
        	
        	var jsonArr=[];
        	for(var i =0 ;i < json.length;i++){
                jsonArr[i] = json[i];
        	}
        	
        	var zTree = $.fn.zTree.getZTreeObj("tree1");
            
            var nodes = zTree.getNodes();    
            var childNodes = zTree.transformToArray(nodes[0]);
            
            for(var i=0;i<childNodes.length;i++){
            	var type=childNodes[i].level;
    	    	if(type==5){ 
    	    		for(var n=0;n<jsonArr.length;n++){ 
	    				var status = jsonArr[n].status;
	    				var devFlag = jsonArr[n].devflag;
	    				
    	    			if(jsonArr[n].lineid == childNodes[i].nodeIndex){
    	    				if(jsonArr[n].lineid == lineIndex){
    	    					if (devFlag == 2) {
        	    					childNodes[i].icon = "../images/img/gray.png";
        	    					$("#image").val("gray");
            					} else if (devFlag == 1) {
            						childNodes[i].icon = "../images/img/yellow.png";
            						$("#image").val("yellow");
            					} else {
            						if(status == 1){
            							childNodes[i].icon = "../images/img/green.png";
            							$("#image").val("green");
            						}else{
            							childNodes[i].icon = "../images/img/red.png";
            							$("#image").val("red");
            						}
            					}
        	    				
        	    				zTree.updateNode(childNodes[i]);
    	    				}else{
	    	    				if (devFlag == 2) {
	    	    					childNodes[i].icon = "../images/img/gray.png";
	        					} else if (devFlag == 1) {
	        						childNodes[i].icon = "../images/img/yellow.png";
	        					} else {
	        						if(status == 1){
	        							childNodes[i].icon = "../images/img/green.png";
	        						}else{
	        							childNodes[i].icon = "../images/img/red.png";
	        						}
	        					}
	    	    				
	    	    				zTree.updateNode(childNodes[i]);
    	    				}
    	    			}
    	    		}
    	    	}
            }
        }
        function queryInfo(name){
        	$.ajax({
        		type : "POST",
        		url : "/pqs9200/trans/selectNameAll",
        		data :{tfName:name},
        		beforeSend: function () {  
                    i = ityzl_SHOW_LOAD_LAYER();  
                },
        		success : function(data) {
        			//没有权限的请求
        			if(data==300){
        				location.href='/pqs9200/auth/unauthorized';
        			//没有登陆的请求
        			}else if(data==301){
        				location.href='/pqs9200';
        			}else{
        				var p=$("#roleJ").val();
        				 $('#vdlist').dataTable().fnClearTable(); 
        				if(p=="Npro"){
        					$('#vdlist').DataTable({
        						columnDefs : [ {
        							orderable : false,
        							targets : [1,2,3,5,8,11,13]
        						} ],
        						destroy : true,
        						data : data,
        				        language : {
        							url:'/pqs9200/json/chine.json'
        						}
        					});
        				} else {
        					var heightTemp=screen.height;
        					var length;
        					if(heightTemp===768){
        						length=10;
        					}else if (heightTemp===1024){
        				        length=20;
        					}else if (heightTemp===960){
        				        length=15;
        				    }else if (heightTemp===1050){
        				        length=18;
        				    }else{
        				        length=11;
        					}
        					var oTable=$('#vdlist').DataTable({
        						scrollX : true,
        						lengthChange : false,
        						bDestroy : true,
        						ordering : false,
        						columnDefs : [ {
        							targets : [ ],
        							visible : false
        						}],
        						"columns": [
        						    {"width": "10%"},
        						    {"width": "10%"},
        						    {"width": "10%"},
        						    {"width": "10%"},
        						    {"width": "20%"},
        						    {"width": "20%"},
        						    {"width": "20%"}
        						 ],
        						data : data.body,
        						destroy : true,
        						pageLength:length,
        						language : {
        							url:'/pqs9200/json/chine.json',
        							"sEmptyTable": "没有内容"
        						},
        						'fnDrawCallback': function(oTable) {    
        						    $("#vdlist_paginate").append("<div style='float:right;padding-top:4px;padding-left:10px'>到第 <input type='text' id='changePage' class='input-text' style='width:50px;height:28px;'> 页  <button class='btn btn-primary' id='dataTable-btn'>确定</button></div>");    
        						    var table = $("#vdlist").dataTable();    
        						    $('#dataTable-btn').click(function(e) {
        						        if($("#changePage").val() && $("#changePage").val() > 0) {    
        						            var redirectpage = $("#changePage").val() - 1;    
        						        } else {    
        						            var redirectpage = 0;    
        						        }    
        						        table.fnPageChange(redirectpage);
        						    });    
        						}
        					});
        					
        				}
        				//***********关闭loading
        	        	ityzl_CLOSE_LOAD_LAYER(i); 
        			}
        		}
        	});
        }