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

//加载列表
function initGrid(){	
	showList();
}

		
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 getQueryParams(){
	var sParam = {};
	sParam.page = 1;
	sParam.rows = 20;
	if (treeSelectId != '-1') {
		sParam.videocatalog = treeSelectId;
	}
	var startTime = $('#datetimeStart').datetimebox("getValue");	
	var endTime = $('#datetimeEnd').datetimebox("getValue");
	var tableparam = "";
	if(!(startTime==null||startTime==""||startTime==undefined)){
		tableparam += " AND currentstatetime >= '" +startTime + "'";
	}
	if(!(endTime==null||endTime==""||endTime==undefined)){
		tableparam += " AND currentstatetime <= '" +endTime + "'";
	}
	sParam.tableparam = tableparam;
	sParam.order = "order by videocatalog asc ";
	return sParam;
}
//列表展示
function showList(page,rows){
	$("#searchGridListDiv").show();
	$("#searchGridPicDiv").hide();
	displayType = "list";
//	$('#searchGridList').datagrid({ toolbar : toolbar})
	var params = getQueryParams();		
	if(page == undefined || page==null){       // 页码
		if($('#pp .l-btn-selected .l-btn-text').text().trim()){
			page = parseInt($('#pp .l-btn-selected .l-btn-text').text().trim());
		}else{
			page = 1;
		}
	} 
	if(rows == undefined || rows==null){       //每页10条
		if($('#pp .pagination-page-list').val()){
			rows = parseInt($('#pp .pagination-page-list').val());
		}else{
			rows = 20;
		}
	} 
	params.page = page;			
	params.rows = rows;	
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywvideocurrentstateAction!vdqStatisticsRegionList.do',
		data : params,
		success : function(res){
			renderTable(res);
		}
	});
}


function showGraph(){
	$("#searchGridPicDiv").show();
	$("#searchGridListDiv").hide();
	var params = getQueryParams();	
	params.page = 1;
	params.rows = 10000;
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywvideocurrentstateAction!vdqStatisticsRegionList.do',
		data : params,
		success : function(res){
			if(res && res.total>0){
				$("#noData").css("display","none");
				$("#searchGridGraph").css("display","block");
				var x = [];
				var zxnum = [];
				var lxnum = [];
				var videonormalnum = [];
				var videoabnormalnum = [];
				var rows = res.rows
				for(var i=0;i<rows.length-1;i++){
					x.push(rows[i].videocatalogname);
					zxnum.push(transStr2Int(rows[i].zxnum));
					lxnum.push(transStr2Int(rows[i].lxnum));
					videonormalnum.push(transStr2Int(rows[i].videonormalnum));
					videoabnormalnum.push(transStr2Int(rows[i].videoabnormalnum));
				}
				var data={
						"title":"视频质量诊断统计",
						xAxis: x,//["监控","NVR","服务器","应用系统"],
						"legend":[
						          {"name":"在线数", "data":zxnum,"color":"yellow"},
						          {"name":"离线数","data":lxnum,"color":"blue"},
						          {"name":"视频正常数","data":videonormalnum,"color":"gray"},
						          {"name":"视频异常数","data":videoabnormalnum,"color":"green"},
						          ]};
				EchartsBase.barChart({
					id:"searchGridGraph",
					data:data
				});
			}else{
				$("#noData").css("display","block");
				$("#searchGridGraph").css("display","none");
			}
		}
	});
	
}
function showVideo(title,state,type,name,xzqh){
	var url = top.sysUrl+"/yw/operationcount/vqdcount/showVideo.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/vqdcount/showCompute.jsp";
	windowid = top.$.createWin({
		title	: 	'计算公式',
		width  :  '400',
		height :  '200',
		data:id,
		url	:  url
	});
}

