var windowId,proName = window.location.pathname.split("/")[1],sysUrl = "http://"+window.location.host+"/"+proName,toEdit;
var result=["12月","11月","10月","09月","08月","07月","06月","05月","04月","03月","02月","01月"];
var videoalarmTree = null;
$(function(){
	initCountTime();
	$("#datetimeStart").datebox("setValue",$.getTodayStart(0,"00:00:00"));
	$("#datetimeEnd").datebox("setValue",$.getTodayEnd("23:59:59"));
	$('#lb').combobox({
		url: 'xtclAction!query_Xtcl.do?csdl=nhywjtsblx',
		textField: "csmc",
		valueField: "csdm",
		panelWidth: 148,
		loadFilter: function (data) {
			return data;
		},
		onChange: function (n, o) {
			if (n == "1") {
				$("#treediv").show();
			} else {
				$("#treediv").hide();
			}

		},
		onLoadSuccess:function(){ //默认选中第一条数据
			var data= $(this).combobox("getData");
			if(data.length>1){
				$('#lb').combobox('select',data[0].csdm);
			}
		}
	});
	initTree();	
	initGrid();	
});

//加载列表
function initGrid(){	
	toolbar = [
	      {
		        text:'统计列表',
		        iconCls:'icon-search',
		        handler:function(){
		        	showList();
		        }
	      },
	      {
		        text:'统计图',
		        iconCls:'icon-search',
		        handler:function(){
		        	showBarChart();
		        }
	      },
		  {
				text:"导出Excel",
				iconCls:"icon-search",
				handler:function(){
					showExport("excel");
				}
			},
			{
				text:"导出PDF",
				iconCls:"icon-search",
				handler:function(){
					showExport("pdf");
				}
			},
			{
				text:"计算公式",
				iconCls:"icon-search",
				handler:function(){
					lookJsgs();
				}
			},{
				text:"打印",
				iconCls:"icon-search",
				handler:function(){
					dayin();
				}
			}
	];
	showList();
}

//加载统计时间

function initCountTime(){
	var date=new Date();
	var year=date.getFullYear();
	var month=date.getMonth()+1;
	var str=year+"年"+month+"月";	
	$.each(result,function(i,v){
		result[i]=year+"年"+result[i];
	});
	result.unshift("自定义时间");
	$('#countTime').combobox({  
		data : $.obj2ary(result),  
		textField:1,  
		valueField:0,
		panelWidth:148,
		value:str,
		onSelect:function(record){
			var value=record[1].trim();
			if(value=='自定义时间'){
				$("#controlDate").show();
			}else{
				$("#controlDate").hide();
			}
		}
	});
}

