var windowId,proName = window.location.pathname.split("/")[1],sysUrl = "http://"+window.location.host+"/"+proName,toEdit;
var records = [];
var date = new Date();
var nowDate = date.getFullYear()+"-"+(date.getMonth()+1);
var flag=true;
var treeSelectId = "-1";
$(function(){
	initTree();
	initTime();
	$("#timeTJ").text("制表时间："+getCurrtentTime());
	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($("#xzmc"), setting, data);
            }
        }
    });

}

function zTreeOnClick(event, treeid, treeNode) {
    treeSelectId = treeNode.id;
}
//初始化查询时间，默认当前一星期
function initTime(){
	var endDate = new Date();
	var year = endDate.getFullYear();
	var month = endDate.getMonth()+1;
	var day = endDate.getDate()
	if(day<10){
		day = "0"+day;
	}
	if(month<10){
		month = "0"+month;
	}
	$("#datetimeEnd").datebox("setValue",year +"-"+month+"-"+day);
	var startDate = new Date(endDate.getTime()-86400000*7);
	var yearStart = startDate.getFullYear();
	var monthStart = startDate.getMonth()+1;
	var dayStart = startDate.getDate()
	if(dayStart<10){
		dayStart = "0"+dayStart;
	}
	if(monthStart<10){
		monthStart = "0"+monthStart;
	}
	$("#datetimeStart").datebox("setValue",yearStart +"-"+monthStart+"-"+dayStart);
	
}
//加载列表
function initGrid(){	
	showList();
}



//查询条件
function getQueryParams(){
var sParam = {};
	
	sParam.page = 1;
	sParam.rows = 5000;
	sParam.order = "order by areanum desc ";
	var datetimeStart = $('#datetimeStart').datebox("getValue");	
	var datetimeEnd = $('#datetimeEnd').datebox("getValue");	
	var tableparam = "";
	if (treeSelectId != '-1') {
		sParam.areanum = treeSelectId;
	}
	if(!(datetimeStart==null||datetimeStart==""||datetimeStart==undefined)){
		tableparam += " AND countDate >= '" +datetimeStart + "'";
	}
	if(!(datetimeEnd==null||datetimeEnd==""||datetimeEnd==undefined)){
		tableparam += " AND countDate <= '" +datetimeEnd + "'";
	}
	sParam.tableparam = tableparam;
	return sParam;
}
//列表展示
function showList(page,rows){
	$("#searchGridListDiv").show();
	$("#searchGridPicDiv").hide();
	displayType = "list";
	var params = getQueryParams();		
	if(page == undefined || page==null){       // 页码
		page = 1;
	} 
	if(rows == undefined || rows==null){       //每页10条
		rows = 10;
	} 
	params.page = page;			
	params.rows = rows;	
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountarearecordAction!listareaRecordCount.do',
		data : params,
		success : function(res){
			console.log("----",res);
			renderTable(res);
		}
	});
}


function showGraph(){
	$("#searchGridPicDiv").show();
	$("#searchGridListDiv").hide();
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountarearecordAction!listareaRecordCount.do',
		data : getQueryParams(),
		success : function(res){
			if(res && res.total>0){
				$("#noData").css("display","none");
				$("#searchGridGraph").css("display","block");
				var x = [];
				var recordnormalnum = [];
				var recordabnormalnum = [];
				var totalnum = [];
				var rows = res.rows
				for(var i=0;i<rows.length-1;i++){
					x.push(rows[i].areaname);
					recordnormalnum.push(transStr2Int(rows[i].recordnormalcount));
					recordabnormalnum.push(transStr2Int(rows[i].recordabnormalcount));
//					totalnum.push(transStr2Int(rows[i].totalNum));
				}
				var data={
						"title":"区域录像情况统计",
						xAxis: x,//["监控","NVR","服务器","应用系统"],
						"legend":[
//						          {"name":"在线数", "data":zxnum,"color":"yellow"},
//						          {"name":"录像总数","data":totalnum,"color":"blue"},
						          {"name":"录像正常数","data":recordnormalnum,"color":"green"},
						          {"name":"录像异常数","data":recordabnormalnum,"color":"gray"},
						          ]};
				EchartsBase.barChart({
					id:"searchGridGraph",
					data:data
				});
			}else{
				$("#noData").css("display","block");
				$("#searchGridGraph").css("display","none");
			}
		}
	});
	
}
function showRecord(title,state,type,name,xzqh){
	var url = top.sysUrl+"/yw/operationcount/arearecordcount/showRecord.jsp";
	windowid = top.$.createWin({
		 title	: 	title,
		 width  :  '720',
		 height :  '400',
		 data:{state:state,type:type,name:name,xzqh:xzqh},
		 url	:  url
	 });
}

