
$(function(){
    var data=$.parseJSON("[{\"id\":-1,\"text\":\"用户分组\",\"iconCls\":\"icon-ico_server_hui\"}]"); 
            
    $("#tt2").tree({
				  data : data
	});

});
//获取组信息
function getGroup(){
    $.ajax({
	        type: "POST",
	        dataType: "json",
	        async:false,
	        url: "json/groupAction_groupName.action",
	        data: {dataType:$.cookie('loadType')!=null?$.cookie('loadType'):1},
	        success: function(json) {		         
		         if (json.flag==true) {
		               
		                $("#tt2").html(""); 
                        var data=$.parseJSON("[{\"id\":-1,\"text\":\"用户分组\",\"iconCls\":\"icon-loading\"}]");         
                        $("#tt2").tree({
				         data : data
	                    });
		             var loadType=$.cookie('loadType');
		             var data=null;
		             if(loadType==0){
		               data=praseGroup(json); 
		             }else{
		               data=parseGroupAndCart(json);
		             }
                     
                     

                     $("#tt2").html("");               

                     $("#tt2").tree({
					     data : data,
					     checkbox:true,
					     cascadeCheck:true,
					     onBeforeExpand : function(node) {
					       
					       var root = $('#tt2').tree('getRoot');

                           if(root.id!=node.id){
					        
						       if(loadType==0&&rootflag&&node.attributes.flag){
						         $('#tt2').tree('update', {
			                           target: node.target,
			                           iconCls: 'icon-loading'
		                         });
						              addLeaf(node);					         
						         $('#tt2').tree('update', {
			                           target: node.target,
			                           iconCls: 'icon-ico_fenzu_nor',
			                           attributes:{flag:false}
		                         });
		                        }
		                    }	        
					     },
					     onCheck:function(node, checked){
				             getCart(node,checked);
					     },
					     onDblClick:function(node){
					             var flag=$('#tt2').tree('isLeaf', node.target);
					             if(flag){
					                 $("#vehName").text(node.text);
				                     $("#vhcid").val(node.id);
				                     $("#vehicle").val(node.text);
					             
					             }
					            
					     }
				     });                                                          
		         }
	        },
	        error: function() {
	             $.messager.alert('错误', '获取组信息失败...请联系管理员!', 'error');
	        }
	   });			
}
//添加车辆列表
function addLeaf(node){
      		    node.attributes.flag=false;//设置标记标识已经加载alert(node.text);
				$.ajax({type: "POST",
	                    dataType: "json",
	                    async:false,
	                    url: "json/groupAction_getGroupData.action",
	                    data: {groupid:node.id},
	                    success: function(json){
	                                //alert(JSON.stringify(json));
	                                if (json.flag==true) {
                                          var data=praseCart(json);
                                          $('#tt2').tree('append', {//追加会触发节点的选中事件
								                     parent : node.target,
								                     data : data.data
							              });
							              
                                    }
	                    },
	                    error: function() {
	                              $.messager.alert('错误', '获取车辆信息失败...请联系管理员!', 'error');
	                    }						                						                
			     });
}

var rootflag=true;
var groupflag=true;

