var windowId,proName = window.location.pathname.split("/")[1],sysUrl = "http://"+window.location.host+"/"+proName,toEdit;
var records = [];
var date = new Date();

var flag=true;
var pageSizeInit = 10;
var treeSelectId = "-1";
$(function(){
	initCountTime();
	$('#datetime').datebox({
	    onShowPanel: function () {//显示日趋选择对象后再触发弹出月份层的事件，初始化时没有生成月份层
	        span.trigger('click'); //触发click事件弹出月份层
	        if (!tds)
	            setTimeout(function() { //延时触发获取月份对象，因为上面的事件触发和对象生成有时间间隔
	                tds = p.find('div.calendar-menu-month-inner td');
	                tds.click(function(e) {
	                    e.stopPropagation(); //禁止冒泡执行easyui给月份绑定的事件
	                    var year = /\d{4}/.exec(span.html())[0] //得到年份
	                        ,month = parseInt($(this).attr('abbr'), 10); //月份 之前是这样的month = parseInt($(this).attr('abbr'), 10) + 1; 
	                   if(month<10){
	                	   month = "0"+month;
	                   }
	                    $('#datetime').datebox('hidePanel') //隐藏日期对象
	                        .datebox('setValue', year + '-' + month); //设置日期的值
	                });
	            }, 0);
	    },
	    parser: function (s) {//配置parser，返回选择的日期
	        if (!s) return new Date();
	        var arr = s.split('-');
	        return new Date(parseInt(arr[0], 10), parseInt(arr[1], 10) - 1, 1);
	    },
	    formatter: function (d) { return d.getFullYear() + '-' +((d.getMonth()+1)<10?'0'+(d.getMonth()+1):(d.getMonth()+1)); }//配置formatter，只返回年月 之前是这样的d.getFullYear() + '-' +(d.getMonth()); 
	});

	var p = $('#datetime').datebox('panel'), //日期选择对象
	tds = false, //日期选择对象中月份
	span = p.find('span.calendar-text'); //显示月份层的触发控件
	var curr_time = new Date();
	$("#datetime").datebox("setValue", myformatter(curr_time));//设置前当月
	$("#timeTJ").text("制表时间："+getCurrtentTime())
	initGrid();
	initTree();
	//initXzNameTree();
});
//格式化日期
function myformatter(date) {
		var y = date.getFullYear();
		var m = date.getMonth() + 1;
		//var d = 1;
		return y + '-' + (m < 10 ? ('0' + m) : m);//+ '-' + (d < 10 ? ('0' + d) : d);
}
//加载列表
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 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 getQueryParams(){
	var sParam = {};
	
	sParam.page = 1;
	sParam.rows = 1000;
	sParam.order = "order by areanum desc ";
	var month = $("#countTime").combobox("getText");
	if (treeSelectId != '-1') {
		sParam.areanum = treeSelectId;
	}
	if("自定义时间"==month){
		sParam.countMonth = $("#datetime").datebox("getValue");	
	}else{
		sParam.countMonth = month.replace("年","-").replace("月","");
	}
	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 : 'ywcountlalcollectAction!listYwcountlalcollectByPage.do',
		data : params,
		success : function(res){
			renderTable(res);
		}
	});
}