$.extend($.fn.datagrid.methods,
		{
	renderAlarmOverviewData:function(n, g, h){
		 var m = n.parent(".datagrid-view:eq(0)"),c;
         var k = m.prev("div").append("<table cellspacing=0 cellpadding=0 style='display:inline-block;height:26px;float:right;'><tbody><tr/></tbody></table>").children("table:eq(1)").find("tbody tr");
         var b = m.parent().height();
         var o = m.parent().width();
         if (!m.next("div.imgcontainer").html()) {
             c = $("<div class='imgcontainer' style='overflow-y:auto; width:99%;height:" + (b - 70) + "px;'></div>");
             m.after(c)
         } else {
             c = m.next("div.imgcontainer")
         }
         if (!g) {
             return
         }
         var f = 0,l = [],e,d,
         j = this;
         var nowTime = getNowTime("-");
         var TABLE='<table  cellspacing="0"  width="90%"  cellpadding="0"  border="1"  align="center"  style="text-align:center;margin:0 auto;	border:1px solid #827d7d;font-size:12px;">\
		           				<thead>\
						        	<tr>\
										<td colspan="7" style="font-size:14px;font-weight:bold;border:none">区域在线率统计</td>\
									</tr>\
						        	<tr style="border-top: 1px solid #827d7d;">\
										<td colspan="7" style="text-align:right;padding: 15px;border:none" id="zbsj">制表时间：'+nowTime+'</td>\
									</tr>\
		           					<tr>\
		           						<td >序号</td>\
        	 							<td>行政区划</td>\
        	 							<td>点位总数</td>\
        	 							<td>未巡检数</td>\
        	 							<td>在线数</td>\
        	 							<td>离线数</td>\
        	 							<td>在线率</td>\
		           					</tr>\
			           			</thead>\
        	 	<tbody>'
		 var zs = 0;
         var zwxjs = 0;
         var zzxs = 0;
         var zlxs = 0;
         
         var total = g.totalSize;
         if(total!=null && total>0){
        	 for (; (g.data[f]); f++) {
            	 var xzmc = g.data[f].xzmc==null?"-":g.data[f].xzmc;
            	 var dwzs = g.data[f].mcount;				//点位总数
            	 var wxjs = g.data[f].wxj;					//未巡检数
            	 var zxs = g.data[f].onlinecount;
            	 var lxs = g.data[f].notonlinecount;
            	 var zxl = 0;
            	 var linecount = parseInt(zxs)+parseInt(lxs);
            	 if(linecount != 0){
            		 zxl = zxs/linecount;       		 
            	 }
            	 if(zxl != 0){        		
            		 zxl = zxl*100; 
            		 zxl = zxl.toFixed(2)+"%";
            	 }
            	 zs = zs + parseInt(dwzs);
            	 zwxjs = zwxjs + parseInt(wxjs);
            	 zzxs = zzxs + parseInt(zxs);
            	 zlxs = zlxs + parseInt(lxs);
            	 TABLE+='<tr>\
	     		 		<td>'+(f+1)+'</td>\
	     		 		<td>'+xzmc+'</td>\
	     		 		<td><a href="javascript:void(0);" class="ahref" onclick="shownArea(\''+g.data[f].xzqh+'\',\''+xzmc+'\',1)">'+dwzs+'</a></td>\
	     		 		<td>'+wxjs+'</td>\
	     		 		<td><a href="javascript:void(0);" class="ahref" onclick="shownArea(\''+g.data[f].xzqh+'\',\''+xzmc+'\',3)">'+zxs+'</a></td>\
	     		 		<td><a href="javascript:void(0);" class="ahref" onclick="shownArea(\''+g.data[f].xzqh+'\',\''+xzmc+'\',4)">'+lxs+'</a></td>\
	     		 		<td>'+zxl+'</td>\
	     	 		 <tr>'
             }
             var zlinecount = parseInt(zzxs)+parseInt(zlxs);
             var zzsl = 0;
             if(zlinecount != 0){
            	 zzsl = zzxs/zlinecount;       	 
             }
             if(zzsl != 0){
            	 zzsl = zzsl*100;
            	 zzsl = zzsl.toFixed(2)+"%";
             }
             TABLE+="<tr>" +
             			"<td colspan='2'>总计</td>" +
             			"<td>"+zs+"</td>" +
             			"<td>"+zwxjs+"</td>" +
             			"<td>"+zzxs+"</td>" +
             			"<td>"+zlxs+"</td>" +
             			"<td>"+zzsl+"</td>" +
             		"<tr>"
         }else{
        	 TABLE+="<tr><td colspan='7'>暂无数据</td></tr>";
         }
         
		TABLE+='</tbody></table> '
         c.html('<div class="img-box"  style="margin:0 auto;">'+ TABLE+'</div>')
     }
});

//查询条件
function getQueryParams(){
	var sParam = {};
	// if(treeSelectId == ''){				// 本地目录
	// 	treeSelectId = "-1";
	// }
	sParam.alarmdevicetype = $('#lb').combobox("getValue")==""?"1": $('#lb').combobox("getValue");
	if(videoalarmTree!=null &&  videoalarmTree!=undefined ) {
		var videoalarm =videoalarmTree.getSelectedIds();
		if(videoalarm!=null && videoalarm.length>0)
		{
			//讲数组赋值给行政区划的值['1','2']
			sParam.xzbh = videoalarm.join(",");
		}
	}
//	console.log("查询：",sParam);
	return sParam;
}


//列表展示
function showList(){
	$("#searchGridListDiv").show();
	$("#searchGridPicDiv").hide();
	displayType = "list";
	$('#searchGridList').datagrid({
		toolbar : toolbar,
		bodyCls:'pic-datagrid',
		rownumbers:false,
		queryParams:getQueryParams(),
		url : 'ywvideocurrentstateAction!countAreaOnlineByPage.do',
		/*columns : [[
			{field: 'A',checkbox:'true',width:30},
			{field:'xzmc',title:'行政区划',hidden:false,width:120},
			{field:'mcount',title:'总点位数',hidden:false,width:120},
			{field:'wxj',title:'未巡检数',hidden:false,width:120},
			{field:'onlinecount',title:'在线数',hidden:false,width:120},	
			{field:'notonlinecount',title:'离线数',hidden:false,width:120},	
		]],*/
		onLoadSuccess:function(data){
//	    	  console.log("data",data)
			if(data){
				data.data=data.rows;
				data.totalSize=data.total;
				$('#searchGridList').datagrid("renderAlarmOverviewData",data);
			}
		},

	});	
}



