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 treeSelectId = "-1";
$(function(){
	initCountTime();
	$("#datetimeStart").datebox("setValue",$.getTodayStart(0,"00:00:00"));
	$("#datetimeEnd").datebox("setValue",$.getTodayEnd("23:59:59"));
	
	initTree();	
	initGrid();	
});
		
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);
            }
        }
    });

}

function zTreeOnClick(event, treeid, treeNode) {
    treeSelectId = treeNode.id;
}
//加载列表
function initGrid(){	
	toolbar = [
	      {
		        text:'统计列表',
		        iconCls:'icon-search',
		        handler:function(){
		        	showList();
		        }
	      },
	      {
		        text:'饼图',
		        iconCls:'icon-search',
		        handler:function(){
		        	showPie();
		        }
	      },
	      {
		        text:'柱状图',
		        iconCls:'icon-search',
		        handler:function(){
		        	showBarChart();
		        }
	      }
	      ,
		  {
				text:"导出",
				iconCls:"icon-search",
				handler:function(){
					showExport();
				}
			}
	];
	showList();
}

//加载统计时间

function initCountTime(){
	var flag=false;
	var date=new Date();
	var year=date.getFullYear();
	var month=date.getMonth()+1;
	var str=year+"年"+(month<10?"0"+month:month)+"月";
	var result=[12,11,10,9,8,7,6,5,4,3,2,1];
	result=result.filter(function(value){
		if(month==value){
			flag=true;
		}
		if(flag){
			if(value<10){
				return "0"+value;
			}else{
				return ""+value;
			}
		}
	});
	$.each(result,function(i,v){
		if(result[i]<10){
			result[i]=year+"年0"+result[i]+"月";
		}else{
			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();
			}
		}
	});
}

function getCurrtentTime(){
	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();
	if(month<10){
		month = "0"+month;
	}
	if(day<10){
		day = "0"+day;
	}
	if(hour<10){
		hour = "0"+hour;
	}
	if(minute<10){
		minute = "0"+minute;
	}
	if(second<10){
		second = "0"+second;
	}
	console.log(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);
	return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second; 
}
$.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 style="height: 40px;">\
										<td colspan="9" style="font-weight:bold;border:none;font-size:14px;">区域一机一档监控设备情况统计</td>\
									</tr>\
						        	<tr style="border-top: 1px solid #827d7d;">\
										<td colspan="9" style="text-align:right;padding: 15px;border:none" id="zbsj">制表时间：'+getCurrtentTime()+'</td>\
									</tr>\
		           					<tr>\
		           						<td rowspan="2">序号</td>\
        	 							<td rowspan="2">行政区划</td>\
        	 							<td rowspan="2" >点位总数</td>\
        	 							<td colspan="2">联网属性</td>\
        	 							<td colspan="4">监控类型</td>\
		           					</tr>\
		           					<tr>\
		           						<td >已联网</td>\
        	 							<td>未联网</td>\
        	 							<td >一类视频监控点</td>\
        	 							<td>二类视频监控点</td>\
        	 							<td >三类视频监控点</td>\
        	 							<td>公安内部监控点</td>\
		           					</tr>\
			           			</thead>\
        	 	<tbody>'
         for (; (g.data[f]); f++) {
        	TABLE+='<tr>\
        		 		<td>'+(f+1)+'</td>\
        		 		<td>'+g.data[f].areaname+'</td>\
        		 		<td>'+g.data[f].monitortotal+'</td>\
        		 		<td>'+g.data[f].networkcount+'</td>\
        		 		<td><a href="javascript:void(0);" class="ahref" onclick="shownotnetwork('+g.data[f].areanum+')">'+g.data[f].notnetworkcount+'</a></td>\
        		 		<td>'+g.data[f].firstmonitorcount+'</td>\
        		 		<td>'+g.data[f].secondmonitorcount+'</td>\
        		 		<td>'+g.data[f].thirdmonitorcount+'</td>\
        		 		<td>'+g.data[f].policemonitorcount+'</td>\
        	 		 <tr>'
         }
		TABLE+='</tbody></table> '
         c.html('<div class="img-box"  style="margin:0 auto;">'+ TABLE+'</div>')
     }
});