function showGraph(){
	$("#searchGridPicDiv").show();
	$("#searchGridListDiv").hide();
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountlalcollectAction!listYwcountlalcollectByPage.do',
		data : getQueryParams(),
		success : function(res){
			if(res && res.total>0){
				$("#noData").css("display","none");
				$("#searchGridGraph").css("display","block");
				var x = [];
				var noJWnum = [];
				var invalidJWnum = [];
				var defectJWnum = [];
				var completeJWnum = [];
				var rows = res.rows
				for(var i in rows){
					x.push(rows[i].areaname);
					noJWnum.push(transStr2Int(rows[i].nolalcount));
					invalidJWnum.push(transStr2Int(rows[i].invalidlalcount));
					defectJWnum.push(transStr2Int(rows[i].laldefectcount));
					completeJWnum.push(transStr2Int(rows[i].lalcompletecount));
				}
				var data={
						"title":"经纬度采集率统计",
						xAxis: x,//["监控","NVR","服务器","应用系统"],
						"legend":[
						          {"name":"无经纬度数", "data":noJWnum,"color":"yellow"},
						          {"name":"无效经纬度数","data":invalidJWnum,"color":"blue"},
						          {"name":"经纬度缺失数","data":defectJWnum,"color":"gray"},
						          {"name":"经纬度完整数","data":completeJWnum,"color":"green"},
						          ]};
//				$('#searchGridStatics').datagrid({ toolbar : toolbar});
				EchartsBase.barChart({
					id:"searchGridGraph",
					data:data
				});
			}else{
				$("#noData").css("display","block");
				$("#searchGridGraph").css("display","none");
			}
		}
	});
	
}
function showJw(title,type,xzqh){
	var url = top.sysUrl+"/yw/operationcount/latandloncount/showJw.jsp";
	windowid = top.$.createWin({
		 title	: 	title,
		 width  :  '720',
		 height :  '400',
		 data:{type:type,xzqh:xzqh},
		 url	:  url
	 });
}

function showCompute(id){
	var url = top.sysUrl+"/yw/operationcount/latandloncount/showCompute.jsp";
	windowid = top.$.createWin({
		title	: 	'计算公式',
		width  :  '400',
		height :  '200',
		data:id,
		url	:  url
	});
}


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 renderTable(res){
	var table = '';
	if(res && res.total>0){
		var rows = res.rows;
		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);
			if(getDate()==rows[i].countmonth){
				
				table += '<tr>\
					<td>'+(i+1)+'</td>\
					<td>'+rows[i].areaname+'</td>\
					<td>'+rows[i].monitortotal+'</td>\
					<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showJw(\'无经纬度监控点设备列表\',\'1\',\''+rows[i].areanum+'\')">'+rows[i].nolalcount+'</a></td>\
					<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showJw(\'经纬度缺失监控点设备列表\',\'2\',\''+rows[i].areanum+'\')">'+rows[i].laldefectcount+'</a></td>\
					<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" class="ahref" onclick="showJw(\'经纬度无效监控点设备列表\',\'3\',\''+rows[i].areanum+'\')">'+rows[i].invalidlalcount+'</a></td>\
					<td>'+rows[i].lalcompletecount+'</td>\
					<td>'+rows[i].lalcollectionrate+'</td>\
					<tr>'
			}else{
				
				table += '<tr>\
					<td>'+(i+1)+'</td>\
					<td>'+rows[i].areaname+'</td>\
					<td>'+rows[i].monitortotal+'</td>\
					<td>'+rows[i].nolalcount+'</td>\
					<td>'+rows[i].laldefectcount+'</td>\
					<td>'+rows[i].invalidlalcount+'</td>\
					<td>'+rows[i].lalcompletecount+'</td>\
					<td>'+rows[i].lalcollectionrate+'</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;
		}
	});
	/*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 getDate(){
	var month = date.getMonth()+1;
	if(month<10){
		month = "0"+month;
	}
	return date.getFullYear()+"-"+month;
}
function transStr2Int(str){
	if(str){
		return parseInt(str);
	}else{
		return 0;
	}
}
//导出
function doExport(){
	var model = getQueryParams();
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountlalcollectAction!count_Ywcountlalcollect.do',
		data : getQueryParams(),
		success : function(res){
			if(res){
				countExport(res);
			}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 downParam = JSON.stringify(getQueryParams());
// var downParam = "";
//	console.log(document)
//	console.log(document.excelForm)
	document.excelForm.action = 'ywcountlalcollectAction!exp_Ywcountlalcollect.do?downParam='+encodeURIComponent(downParam);
	document.excelForm.submit(); 
}