function showExport(type){

//	$.showMsg("待开发！");
	var model = getQueryParams();
	$.ajax({
		type : 'post',
		dataType : 'json',
		data : model,
		url : 'ywvideocurrentstateAction!count_areaOnline.do',
		success : function(value) {
			if(value){
				countExport(value,type);
			}else{
				$.showMsg("暂无数据");
			}
		}
	});
}
//导出传参条件
function countExport(totalSize,type) {
	var limit = 5000;
	if (totalSize > 5000) {
		top.$.dlg.confirm('记录过多支持前5000条,确定要将记录导出Excel为表格吗?',function(){ 
			execExport(type);
		});		
	} else {
		top.$.dlg.confirm('确认导出?',function(){ 
			execExport(type);
		})
	}
}
// 调用后台
function execExport(type) {
	var model = getQueryParams();
	var downParam = "";

	var areacode = model.xzqh;

	downParam = "xzqh="+areacode;
	if(type=="pdf"){
		document.excelForm.action = 'ywvideocurrentstateAction!expPDF_AreaOnline.do?'+downParam;
	}else{
		document.excelForm.action = 'ywvideocurrentstateAction!exp_AreaOnline.do?'+downParam;
	}
		
	document.excelForm.submit(); 
}


function showBarChart(){
	
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywvideocurrentstateAction!count_showBar.do',
		data : getQueryParams(),
		success : function(res){
//			console.log("结果：",res);
			if(res){
				$("#searchGridPicDiv").show();
				$("#searchGridListDiv").hide();
				$("#searchGridPic").remove();
				$("#searchGridPicDiv").append($("<div id='searchGridPic'  style='height:100%;width:100%;'></div>"));
				var xData=[];
				var zs=[];
				var wxjs=[];
				var zxs=[];
				var lxs=[];
				res.forEach(function(item,index){
//					console.log(index,item);
					xData[index] = item.xzmc;
					zs[index] = item.mcount;
					wxjs[index] = item.wxj;
					zxs[index] = item.onlinecount;
					lxs[index] = item.notonlinecount;
				})
				var data={
						"title":"区域在线率统计",
						"xAxis": xData,
						"legend":[
						          {"name":"点位总数", "data":zs,   "color":"blue"},
						          {"name":"未巡检数", "data":wxjs, "color":"yellow"},
						          {"name":"在线数",   "data":zxs, "color":"green"},
						          {"name":"离线数",   "data":lxs, "color":"red"},
						        ]
				};
				$('#searchGridStatics').datagrid({ toolbar : toolbar});
				EchartsBase.barChart({
					id:"searchGridPic",
					data:data
				});
			}
		}
	})
}

function showLineChart(){

	$("#searchGridPicDiv").show();
	$("#searchGridListDiv").hide();
	$("#searchGridPic").remove();
	$("#searchGridPicDiv").append($("<div id='searchGridPic'  style='height:100%;width:100%;'></div>"));
	var data={"title":"区域一机一档监控设备情况统计",xAxis: ["监控","NVR","服务器","应用系统"],"legend":[{"name":"Doset","data":[5, 20, 36, 50],"color":"green"},{"name":"Yeland","data":[51, 210, 36, 10],"color":"blue"},{"name":"Yeland1","data":[21,12,13,14],"color":"red"}]};

	$('#searchGridStatics').datagrid({ toolbar : toolbar});
	//$("#searchGridPic").empty();
	EchartsBase.lineChart({
		id:"searchGridPic",
		data:data
	});
	
}

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($("#deviceName"), setting, data);
    //         }
    //     }
    // });
	$.ajax({
		type: 'post',
		dataType: 'json',
		url: 'ptxzsAction!query_PtxzsTree.do',
		data: {
			order: " order by jdpx asc "
		},
		success: function (data) {
			videoalarmTree = $('#xzbh').comboTree({
				source: data,
				isMultiple: true,
				cascadeSelect: true,
				collapse: false
			});
		}
	});
}

function zTreeOnClick(event, treeid, treeNode) {
    treeSelectId = treeNode.id;
}