//获取车辆信息
function getCart(node,checked){
         var loadType=$.cookie("loadType");
         
         var root = $('#tt2').tree('getRoot');

         if(root.id==node.id){
           if(checked){
              if(loadType==0&&rootflag){
                var nodes=$('#tt2').tree('getChildren', node.target);        
                for(var i=0;i<nodes.length;i++){
                   $('#tt2').tree('check', nodes[i].target);             
                }                              
                rootflag=false;
              }else{
                $('#tt2').tree('expandAll', node.target);
                $('#tt2').tree('expand', node.target);
                var nodes=$('#tt2').tree('getChildren', node.target);
                var ids=getAllchildIds(nodes);
                appendCartDetailPost(ids);           
              }
           }else{
                $('#tt2').tree('collapse',node.target);
                var nodes=$('#tt2').tree('getChildren', node.target);        
                for(var i=0;i<nodes.length;i++){
                   if(!$('#tt2').tree('isLeaf',node.target)){
                      $('#tt2').tree('collapse',nodes[i].target);
                   }              
                }                
              deletePointAndrows();
           }
         }else if(!$('#tt2').tree('isLeaf',node.target)){
	           if(checked){
                  if(loadType==0&&rootflag&&node.attributes.flag){
                     node.attributes.flag=false;//设置标记标识已经加载
                     addLeaf(node);
                   }  
                     $('#tt2').tree('expand', node.target);
                     var nodes=$('#tt2').tree('getChildren', node.target);
                     var ids=getAllchildIds(nodes);
                     deletePointAndrowsById(ids);
                     appendCartDetailPost(ids);                

	           }else{
	               var nodes=$('#tt2').tree('getChildren', node.target);
	               var ids=getAllchildIds(nodes);
	               $('#tt2').tree('collapse', node.target);
	               deletePointAndrowsById(ids);
	           }
         }else{       
	          if(checked){
	                  var ids=getAllchildIds(node.id);
	                  appendCartDetailPost(node.id);
		      }else{
		              deletePointAndrowsById(node.id+",");
		      }
         }
}
//删除地图中的点和表格中的数据
function deletePointAndrowsById(idsStr){
   var ids =idsStr.split(",");
   for(var i=0;i<ids.length;i++){
	    for(var j=0;j<markers.length;j++){
	      if(markers[j].id==ids[i]){
	         map.deletePoint(markers[j]);
	         markers.remove(markers[j]); 
	      }
	      if(titles[j].id==ids[i]){
	         map.deleteTitle(titles[j]);
	         titles.remove(titles[j]);
	         
	          //根据id获取表格行号
	          var index=$('#table').datagrid('getRowIndex',ids[i]);
	     
	          //触发行选择事件，获取行对应的id号
	          var rows=$('#table').datagrid('selectRow',index);
	     
	          //删除table中的行
	          if(tableid==ids[i]){
	             $('#table').datagrid('deleteRow',index);  
	          }        
	         j--;
	      }
	    }    
	}
}
function appendCartDetailPost(ids){
     $.ajax({
	        type: "POST",
	        dataType: "json",
	        async:false,
	        url: "json/vehicleAction_byids.action",
	        data: {ids:ids},
	        success: function(json) {		         
		         if (json.flag==true) {  
                    var data=appendCartDetailMarker(json);//格式化返回的数据+map打点                                           
		         }
	        },
	        error: function() {
	             $.messager.alert('错误', '获取车辆详细信息失败...请联系管理员!', 'error');
	        }
	   });


}
function getAllchildIds(nodes){
     
      var ids="";  
      for(var i=0;i<nodes.length;i++){
         if($('#tt2').tree('isLeaf',nodes[i].target)){
            ids=ids+nodes[i].id+",";
         }
      }
      ids=ids.substring(0,ids.length-1); 
      return ids
}
function getCartDetailPost(ids){
 $.ajax({
	        type: "POST",
	        dataType: "json",
	        async:false,
	        url: "json/vehicleAction_byids.action",
	        data: {ids:ids},
	        success: function(json) {		         
		         if (json.flag==true) {  
                    var data=praseCartDetail(json)//格式化返回的数据+map打点
                     //table加载数据   
                     //alert(JSON.stringify(data));
                    $('#table').datagrid('loadData', data);                                              
		         }
	        },
	        error: function() {
	             $.messager.alert('错误', '获取车辆详细信息失败...请联系管理员!', 'error');
	        }
	   });			

}

//刷新车辆列表
function resfCart(){
         var nodes = $('#tt2').tree('getChecked');
         var ids = getIds(nodes);
         getResfCartDetailPost(ids);

}

function getResfCartDetailPost(ids){
 $.ajax({
	        type: "POST",
	        dataType: "json",
	        async:false,
	        url: "json/vehicleAction_onlinevids.action",
	        data: {ids:ids},
	        success: function(json) {	         
		         if (json.flag==true) {	              
                      var data=resfCartDetail(json)//格式化返回的数据+map打点                                                                         
		         }
	        },
	        error: function() {
	             $.messager.alert('错误', '获取车辆详细信息失败...请联系管理员!', 'error');
	        }
	   });			

}