function renderTable(res){
	var table = '';
	if(res && res.total>0){
		var rows = res.rows;
		$("#timeTJ").text("制表时间："+getCurrtentTime())
		for (var i=0 ; i<rows.length-1; i++) {
			table += '<tr>\
				<td>'+(i+1)+'</td>\
				<td>'+(rows[i].videocatalogname==null?"-":rows[i].videocatalogname)+'</td>\
				<td>'+rows[i].totalnum+'</td>\
				<td>'+rows[i].noinspectionnum+'</td>\
				<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showVideo(\'监控点在线详细列表\',\'1\',\'isonline\',\''+transEmpty(rows[i].videocatalogname)+'\',\''+transEmpty(rows[i].videocatalog)+'\')">'+rows[i].zxnum+'</a></td>\
				<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showVideo(\'监控点不在线详细列表\',\'0\',\'isonline\',\''+transEmpty(rows[i].videocatalogname)+'\',\''+transEmpty(rows[i].videocatalog)+'\')">'+rows[i].lxnum+'</a></td>\
				<td>'+rows[i].zxrate+'</td>\
				<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showVideo(\'监控点视频正常设备详细列表\',\'1\',\'video\',\''+transEmpty(rows[i].videocatalogname)+'\',\''+transEmpty(rows[i].videocatalog)+'\')">'+rows[i].videonormalnum+'</a></td>\
				<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showVideo(\'监控点视频异常设备详细列表\',\'0\',\'video\',\''+transEmpty(rows[i].videocatalogname)+'\',\''+transEmpty(rows[i].videocatalog)+'\')">'+rows[i].videoabnormalnum+'</a></td>\
				<td>'+rows[i].videorate+'</td>\
				<td>'+rows[i].nosignalstatusnum+'</td>\
				<td>'+rows[i].videoocclusionstatusnum+'</td>\
				<td>'+rows[i].scenechangestatusnum+'</td>\
				<td>'+rows[i].imgtoodarkstatusnum+'</td>\
				<td>'+rows[i].imgoverbrightstatusnum+'</td>\
				<td>'+rows[i].imgclearstatusnum+'</td>\
				<td>'+rows[i].imgcolorstatusnum+'</td>\
				<tr>'
		}
		//总计
		var totalObj = rows[rows.length-1];
		table += '<tr>\
		<td colspan="2">总计</td>\
		<td>'+totalObj.monitorSum+'</td>\
		<td>'+totalObj.noinspectionSum+'</td>\
		<td>'+totalObj.zxSum+'</td>\
		<td>'+totalObj.lxSum+'</td>\
		<td>'+totalObj.zxrate+'</td>\
		<td>'+totalObj.videonormalSum+'</td>\
		<td>'+totalObj.videoabnormalSum+'</td>\
		<td>'+totalObj.videorate+'</td>\
		<td>'+totalObj.nosignalstatusSum+'</td>\
		<td>'+totalObj.videoocclusionstatusSum+'</td>\
		<td>'+totalObj.scenechangestatusSum+'</td>\
		<td>'+totalObj.imgtoodarkstatusSum+'</td>\
		<td>'+totalObj.imgoverbrightstatusSum+'</td>\
		<td>'+totalObj.imgclearstatusSum+'</td>\
		<td>'+totalObj.imgcolorstatusSum+'</td>\
		<tr>'
	}else{
		table += '<tr> <td colspan="17">暂无数据</td> <tr>';
	}
	 

	$("#searchGridList").html(table);
	var total = 0;
	if(res && res.total>0){
		total = res.total;
	}
	$('#pp').pagination({
	    total:total,
	    showRefresh:true,
	    pageSize:pageSizeInit,
	    pageList:[10,20,30,50,100],
		onSelectPage:function(pageNumber, pageSize){
			$(this).pagination('loading');
			$(this).pagination('loaded');
			showList(pageNumber,pageSize)
			pageSizeInit = pageSize;
		}
	});
}
function transStr2Int(str){
	if(str){
		return parseInt(str);
	}else{
		return 0;
	}
}
//导出
function doExport(type){
	var model = getQueryParams();
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywvideocurrentstateAction!count_vdqStatisticsRegionList.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());
// var downParam = "";
	console.log(document)
	console.log(document.excelForm)
	if(type=="excel"){
		document.excelForm.action = 'ywvideocurrentstateAction!exp_Ywvideocurrentstatecount.do?downParam='+encodeURIComponent(downParam);
	}else if(type=="pdf"){
		document.excelForm.action = 'ywvideocurrentstateAction!expPDF_Ywvideocurrentstatecount.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 transEmpty(str){
	if (!str || str == null || str == "null") {
		return "" ;
	}else{
		return str ;
	}
	
}

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!vdqStatisticsRegionList.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;
		var table = '';
		
		
		if(res && res.total>0){
			var rows = res.rows;
			$("#timeTJ").text("制表时间："+getCurrtentTime())
			var 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="17" style="font-size:14px;font-weight:bold;border:none">视频质量诊断统计</td>'+									
				'</tr>'+
				'<tr style="border-top: 1px solid #827d7d;">'+										
					'<td id="timeTJ" colspan="17" 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>'+
						'<th >视频正常数</th>'+
						'<th >视频异常数</th>'+
						'<th >视频完好率</th>'+
						'<th >视频丢失</th>'+
						'<th >视频遮挡</th>'+
						'<th>场景变更</th>'+
						'<th>亮度过低</th>'+
						'<th>亮度过高</th>'+
						'<th>图像模糊</th>'+
						'<th>图像偏色</th>'+
					'</tr>'+
   			'</thead><tbody>'
			for (var i=0 ; i<rows.length-1; i++) {
				table += '<tr>\
					<td>'+(i+1)+'</td>\
					<td>'+(rows[i].videocatalogname==null?"-":rows[i].videocatalogname)+'</td>\
					<td>'+rows[i].totalnum+'</td>\
					<td>'+rows[i].noinspectionnum+'</td>\
					<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showVideo(\'监控点在线详细列表\',\'1\',\'isonline\',\''+transEmpty(rows[i].videocatalogname)+'\',\''+transEmpty(rows[i].videocatalog)+'\')">'+rows[i].zxnum+'</a></td>\
					<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showVideo(\'监控点不在线详细列表\',\'0\',\'isonline\',\''+transEmpty(rows[i].videocatalogname)+'\',\''+transEmpty(rows[i].videocatalog)+'\')">'+rows[i].lxnum+'</a></td>\
					<td>'+rows[i].zxrate+'</td>\
					<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showVideo(\'监控点视频正常设备详细列表\',\'1\',\'video\',\''+transEmpty(rows[i].videocatalogname)+'\',\''+transEmpty(rows[i].videocatalog)+'\')">'+rows[i].videonormalnum+'</a></td>\
					<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showVideo(\'监控点视频异常设备详细列表\',\'0\',\'video\',\''+transEmpty(rows[i].videocatalogname)+'\',\''+transEmpty(rows[i].videocatalog)+'\')">'+rows[i].videoabnormalnum+'</a></td>\
					<td>'+rows[i].videorate+'</td>\
					<td>'+rows[i].nosignalstatusnum+'</td>\
					<td>'+rows[i].videoocclusionstatusnum+'</td>\
					<td>'+rows[i].scenechangestatusnum+'</td>\
					<td>'+rows[i].imgtoodarkstatusnum+'</td>\
					<td>'+rows[i].imgoverbrightstatusnum+'</td>\
					<td>'+rows[i].imgclearstatusnum+'</td>\
					<td>'+rows[i].imgcolorstatusnum+'</td>\
					<tr>'
			}
			//总计
			var totalObj = rows[rows.length-1];
			table += '<tr>\
			<td colspan="2">总计</td>\
			<td>'+totalObj.monitorSum+'</td>\
			<td>'+totalObj.noinspectionSum+'</td>\
			<td>'+totalObj.zxSum+'</td>\
			<td>'+totalObj.lxSum+'</td>\
			<td>'+totalObj.zxrate+'</td>\
			<td>'+totalObj.videonormalSum+'</td>\
			<td>'+totalObj.videoabnormalSum+'</td>\
			<td>'+totalObj.videorate+'</td>\
			<td>'+totalObj.nosignalstatusSum+'</td>\
			<td>'+totalObj.videoocclusionstatusSum+'</td>\
			<td>'+totalObj.scenechangestatusSum+'</td>\
			<td>'+totalObj.imgtoodarkstatusSum+'</td>\
			<td>'+totalObj.imgoverbrightstatusSum+'</td>\
			<td>'+totalObj.imgclearstatusSum+'</td>\
			<td>'+totalObj.imgcolorstatusSum+'</td>\
			<tr>'
		}else{
			table += '<tr> <td colspan="17">暂无数据</td> <tr>';
			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();
 //		window.location.reload()
		
	 
	}
}