function shownArea(xzbh,xzmc,flag){	
	var zbsj = $('#zbsj').html();
	var title = "";
	var tableparam = "";
	var params = getQueryParams();
	params.zbsj = zbsj;
	params.xzbh = xzbh;
	params.xzmc = xzmc;
	params.alarmdevicetype = $('#lb').combobox("getValue")==""?"1": $('#lb').combobox("getValue");
	if(flag==1){
		title="总数";
	}else if(flag==2){
		title = "未巡检数";
		//tableparam = " and b.currentstateid is null";
	}else if(flag==3){
		title = "在线数";
		tableparam = " and b.isonline=1  "
	}else if(flag==4){
		title = "离线数";
		tableparam = " and b.isonline=0  "
	}
	params.tableparam = tableparam;
	params.title = title;
	windowId = top.$.createWin({
		title : "详细信息",
		width : 700,
		height : 550,
		data : params,
		onClose:function(){
			var win		=	$.getTopWindowById(windowId);
			win.window('close');
		},
		url : sysUrl+"/yw/operationcount/videoarchivecount/onlinecount/shownOnline.jsp"
	});
}


function lookJsgs(){
	windowId = top.$.createWin({
		title : '计算公式',
		width  :  '400',
		height :  '200',
		onClose:function(){
			var win		=	$.getTopWindowById(windowId);
			win.unloadWindow();
		},
		url : sysUrl+"/yw/operationcount/videoarchivecount/onlinecount/lookJsgs.jsp"
	});
}

function getNowTime(flag){
	var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
	var minute = date.getMinutes();
	var second = date.getSeconds();
	var minsec = date.getMilliseconds(); //获取当前毫秒数(0-999)
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;
    hour = hour < 10 ? '0' + hour : hour;
    second = second < 10 ? '0' + second : second;
    if(flag == "-"){
    	return year +"-"+ month +"-"+ day +" "+ hour +":"+ minute +":"+ second;
    }else{
    	return "" + year + month + day + hour + minute + second + minsec;
    }  
}




/*function dayin(){
	var userAgent = navigator.userAgent.toLowerCase(); //取得浏览器的userAgent字符串
	if (userAgent.indexOf("trident") > -1){
		alert("请使用google或者360浏览器打印");
		return false;
	}else if(userAgent.indexOf('msie')>-1){ 
		var onlyChoseAlert = simpleAlert({
           "content":"请使用Google或者360浏览器打印",
           "buttons":{
               "确定":function () {
                   onlyChoseAlert.close();
               }
           }
       })
		alert("请使用google或者360浏览器打印");
		return false;
	}else{//其它浏览器使用lodop
//		var oldstr = document.body.innerHTML; 
		var headstr = "<html><head><title></title></head><body>";  
		var footstr = "</body>";  
		//执行隐藏打印区域不需要打印的内容
//		document.getElementById("searchGridPicDiv").style.display="none";
		$('.datagrid-toolbar').hide();
		//获得 div 里的所有 html 数据
		var printData = document.getElementById("searchGridListDiv").innerHTML; 
		document.body.innerHTML = headstr+printData+footstr;
		window.print();
		//打印结束后，放开隐藏内容
//		document.getElementById("searchGridPicDiv").style.display="block";
		$('.datagrid-toolbar').show();
//		document.body.innerHTML = oldstr ;
		window.location.reload();
	}
}*/