var markers=new Array();
var titles = new Array();

function appendCartDetailMarker(json){

   var carts=json.data;
   for(var i=0;i<json.totalcount;i++){
     var icon=getVhcIcon(((carts[i].positionLast.state!=null)?carts[i].positionLast.state:''), ((carts[i].positionLast.direct!=null)?carts[i].positionLast.direct:''));
     var marker=map.addPoint(((carts[i].positionLast.vehicleId!=null)?carts[i].positionLast.vehicleId:''),carts[i].positionLast.lng,carts[i].positionLast.lat,icon,17,17);
     var title= map.addPointTitle(((carts[i].positionLast.vehicleId!=null)?carts[i].positionLast.vehicleId:''),marker,((carts[i].vhcCode!=null)?carts[i].vhcCode:''));
     var popup= map.addPointEvent(marker,"<span style='color:#4d4d4d;font-weight:bold'>车牌号码:"+((carts[i].vhcCode!=null)?carts[i].vhcCode:'')+
                              "</span><div style='margin-top:10px;font-size: 12px;'>接收时间:"+((carts[i].positionLast.recvtime!=null)?carts[i].positionLast.recvtime:'')+
                              "</div><span style=font-size: 12px;>速度:"+((carts[i].positionLast.speed!=null)?carts[i].positionLast.speed:'')+
                              "<br/>方向:"+((carts[i].positionLast.direct!=null)?carts[i].positionLast.direct:'')+
                              "<br/>状态:"+((carts[i].positionLast.state2!=null)?carts[i].positionLast.state2:'')+
                              "<br/>位置:"+((carts[i].positionLast.memo!=null)?carts[i].positionLast.memo:''))+"</span>";
     
      markers.push(marker);	
      titles.push(title);
    } 
    
    
    for(var i=0;i<json.totalcount;i++){
    var data= {
			   carId:(carts[i].positionLast.vehicleId!=null)?carts[i].positionLast.vehicleId:'',
			   vhcCode:(carts[i].vhcCode!=null)?carts[i].vhcCode:'',
			   recvtime:((carts[i].positionLast.recvtime!=null)?carts[i].positionLast.recvtime:''),
			   gpstime:((carts[i].positionLast.gpstime!=null)?carts[i].positionLast.gpstime:''),
			   state2:((carts[i].positionLast.state2!=null)?carts[i].positionLast.state2:''),
			   direct:((carts[i].positionLast.direct!=null)?carts[i].positionLast.direct:''),
			   speed:((carts[i].positionLast.speed!=null)?carts[i].positionLast.speed:''),
			   oilMN1:((carts[i].positionLast.oilMN1!=null)?carts[i].positionLast.oilMN1:''),
			   temp1:((carts[i].temp1!=null)?carts[i].temp1:''),
			   temp2:((carts[i].temp2!=null)?carts[i].temp2:''),
			   temp3:((carts[i].temp3!=null)?carts[i].temp3:''),
			   temp4:((carts[i].temp4!=null)?carts[i].temp4:''),
			   totalDistance:((carts[i].positionLast.totalDistance!=null)?carts[i].positionLast.totalDistance:''),
			   lng:((carts[i].positionLast.lng!=null)?carts[i].positionLast.lng:''),
			   lat:((carts[i].positionLast.lat!=null)?carts[i].positionLast.lat:''),
			   memo:((carts[i].positionLast.memo!=null)?carts[i].positionLast.memo:'')
			  };
    
	      $('#table').datagrid('appendRow',data);	  
	}
}