//查询条件
function getQueryParams(){
	var sParam = {};
	var countTime = $('#countTime').combobox("getText");
	var datetimeStart = $('#datetimeStart').datebox("getValue");
	var datetimeEnd = $('#datetimeEnd').datebox("getValue");


	var countMonth = "";
	var countDateStart = "";
	var countDateEnd = "";
	if(treeSelectId == '-1'){				// 本地目录
		treeSelectId = "";
	}
	if("自定义时间"==countTime){
//		sParam.countMonth = $("#datetime").datebox("getValue");	
		countDateStart = datetimeStart;
		countDateEnd = datetimeEnd;
	}else{
		sParam.countMonth = countTime.replace("年","-").replace("月","");
	}
	/*
	if(countTime.indexOf("年") != -1){				// 是当前月份
		var date=new Date();
		var year=date.getFullYear();
		var month=date.getMonth()+1;
		if(month < 10){
			countMonth = year + "-0" + month;
		}else{
			countMonth = year + "-" + month;
		}
	}else if(countTime == 0){				// 自定义时间
//		countDateStart = datetimeStart.substring(0,10);
//		countDateEnd = datetimeEnd.substring(0,11);
		countDateStart = datetimeStart;
		countDateEnd = datetimeEnd;		
	}else{
		countMonth = result[countTime];
		countMonth = countMonth.replace("年","-").replace("月","-");
		countMonth = countMonth.substring(0,countMonth.length-1);
	}*/
	sParam.countDateStart = countDateStart;
	sParam.countDateEnd = countDateEnd;
//	sParam.countMonth = countMonth;
	sParam.areanum = treeSelectId;
//	console.log("查询：",sParam);
	sParam.order = " order by updateTime desc"
	return sParam;
}