function dayin() {
	var userAgent = navigator.userAgent.toLowerCase(); //取得浏览器的userAgent字符串
	if (userAgent.indexOf("trident") > -1) {
		alert("请使用google或者360浏览器打印");
		return false;
	} else if (userAgent.indexOf('msie') > -1) {
		var onlyChoseAlert = simpleAlert({
			"content" : "请使用Google或者360浏览器打印",
			"buttons" : {
				"确定" : function() {
					onlyChoseAlert.close();
				}
			}
		})
		alert("请使用google或者360浏览器打印");
		return false;
	} else {//其它浏览器使用lodop
		
		
		var params = getQueryParams();
		var data = {};
		params.rows=10000;
		params.page=1;
		$.ajax({
			type : 'post',
			dateType : 'json',
			url : 'ywvideocurrentstateAction!countAreaOnlineByPage.do',
			data : params,
			async : false,
			success : function(res){
				console.log("打印：",res);
				if(res == null){
					$.showMsg("暂无数据！");
					return;
				}else{
					if(res.total>0){
						data = res;
					}else{
 						$.showMsg('暂无记录!');
						return;
					}
				}
				
			}
		})
		
		
		var g = {"data":data.rows,"totalSize":data.total}
		var f=0;
		
		var nowTime = getNowTime("-");
        var TABLE='<table  cellspacing="0"  width="90%"  cellpadding="0"  border="1"  align="center"  style="text-align:center;margin:0 auto;	border:1px solid #827d7d;font-size:12px;">\
		           				<thead>\
						        	<tr>\
										<td colspan="7" style="font-size:14px;font-weight:bold;border:none">区域在线率统计</td>\
									</tr>\
						        	<tr style="border-top: 1px solid #827d7d;">\
										<td colspan="7" style="text-align:right;padding: 15px;border:none" id="zbsj">制表时间：'+nowTime+'</td>\
									</tr>\
		           					<tr>\
		           						<td >序号</td>\
       	 							<td>行政区划</td>\
       	 							<td>点位总数</td>\
       	 							<td>未巡检数</td>\
       	 							<td>在线数</td>\
       	 							<td>离线数</td>\
       	 							<td>在线率</td>\
		           					</tr>\
			           			</thead>\
       	 	<tbody>'
		var zs = 0;
        var zwxjs = 0;
        var zzxs = 0;
        var zlxs = 0;
        
        var total = g.totalSize;
        if(total!=null && total>0){
       	 for (; (g.data[f]); f++) {
           	 var xzmc = g.data[f].xzmc==null?"-":g.data[f].xzmc;
           	 var dwzs = g.data[f].mcount;				//点位总数
           	 var wxjs = g.data[f].wxj;					//未巡检数
           	 var zxs = g.data[f].onlinecount;
           	 var lxs = g.data[f].notonlinecount;
           	 var zxl = 0;
           	 var linecount = parseInt(zxs)+parseInt(lxs);
           	 if(linecount != 0){
           		 zxl = zxs/linecount;       		 
           	 }
           	 if(zxl != 0){        		
           		 zxl = zxl*100; 
           		 zxl = zxl.toFixed(2)+"%";
           	 }
           	 zs = zs + parseInt(dwzs);
           	 zwxjs = zwxjs + parseInt(wxjs);
           	 zzxs = zzxs + parseInt(zxs);
           	 zlxs = zlxs + parseInt(lxs);
           	 TABLE+='<tr>\
	     		 		<td>'+(f+1)+'</td>\
	     		 		<td>'+xzmc+'</td>\
	     		 		<td><a href="javascript:void(0);" class="ahref" onclick="shownArea(\''+g.data[f].xzbh+'\',\''+xzmc+'\',1)">'+dwzs+'</a></td>\
	     		 		<td><a href="javascript:void(0);" class="ahref" onclick="shownArea(\''+g.data[f].xzbh+'\',\''+xzmc+'\',2)">'+wxjs+'</a></td>\
	     		 		<td><a href="javascript:void(0);" class="ahref" onclick="shownArea(\''+g.data[f].xzbh+'\',\''+xzmc+'\',3)">'+zxs+'</a></td>\
	     		 		<td><a href="javascript:void(0);" class="ahref" onclick="shownArea(\''+g.data[f].xzbh+'\',\''+xzmc+'\',4)">'+lxs+'</a></td>\
	     		 		<td>'+zxl+'</td>\
	     	 		 <tr>'
            }
            var zlinecount = parseInt(zzxs)+parseInt(zlxs);
            var zzsl = 0;
            if(zlinecount != 0){
           	 zzsl = zzxs/zlinecount;       	 
            }
            if(zzsl != 0){
           	 zzsl = zzsl*100;
           	 zzsl = zzsl.toFixed(2)+"%";
            }
            TABLE+="<tr>" +
            			"<td colspan='2'>总计</td>" +
            			"<td>"+zs+"</td>" +
            			"<td>"+zwxjs+"</td>" +
            			"<td>"+zzxs+"</td>" +
            			"<td>"+zlxs+"</td>" +
            			"<td>"+zzsl+"</td>" +
            		"<tr>"
        }else{
       	 TABLE+="<tr><td colspan='7'>暂无数据</td></tr>";
        }
        
		TABLE+='</tbody></table> '
		
		
//		var oldstr = document.body.innerHTML;
		var headstr = "<html><head><title></title></head><body>";
		var footstr = "</body></html>";
		//执行隐藏打印区域不需要打印的内容
//		document.getElementById("searchGridPicDiv").style.display="none";
//		$('.datagrid-toolbar').hide();
//		$('.pagination').hide();
//		var printData = document.getElementById("searchGridListDiv").innerHTML; //获得 div 里的所有 html 数据

		var wind = window.open("", "newwin","toolbar=no,scrollbars=yes,menubar=no");
		wind.document.body.innerHTML = headstr + TABLE + footstr;
		wind.print();
		//打印结束后，放开隐藏内容
//		document.getElementById("searchGridPicDiv").style.display="block";
//		$('.datagrid-toolbar').show();
		wind.close();
//		window.document.body.innerHTML = oldstr;
//		window.location.reload()
	}
}

 