//format组信息
function praseCartDetail(data){
      markers=[];	
      titles=[];
   
   deletePointAndrows();  
   
   var formatStr="{\"total\":"+ data.totalcount+",\"rows\":[";
   var carts=data.data;
   for(var i=0;i<data.totalcount;i++){
     var icon=getVhcIcon(((carts[i].positionLast.state!=null)?carts[i].positionLast.state:''), ((carts[i].positionLast.direct!=null)?carts[i].positionLast.direct:''));
     var marker=map.addPoint(((carts[i].vehicleId!=null)?carts[i].vehicleId:''),carts[i].positionLast.lng,carts[i].positionLast.lat,icon,17,17);
     var title= map.addPointTitle(((carts[i].vehicleId!=null)?carts[i].vehicleId:''),marker,((carts[i].vhcCode!=null)?carts[i].vhcCode:''));
     var popup= map.addPointEvent(marker,"车牌号码:"+((carts[i].vhcCode!=null)?carts[i].vhcCode:'')+
                              "<br/>接收时间:"+((carts[i].positionLast.recvtime!=null)?carts[i].positionLast.recvtime:'')+
                              "<br/>速度:"+((carts[i].positionLast.speed!=null)?carts[i].positionLast.speed:'')+
                              "<br/>方向:"+((carts[i].positionLast.direct!=null)?carts[i].positionLast.direct:'')+
                              "<br/>状态:"+((carts[i].positionLast.state2!=null)?carts[i].positionLast.state2:'')+
                              "<br/>位置:"+((carts[i].positionLast.memo!=null)?carts[i].positionLast.memo:''));
     
      markers.push(marker);	
      titles.push(title);
      

     formatStr=formatStr+"{\"carId\":\""+((carts[i].positionLast.vehicleId!=null)?carts[i].positionLast.vehicleId:'')+
                          "\",\"车牌号码\":\""+((carts[i].vhcCode!=null)?carts[i].vhcCode:'')+
                          "\",\"服务器时间\":\""+((carts[i].positionLast.recvtime!=null)?carts[i].positionLast.recvtime:'')+
                          "\",\"GPS时间\":\""+((carts[i].positionLast.gpstime!=null)?carts[i].positionLast.gpstime:'')+
                          "\",\"状态\":\""+((carts[i].positionLast.state2!=null)?carts[i].positionLast.state2:'')+
                          "\",\"方向\":\""+((carts[i].positionLast.direct!=null)?carts[i].positionLast.direct:'')+
                          "\",\"速度\":\""+((carts[i].positionLast.speed!=null)?carts[i].positionLast.speed:'')+
                          "\",\"油量\":\""+((carts[i].positionLast.oilMN1!=null)?carts[i].positionLast.oilMN1:'')+
                          "\",\"温度1\":\""+((carts[i].temp1!=null)?carts[i].temp1:'')+
                          "\",\"温度2\":\""+((carts[i].temp2!=null)?carts[i].temp2:'')+
                          "\",\"温度3\":\""+((carts[i].temp3!=null)?carts[i].temp3:'')+
                          "\",\"温度4\":\""+((carts[i].temp4!=null)?carts[i].temp4:'')+
                          "\",\"总里程\":\""+((carts[i].positionLast.totalDistance!=null)?carts[i].positionLast.totalDistance:'')+
                          "\",\"纬度\":\""+((carts[i].positionLast.lng!=null)?carts[i].positionLast.lng:'')+
                          "\",\"经度\":\""+((carts[i].positionLast.lat!=null)?carts[i].positionLast.lat:'')+
                          "\",\"位置\":\""+((carts[i].positionLast.memo!=null)?carts[i].positionLast.memo:'')+"\"},";
   }
    formatStr=formatStr.substring(0,formatStr.length-1);
    formatStr=formatStr+"]}";
    return $.parseJSON(formatStr);
}
//删除地图中的所有点和表格中的数据
function deletePointAndrows(){

      map.deleteAllMarker(); 
   
   var item = $('#table').datagrid('getRows');
   if (item) {
      for (var i = item.length - 1; i >= 0; i--) {
              var index = $('#table').datagrid('getRowIndex', item[i]);
              $('#table').datagrid('deleteRow', index);
      }
    }

}