//列表展示
function showList(){
	$("#searchGridListDiv").show();
	$("#searchGridPicDiv").hide();
	displayType = "list";
	$('#searchGridList').datagrid({
		toolbar : toolbar,
		bodyCls:'pic-datagrid',
		rownumbers:true,
		queryParams:getQueryParams(),
		url : 'ywcountvideoarchiveAction!listYwcountvideoarchiveByPage.do',
		columns : [[
			{field: 'A',checkbox:'true',width:30},
			{field:'areanum',title:'行政区划编号',hidden:false,width:120},
			{field:'areaname',title:'行政区划名称',hidden:false,width:120},
			{field:'countDate',title:'统计日期',hidden:false,width:120},
			{field:'monitortotal',title:'监控点总数',hidden:false,width:120},
			{field:'networkcount',title:'已联网数量',hidden:false,width:120},
			{field:'notnetworkcount',title:'未联网数量',hidden:false,width:120},
			{field:'firstmonitorcount',title:'一类视频监控点数量',hidden:false,width:120},
			{field:'secondmonitorcount',title:'二类视频监控点数量',hidden:false,width:120},
			{field:'thirdmonitorcount',title:'三类视频监控点数量',hidden:false,width:120},
			{field:'policemonitorcount',title:'公安内部监控点数量',hidden:false,width:120},
			{field:'onmaprate',title:'上图量',hidden:false,width:120},
			{field:'completerate',title:'完整量',hidden:false,width:120},
			{field:'newnetwork',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(){

	var model = getQueryParams();
	$.ajax({
		type : 'post',
		dataType : 'json',
		data : model,
		url : 'ywcountvideoarchiveAction!count_Ywcountvideoarchive.do',
		success : function(value) {
			if(value==0){
				$.showMsg("暂无数据！");								
			}else if(value){
				countExport(value);
			}else{
				$.showMsg("操作失败！");
			}
		}
	});
}
//导出传参条件
function countExport(totalSize) {
	var limit = 5000;
	if (totalSize > 5000) {
		top.$.dlg.confirm('记录过多支持前5000条,确定要将记录导出Excel为表格吗?',function(){ 
			execExport();
		});		
	} else {
		top.$.dlg.confirm('确认导出?',function(){ 
			execExport();
		})
	}
}
// 调用后台
function execExport() {
	var model = getQueryParams();
	var downParam = "";
	
	var countDateStart = model.countDateStart;
	var countDateEnd = model.countDateEnd;
	var countMonth = model.countMonth;
	var areanum = model.areanum;
	
	downParam = "areanum="+areanum+"&countMonth="+countMonth+"&countDateStart="+countDateStart+"&countDateEnd="+countDateEnd;
	
	document.excelForm.action = 'ywcountvideoarchiveAction!exp_Ywcountvideoarchive.do?'+downParam;
	document.excelForm.submit(); 
}

function showPie(){
	
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountvideoarchiveAction!count_showPie.do',
		data : getQueryParams(),
		success : function(res){
			console.log("结果：",res);
			if(res){
				var networkcount = res.networkcount;       // 已联网数量
				var notnetworkcount = res.notnetworkcount; // 未联网数量
				var firstmonitorcount = res.firstmonitorcount;  // 一类视频数量
				var secondmonitorcount = res.secondmonitorcount; // 二类视频数量
				var thirdmonitorcount = res.thirdmonitorcount;   // 三类视频数量
				var policemonitorcount = res.policemonitorcount; // 公安内部监控点数量
				var onmaprate = res.onmaprate;					// 上图量
				var completerate = res.completerate;			// 完整量
				var newnetwork = res.newnetwork;				// 新增联网数
				
				var pie={"title":"区域一机一档监控设备情况统计",
						data:[
							  {name:"已联网数量",value:networkcount,color:"red"},
							  {name:"未联网数量",value:notnetworkcount,color:"blue"},
							  {name:"一类视频数量",value:firstmonitorcount,color:"green"},
							  {name:"二类视频数量",value:secondmonitorcount,color:"yellow"},
							  {name:"三类视频数量",value:thirdmonitorcount,color:"pink"},
							  {name:"公安内部监控点数量",value:policemonitorcount,color:"brown" },
							 /* {name:"上图量",value:onmaprate,color:"black "},
							  {name:"完整量",value:completerate,color:"purple"},
							  {name:"新增联网数",value:newnetwork,color:"orange"},*/
						]		
					}
				$("#searchGridPicDiv").show();
				$("#searchGridListDiv").hide();
				$("#searchGridPic").remove();
				$("#searchGridPicDiv").append($("<div id='searchGridPic'  style='height:100%;width:100%;'></div>"));
				$('#searchGridStatics').datagrid({ toolbar : toolbar});
				
				EchartsBase.pieChart({
					id:"searchGridPic",
					data:pie
				});
			}
		}
	})
	
	
	/*$("#searchGridPicDiv").show();
	$("#searchGridListDiv").hide();
    var data={"title":"区域一机一档监控设备情况统计",data:[{name:"直接访问",value:335,color:"red"},{name:"邮件营销",value:310,color:"blue"},
    	{name:"联盟广告",value:234,color:"green"},{name:"视频广告",value:135,color:"yellow"},{name:"搜索引擎",value:1548,color:"pink"}]};

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

function showBarChart(){
	
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountvideoarchiveAction!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=[],yData=[];
				res.forEach(function(item,index){
//					console.log(index,item);
					xData[index]=item.areaname;
					yData[index]=item.monitortotal;
				})
				var data={"title":"区域一机一档监控设备情况统计","xAxis":xData,"yData":yData,"color":"green"}
				$('#searchGridStatics').datagrid({ toolbar : toolbar});
				EchartsBase.barChart({
					id:"searchGridPic",
					data:data
				});
			}
		}
	})
	/*$("#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});
	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 shownotnetwork(areanum){	

	var zbsj = $('#zbsj').html();
	
	var params = getQueryParams();
	params.zbsj = zbsj;
	params.areanum = areanum;
//	console.log("参数",params);
//	var params = {"zbsj":zbsj,"areanum":areanum};
	windowId = top.$.createWin({
		title : '查看详情',
		width : 600,
		height : 450,
		data : params,
		url : sysUrl+"/yw/operationcount/videoarchivecount/yjydDefault/notnetwork.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;
    }  
}