function showCompute(id){
	var url = top.sysUrl+"/yw/operationcount/arearecordcount/showCompute.jsp";
	windowid = top.$.createWin({
		title	: 	'计算公式',
		width  :  '400',
		height :  '400',
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:savecomputingInfo
		}],
		data:id,
		url	:  url
	});
}
function savecomputingInfo(){



}
function renderTable(res){
	console.log("结果：",res);
	var table = '';
	if(res && res.total>0){
		var rows = res.rows;

		for (var i=0 ; i<rows.length-1; i++) {
			table += '<tr>\
				<td>'+(i+1)+'</td>\
				<td>'+rows[i].areaname+'</td>\
				<td>'+rows[i].totalnum+'</td>\
				<td>'+rows[i].notconfignum+'</td>\
				<td>'+rows[i].recordnormalcount+'</td>\
				<td>'+rows[i].recordabnormalcount+'</td>\
				<td>'+rows[i].recordintactrate+'</td>\
				<tr>'
		}
		//总计
		var totalObj = rows[rows.length-1];
		table += '<tr>\
		<td colspan="2">总计</td>\
		<td>'+totalObj.totalSum+'</td>\
		<td>'+totalObj.notconfigSum+'</td>\
		<td>'+totalObj.recordnormalSum+'</td>\
		<td>'+totalObj.recordabnormalSum+'</td>\
		<td>'+totalObj.recordintactrate+'</td>\
		<tr>'
	}else{
		table += '<tr> <td colspan="7">暂无数据</td> <tr>';
	}
	 

	$("#searchGridList").html(table); 
	var total = res.total;
	if(total>0){
		$('#pp').pagination({
		    total:res.total,
		    showRefresh:true,
		    pageSize:10,
		    pageList:[10,20,30,50,100],
			onSelectPage:function(pageNumber, pageSize){
				$(this).pagination('loading');
				$(this).pagination('loaded');
				showList(pageNumber,pageSize)
			}
		});
	}
	/*if(flag){
		$('#pp').pagination({
		    total:res.total,
		    showRefresh:true,
		    pageSize:10,
		    pageList:[10,20,30,50,100],
			onSelectPage:function(pageNumber, pageSize){
				$(this).pagination('loading');
				$(this).pagination('loaded');
				showList(pageNumber,pageSize)
			}
		});
		flag=false;
	}*/
}
function transStr2Int(str){
	if(str){
		return parseInt(str);
	}else{
		return 0;
	}
}
//导出
function doExport(type){
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountarearecordAction!count_listareaRecordCount.do',
		data : getQueryParams(),
		success : function(res){
			if(res){
				countExport(res,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 downParam = JSON.stringify(getQueryParams());
	if(type=="pdf"){
		document.excelForm.action = 'ywcountarearecordAction!expPDF_Ywcountarearecord.do?downParam='+encodeURIComponent(downParam);
	}else{
		document.excelForm.action = 'ywcountarearecordAction!exp_Ywcountarearecord.do?downParam='+encodeURIComponent(downParam);
	}
	document.excelForm.submit(); 
}
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; 
}

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 : 'ywcountarearecordAction!listareaRecordCount.do',
			data : params,
			async : false,
			success : function(res){
//				console.log("打印：",res);
				if(res == null){
					$.showMsg("暂无数据！");
					return;
				}else{
					if(res.total>0){
						data = res;
					}else{
//						console.log("返回");
						$.showMsg('暂无记录!');
						return;
					}
				}
				
			}
		})
		
		
		var res = data;
		total = res.total;
		var table = '';
		if(res && res.total>0){
			var rows = res.rows;
			table='<table  cellspacing="0"  width="100%"  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 id="timeTJ" colspan="7" style="text-align:right;border:none;padding: 15px;">制表时间：2018-12-28 14:11:49</td>'+
			'</tr>'+
				'<tr>'+
					'<th >序号</th>'+
					'<th >行政区划</th>'+
					'<th >点位总数</th>'+
					'<th >未配置数</th>'+
					'<th >录像正常数</th>'+
					'<th >录像异常数</th>'+
					'<th >录像完好率</th>'+
				'</tr>'+
			'</thead>';
			
			for (var i=0 ; i<rows.length-1; i++) {
				table += '<tr>\
					<td>'+(i+1)+'</td>\
					<td>'+rows[i].areaname+'</td>\
					<td>'+rows[i].totalnum+'</td>\
					<td>'+rows[i].notconfignum+'</td>\
					<td>'+rows[i].recordnormalcount+'</td>\
					<td>'+rows[i].recordabnormalcount+'</td>\
					<td>'+rows[i].recordintactrate+'</td>\
					<tr>'
			}
			//总计
			var totalObj = rows[rows.length-1];
			table += '<tr>\
			<td colspan="2">总计</td>\
			<td>'+totalObj.totalSum+'</td>\
			<td>'+totalObj.notconfigSum+'</td>\
			<td>'+totalObj.recordnormalSum+'</td>\
			<td>'+totalObj.recordabnormalSum+'</td>\
			<td>'+totalObj.recordintactrate+'</td>\
			<tr>'
		}else{
			return;
		}
        table +='</tbody></table>' 
		
 		var headstr = "<html><head><title></title></head><body>";
 		var footstr = "</body></html>";
  
 		var wind = window.open("", "newwin","toolbar=no,scrollbars=yes,menubar=no");
		wind.document.body.innerHTML = headstr + table + footstr;
		wind.print();
 
		wind.close();
		
	 
	}
}