function resfCartDetail(data){
   
   var popup,title,marker;
   
   var carts=data.data;
   for(var i=0;i<data.totalcount;i++){
   
     if(markers[i].id==carts[i].vehicleId){
        markers.remove(markers[i]);	
        map.deletePoint(markers[i]);
        var icon=getVhcIcon(((carts[i].state!=null)?carts[i].state:''), ((carts[i].direct!=null)?carts[i].direct:''));
        marker=map.addPoint(((carts[i].vehicleId!=null)?carts[i].vehicleId:''),carts[i].lng,carts[i].lat,icon,17,17);
     }
     if(titles[i].id==carts[i].vehicleId){
        titles.remove(titles[i]);
        map.deleteTitle(titles[i]);
        title= map.addPointTitle(((carts[i].state!=null)?carts[i].state:''),marker,((carts[i].vhcCode!=null)?carts[i].vhcCode:''));
     }

     popup= map.addPointEvent(marker,"车牌号码:"+((carts[i].vhcCode!=null)?carts[i].vhcCode:'')+
                              "<br/>接收时间:"+((carts[i].recvtime!=null)?carts[i].positionLast.recvtime:'')+
                              "<br/>速度:"+((carts[i].speed!=null)?carts[i].speed:'')+
                              "<br/>方向:"+((carts[i].direct!=null)?carts[i].direct:'')+
                              "<br/>状态:"+((carts[i].state2!=null)?carts[i].state2:'')+
                              "<br/>位置:"+((carts[i].memo!=null)?carts[i].memo:'')
                       );
     
     
     
     markers.push(marker);	
     titles.push(title); 
     //根据id获取表格行号
     var index=$('#table').datagrid('getRowIndex',(carts[i].vehicleId!=null)?carts[i].vehicleId:'');
     
     //触发行选择事件，获取行对应的id号
     var rows=$('#table').datagrid('selectRow',index);
     
     //修改以改变的行
     if(tableid==carts[i].vehicleId){
       $('#table').datagrid('updateRow',{
	    index: i,
	    row: {
		     recvtime:((carts[i].recvtime!=null)?carts[i].recvtime:''),
		     gpstime:((carts[i].gpstime!=null)?carts[i].gpstime:''),
		     state2:((carts[i].state2!=null)?carts[i].state2:''),
		     direct:((carts[i].direct!=null)?carts[i].direct:''),
		     speed:((carts[i].speed!=null)?carts[i].speed:''),
		     oilMN1:((carts[i].oilMN1!=null)?carts[i].oilMN1:''),
		     temp1:((carts[i].temp1!=null)?carts[i].temp1:''),
		     temp2:((carts[i].temp2!=null)?carts[i].temp2:''),
		     temp3:((carts[i].temp3!=null)?carts[i].temp3:''),
		     temp4:((carts[i].temp4!=null)?carts[i].temp4:''),
		     totalDistance:((carts[i].totalDistance!=null)?carts[i].totalDistance:''),
		     lng:((carts[i].lng!=null)?carts[i].lng:''),
		     lat:((carts[i].lat!=null)?carts[i].lat:''),
		     memo:((carts[i].memo!=null)?carts[i].memo:'')
	    }
     });
   } 
 }
}

//清空所有组数据
function deleteALLGroup(){
   var root = $('#tt2').tree('getRoot');
   $('#tt2').tree('remove',root.target);

}

