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").datebox("setValue",$.getTodayStart(0,""));
	$("#datetimeEnd").datebox("setValue",$.getTodayEnd(""));
	initGrid();
//	initCountTime();
	initTree();
});

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

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 initCountTime(){
		var flag=false;
		var date=new Date();
		var year=date.getFullYear();
		var month=date.getMonth()+1;
		var str=year+"年"+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){
			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 getQueryParams(){
	var sParam = {};
	
//	sParam.page = 1;
//	sParam.rows = 1000;
	sParam.order = "order by areanum desc,devicenum ,channelnum ";
	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";
//	$('#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 = 10;
		}
	} 
	params.page = page;			
	params.rows = rows;	
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountvideoappraiseAction!listYwcountvideoappraiseByPage.do',
		data : params,
		success : function(res){
			renderTable(res,page,rows);
		}
	});
}



function renderTable(res,page,limit){
	var table = '';
	if(res && res.total>0){
		var rows = res.rows;
		$("#timeTJ").text("制表时间："+getCurrtentTime())
		var monitorSum = 0,invalidlalSum = 0,laldefectSum = 0,lalcompleteSum=0,nolalSum=0;
		for (var i=0 ; i<rows.length; i++) {
//			monitorSum += parseInt(rows[i].monitortotal);
//			nolalSum += parseInt(rows[i].nolalcount);
//			invalidlalSum += parseInt(rows[i].invalidlalcount);
//			laldefectSum += parseInt(rows[i].laldefectcount);
//			lalcompleteSum += parseInt(rows[i].lalcompletecount);
				
			table += '<tr>\
				<td>'+((page-1)*limit+(i+1))+'</td>\
				<td>'+transformateEmpty(rows[i].videoname)+'</td>\
				<td>'+transformateEmpty(rows[i].areaname)+'</td>\
				<td>'+transformateEmpty(rows[i].ipaddress)+'</td>\
				<td>'+rows[i].lxsc+'</td>\
				<td>'+transformateEmpty(rows[i].lxstarttime)+'</td>\
				<tr>'
		}
		/*table += '<tr>\
		<td colspan="2">总计</td>\
		<td>'+monitorSum+'</td>\
		<td>'+nolalSum+'</td>\
		<td>'+laldefectSum+'</td>\
		<td>'+invalidlalSum+'</td>\
		<td>'+lalcompleteSum+'</td>\
		<td>'+(lalcompleteSum*100.0/monitorSum).toFixed(2)+'%</td>\
		<tr>'*/
	}else{
		table += '<tr> <td colspan="8">暂无数据</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();
//	execExport();
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountvideoappraiseAction!count_Ywcountvideoappraise.do',
		data : model,
		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 downParams = JSON.stringify(getQueryParams());
	if(type=="pdf"){
		document.excelForm.action = 'ywcountvideoappraiseAction!expPDF_Ywcountvideoappraise_online.do?downParam=' + encodeURIComponent(downParams);
	}else{
		document.excelForm.action = 'ywcountvideoappraiseAction!exp_Ywcountvideoappraise_online.do?downParam=' + encodeURIComponent(downParams);
	}
	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 transformateEmpty(str){
	if(!str || str==null || str=="null"){
		return "-";
	}
	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 : 'ywcountvideoappraiseAction!listYwcountvideoappraiseByPage.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){
			
			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="6" style="font-size:14px;font-weight:bold;border:none">离线时长统计</td>'+									
			'</tr>'+
			'<tr style="border-top: 1px solid #827d7d;">'+							
				'<td id="timeTJ" colspan="6" style="text-align:right;border:none;padding: 15px;">制表时间：2018-12-28 14:11:49</td>'+
			'</tr>'+
				'<tr>'+
					'<th >序号</th>'+
					'<th >监控点名称</th>'+
					'<th >行政区划</th>'+
					'<th >IP地址</th>'+
					'<th >离线时间（小时）</th>'+
					'<th >离线开始时间</th>'+
				'</tr>'+
			'</thead>';
			
			var rows = res.rows;
			$("#timeTJ").text("制表时间："+getCurrtentTime())
			var monitorSum = 0,invalidlalSum = 0,laldefectSum = 0,lalcompleteSum=0,nolalSum=0;
			for (var i=0 ; i<rows.length; i++) {
 					
				table += '<tr>\
					<td>'+(i+1)+'</td>\
					<td>'+transformateEmpty(rows[i].videoname)+'</td>\
					<td>'+transformateEmpty(rows[i].areaname)+'</td>\
					<td>'+transformateEmpty(rows[i].ipaddress)+'</td>\
					<td>'+rows[i].lxsc+'</td>\
					<td>'+transformateEmpty(rows[i].lxstarttime)+'</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();

	}
}