//format组和车信息
function parseGroupAndCart(data){
   var formatStr="[{\"id\":-1,\"text\":\"用户分组\",\"iconCls\":\"icon-ico_server_nor\",\"children\": [";

   var count=data.totalcount;
   var groups=data.data;
   for(var i=0;i<count;i++){

     formatStr=formatStr+"{\"id\":"+groups[i].id +",\"text\": \"" + groups[i].groupName + "\",\"iconCls\":\"icon-ico_fenzu_nor\",\"attributes\":{\"flag\":false},\"state\": \"closed\"";  
     
       var carts=groups[i].data;
       if(carts.length>0){
           var cartsStr=",\"children\": ["
           for(var j=0;j<carts.length;j++){
             cartsStr=cartsStr+"{\"id\":"+carts[j].id +",\"text\": \"" + carts[j].vehicleName + "\",\"iconCls\":\"icon-ico_car_nor\"},";  
           }
           cartsStr=cartsStr.substring(0,cartsStr.length-1);
           cartsStr=cartsStr+"]"; 
           formatStr=formatStr+cartsStr+"},";
       }else{
           formatStr=formatStr+"},";
       }
     
   }
    formatStr=formatStr.substring(0,formatStr.length-1);
    formatStr=formatStr+"]}]";
    return $.parseJSON(formatStr);
}


//format组信息
function praseGroup(data){
   var formatStr="[{\"id\":-1,\"text\":\"用户分组\",\"iconCls\":\"icon-ico_server_nor\",\"children\": [";

   var count=data.totalcount;
   var groups=data.data;
   for(var i=0;i<count;i++){

     formatStr=formatStr+"{\"id\":"+groups[i].id +",\"text\": \"" + groups[i].groupName + "\",\"iconCls\":\"icon-ico_fenzu_nor\",\"attributes\":{\"flag\":true},\"state\": \"closed\"},";  
   }
    formatStr=formatStr.substring(0,formatStr.length-1);
    formatStr=formatStr+"]}]";
    return $.parseJSON(formatStr);
}


//format车辆信息
function praseCart(data){
   var formatStr="{\"data\": [";
   var count=data.totalcount;
   var carts=data.data;
   for(var i=0;i<count;i++){
     formatStr=formatStr+"{\"id\":"+carts[i].id +",\"text\": \"" + carts[i].vehicleName + "\",\"iconCls\":\"icon-ico_car_nor\"},";  
   }
    formatStr=formatStr.substring(0,formatStr.length-1);
    formatStr=formatStr+"]}";
    return $.parseJSON(formatStr);
}
//根据父id formate所有子id
function getIds(nodes){
    var ids="0,";
    for(var i=0;i<nodes.length;i++){
        ids=ids+nodes[i].id+",";
    }
    ids=ids.substring(0,ids.length-1); 
    return ids

} 
//解析方向
function getVhcIcon(runstate, dir)
    {	    	   
		var state = parseInt(runstate);		
		dir=(parseInt(parseInt(dir)/45+'')*45);				
		var pngicon = "image/index/vhc_icons/red_0.gif";
		if(state == 0) pngicon = "image/index/vhc_icons/green_"+dir+".gif";
		else if(state == 1) pngicon = "image/index/vhc_icons/red_"+dir+".gif";
		else if(state == 2) pngicon = "image/index/vhc_icons/gray_"+dir+".gif";
		else if(state == 3) pngicon = "image/index/vhc_icons/yellow_"+dir+".gif";
		else if(state == 4) pngicon = "image/index/vhc_icons/pink_"+dir+".gif";
		else if(state == 5) pngicon = "image/index/vhc_icons/stopalarm.gif";
		else pngicon = "image/index/vhc_icons/black_"+dir+".gif";	   
		return pngicon;
    }

//启动倒计时刷新
$(function(){   
       $('#ss').spinner({       
           increment:1,
           editable:false,
           min:10,
           max:30,
           spin:function(type){
               if(!type){
                 $('#ss').val(parseInt($("#ss").val())+1);
                 
               }else{
                 $('#ss').val(parseInt($("#ss").val())-1);
               }
               //$("#time").text($("#ss").val());
           } 
       });  	  
	   setInterval('autorefersh();', 1000);	
	   
})

function autorefersh(){
	   if($("#time").text()==""){
	     return;
	   }else{
	      var time=parseInt($("#time").text());
	      if(time<1){
	      resfCart();
	      $("#time").text($("#ss").val());
	      return ;
	      }
	      $("#time").text(time-1);
	   }
}
$(function(){
    $("#refersh").click(function(){
          resfCart();
	      $("#time").text($("#ss").val());

   });
});

