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 total = 0;
var treeSelectId = "-1";
$(function(){
	$('#lb').combobox({
		url: 'xtclAction!query_Xtcl.do?csdl=nhywjtsblx',
		textField: "csmc",
		valueField: "csdm",
		panelWidth: 148,
		loadFilter: function (data) {
			return data;
		},
		onChange: function (n, o) {
			if (n == "1") {
				$("#treediv").show();
				initTree();
			} else {
				$("#treediv").hide();
			}

		},
		onLoadSuccess:function(){ //默认选中第一条数据
			var data= $(this).combobox("getData");
			if(data.length>0){
				$('#lb').combobox('select',data[0].csdm);
			}
		}
	});
	initTree();
	initTime();
	initHeader();
	initGrid();
});
function initHeader(){
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountvideoappraiseAction!getWeight.do',
		data : "",
		success : function(res){
			if(res){
				$("#zxl").text("("+res.onlineweight+")");
				$("#spwhl").text("("+res.videoweight+")");
				$("#lxwhl").text("("+res.recordweight+")");
				$("#jwdcjl").text("("+res.lalweight+")");
				$("#xfl").text("("+res.repairweight+")");
			}
		}
	});
}
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 = 1000;
	sParam.order = "order by areanum desc ";
	var datetimeStart = $('#datetimeStart').datebox("getValue");	
	var datetimeEnd = $('#datetimeEnd').datebox("getValue");	
	var tableparam = "";
	var jobtableparam = "";
	sParam.areanum = treeSelectId;
	if(!(datetimeStart==null||datetimeStart==""||datetimeStart==undefined)){
		tableparam += " AND countDate >= '" +datetimeStart + "'";
		jobtableparam += " AND jobreporttime >= '" +datetimeStart + "'";
	}
	if(!(datetimeEnd==null||datetimeEnd==""||datetimeEnd==undefined)){
		tableparam += " AND countDate <= '" +datetimeEnd + "'";
		jobtableparam += " AND jobreporttime <= '" +datetimeEnd + "'";
	}
	sParam.tableparam = tableparam;

	sParam.jobtableparam = jobtableparam;
	return sParam;
}
//列表展示
function showList(page,rows){
	$("#searchGridListDiv").show();
	$("#searchGridPicDiv").hide();
	displayType = "list";
//	rows = 1000;
//	$('#searchGridList').datagrid({ toolbar : toolbar})
	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 : 'ywcountvideoappraiseAction!regionAssessmentCountList.do',
		data : params,
		success : function(res){
			renderTable(res);
		}
	});
}


function showGraph(){
	$("#searchGridPicDiv").show();
	$("#searchGridListDiv").hide();
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountvideoappraiseAction!regionAssessmentCountList.do',
		data : getQueryParams(),
		success : function(res){
			total = res.total;
			if(res && res.total>0){
				$("#noData").css("display","none");
				$("#searchGridGraph").css("display","block");
				var x = [];
				var score = [];
				
				var rows = res.rows
				for(var i=0;i<rows.length-1;i++){
					x.push((rows[i].areaname==null?"":rows[i].areaname));
					score.push(rows[i].score);
				}
				var data={
						"title":"区域运维考核统计",
						xAxis: x,//["监控","NVR","服务器","应用系统"],
						"legend":[
						          {"name":"得分", "data":score,"color":"green"},
						          /*{"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 showRegion(name,xzqh){
	var url = top.sysUrl+"/yw/operationcount/regionassessmentcount/showRegion.jsp";
	var data = {};
	data.areanum = xzqh;
	data.areaname = name;
	data.alarmdevicetype = $('#lb').combobox("getValue")==""?"1": $('#lb').combobox("getValue");
	data.order = "order by devicenum desc ";
	var datetimeStart = $('#datetimeStart').datebox("getValue");	
	var datetimeEnd = $('#datetimeEnd').datebox("getValue");	
	var tableparam = "";
	var jobtableparam = "";
	if(!(datetimeStart==null||datetimeStart==""||datetimeStart==undefined)){
		tableparam += " AND countDate >= '" +datetimeStart + "'";
		jobtableparam += " AND jobreporttime >= '" +datetimeStart + "'";
	}
	if(!(datetimeEnd==null||datetimeEnd==""||datetimeEnd==undefined)){
		tableparam += " AND countDate <= '" +datetimeEnd + "'";
		jobtableparam += " AND jobreporttime <= '" +datetimeEnd + "'";
	}
	data.tableparam = tableparam;
	data.jobtableparam = jobtableparam;
	windowid = top.$.createWin({
		 title	: 	name+"-区域运维考核统计",
		 width  :  '1120',
		 height :  '600',
		 data 	:  data,
		 url	:  url
	 });
}

function showCompute(id){
	var url = top.sysUrl+"/yw/operationcount/regionassessmentcount/showFormula.jsp";
	windowid = top.$.createWin({
		title	: 	'计算公式',
		width  :  '400',
		height :  '200',
		data:id,
		url	:  url
	});
}
function setWeight(id){
	var url = top.sysUrl+"/yw/operationcount/regionassessmentcount/showWeight.jsp";
	windowid = top.$.createWin({
		title	: 	'权重设置',
		width  :  '600',
		height :  '300',
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:saveWeight
		}],
		data:id,
		url	:  url
	});
}
function saveWeight(){
	var win		=	$.getTopWindowById(windowid);
	var jq		=	win.$;
	/*var model   =   $.getFormValues("childform",windowid);
	console.log(model);
	if(!win.$('#childform').form('enableValidation').form('validate')){
      return;
	}*/
	var model = {};
	model.XGTJweightId = jq('#weightId').val();
	model.onlineweight = jq('#onlineweight').val();
	model.videoweight = jq('#videoweight').val();
	model.recordweight = jq('#recordweight').val();
	model.lalweight = jq('#lalweight').val();
	model.repairweight = jq('#repairweight').val();
	model.remarks = jq('#remarks').val();
	$.ajax({
		type:'post',
		dataType : 'json',
		url:'ywcountvideoappraiseAction!setWeight.do',
		data:model,
		success:function(res){
			if(res){
				$.showMsg("操作成功！");
				top.$("#"+windowid).dialog('close');
				initHeader();
				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 renderTable(res){
	console.log(res);
	total = res.total;
	var table = '';
	if(res && res.total>0){
		var rows = res.rows;
		$("#timeTJ").text("制表时间："+getCurrtentTime());
		var monitorSum = 0,zxscSum = 0.0,lxscSum=0,totalSum=0,vqdnormalSum=0,lalnormalSum=0,
		recorddurationnormalSum=0,norecorddurationnormalSum=0,jobtotalSum=0,jobnormalSum=0,
		scoreSum =0;
		for (var i=0 ; i<rows.length-1; i++) {
			totalSum += parseInt(rows[i].total);
			monitorSum += parseInt(rows[i].jksum);
			zxscSum += parseFloat(rows[i].zxsc);
			lxscSum += parseFloat(rows[i].lxsc);
			vqdnormalSum += parseInt(rows[i].vqdnormalnum);
			lalnormalSum += parseInt(rows[i].lalnormalnum);
			recorddurationnormalSum += parseInt(rows[i].recorddurationnormalnum);
			norecorddurationnormalSum += parseInt(rows[i].norecorddurationnormalnum);
			jobtotalSum += parseInt(rows[i].jobtotal);
			jobnormalSum += parseInt(rows[i].jobnormalnum);
			scoreSum += parseFloat(rows[i].score);
			table += '<tr>'
				+'<td>'+(i+1)+'</td>'
				+'<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" onclick="showRegion(\''+(rows[i].areaname==null?"":rows[i].areaname)+'\',\''+rows[i].areanum+'\')" >'+(rows[i].areaname==null?"-":rows[i].areaname)+'</a></td>'
						+'<td>'+rows[i].jksum+'</td>'
						+'<td>'+rows[i].zxsc+'</td>'
						+'<td>'+rows[i].zxRate+'</td>'
						+'<td>'+rows[i].videoIntactRate+'</td>'
						+'<td>'+rows[i].recordIntactRate+'</td>'
						+'<td>'+rows[i].lalIntactRate+'</td>'
						+'<td>'+rows[i].jobIntactRate+'</td>'
						+'<td>'+rows[i].score+'</td>'
						+'<td>'+(i+1)+'</td>'
						+'<tr>';
		}
		table += '<tr>'
		+'<td colspan="2">总计</td>'
		+'<td>'+monitorSum+'</td>'
		+'<td>'+zxscSum+'</td>'
		if((zxscSum+lxscSum)/1==0){
			table += '<td>0.00%</td>';
		}else{
			table += '<td>'+((zxscSum*100.0/(zxscSum+lxscSum)).toFixed(2))+'%</td>';
		}
		if(totalSum==0){
			table += '<td>0.00%</td>';
		}else{
			table += '<td>'+((vqdnormalSum*100.0/totalSum).toFixed(2))+'%</td>';
		}
		if((recorddurationnormalSum+norecorddurationnormalSum)==0){
			table += '<td>0.00%</td>';
		}else{
			table += '<td>'+((recorddurationnormalSum*100.0/(recorddurationnormalSum+norecorddurationnormalSum)).toFixed(2))+'%</td>';
		}
		if(totalSum==0){
			table += '<td>0.00%</td>';
		}else{
			table += '<td>'+((lalnormalSum*100.0/totalSum).toFixed(2))+'%</td>';
		}
		if(jobtotalSum==0){
			table += '<td>0.00%</td>';
		}else{
			table += '<td>'+((jobnormalSum*100.0/jobtotalSum).toFixed(2))+'%</td>';
		}
		table += '<td>'+scoreSum.toFixed(2)+'</td>'
		+'<td></td> <tr>'
	}else{
		table += '<tr> <td colspan="11">暂无数据</td> <tr>';
	}
	 

	$("#searchGridList").html(table);
	/*
	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){
//	execExport();
	var model = getQueryParams();
	/*
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'ywcountlalcollectAction!count_Ywcountlalcollect.do',
		data : getQueryParams(),
		success : function(res){
			if(res){
				countExport(res);
			}else{
				$.showMsg("没有查到符合条件的记录！");
			}
		}
	});*/
	if (total <= 0) {
		$.showMsg("暂无数据");
	} else {
		countExport(total,type);
	}
}
// 导出传参条件
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=="pdf"){
		document.excelForm.action = 'ywcountvideoappraiseAction!expPDF_Ywcountvideoappraise.do?downParam='+encodeURIComponent(downParam);
	}else{
		document.excelForm.action = 'ywcountvideoappraiseAction!exp_Ywcountvideoappraise.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 : 'ywcountvideoappraiseAction!regionAssessmentCountList.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;
			$("#timeTJ").text("制表时间："+getCurrtentTime());
			
			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="11" style="font-size:14px;font-weight:bold;border:none">区域运维考核统计</td>'+									
			'</tr>'+
			'<tr style="border-top: 1px solid #827d7d;">'+										
				'<td id="timeTJ" colspan="11" 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 >在线率<span id="zxl"></span></th>'+
					'<th >视频完好率<span id="spwhl"></span></th>'+
					'<th >录像完好率<span id="lxwhl"></span></th>'+
					'<th >经纬度采集率<span id="jwdcjl"></span></th>'+
					'<th >修复率<span id="xfl"></span></th>'+
					'<th >总分</th>'+
					'<th >排名</th>'+
				'</tr>'+
			'</thead>';
			
			var monitorSum = 0,zxscSum = 0.0,lxscSum=0,totalSum=0,vqdnormalSum=0,lalnormalSum=0,
			recorddurationnormalSum=0,norecorddurationnormalSum=0,jobtotalSum=0,jobnormalSum=0,
			scoreSum =0;
			for (var i=0 ; i<rows.length-1; i++) {
				totalSum += parseInt(rows[i].total);
				monitorSum += parseInt(rows[i].jksum);
				zxscSum += parseFloat(rows[i].zxsc);
				lxscSum += parseFloat(rows[i].lxsc);
				vqdnormalSum += parseInt(rows[i].vqdnormalnum);
				lalnormalSum += parseInt(rows[i].lalnormalnum);
				recorddurationnormalSum += parseInt(rows[i].recorddurationnormalnum);
				norecorddurationnormalSum += parseInt(rows[i].norecorddurationnormalnum);
				jobtotalSum += parseInt(rows[i].jobtotal);
				jobnormalSum += parseInt(rows[i].jobnormalnum);
				scoreSum += parseFloat(rows[i].score);
				table += '<tr>'
					+'<td>'+(i+1)+'</td>'
					+'<td><a style="color: -webkit-link; cursor: pointer; text-decoration: underline;" onclick="showRegion(\''+(rows[i].areaname==null?"":rows[i].areaname)+'\',\''+rows[i].areanum+'\')" >'+(rows[i].areaname==null?"-":rows[i].areaname)+'</a></td>'
							+'<td>'+rows[i].jksum+'</td>'
							+'<td>'+rows[i].zxsc+'</td>'
							+'<td>'+rows[i].zxRate+'</td>'
							+'<td>'+rows[i].videoIntactRate+'</td>'
							+'<td>'+rows[i].recordIntactRate+'</td>'
							+'<td>'+rows[i].lalIntactRate+'</td>'
							+'<td>'+rows[i].jobIntactRate+'</td>'
							+'<td>'+rows[i].score+'</td>'
							+'<td>'+(i+1)+'</td>'
							+'<tr>';
			}
			table += '<tr>'
			+'<td colspan="2">总计</td>'
			+'<td>'+monitorSum+'</td>'
			+'<td>'+zxscSum+'</td>'
			if((zxscSum+lxscSum)/1==0){
				table += '<td>0%</td>';
			}else{
				table += '<td>'+((zxscSum*100.0/(zxscSum+lxscSum)).toFixed(2))+'%</td>';
			}
			if(totalSum==0){
				table += '<td>0%</td>';
			}else{
				table += '<td>'+((vqdnormalSum*100.0/totalSum).toFixed(2))+'%</td>';
			}
			if((recorddurationnormalSum+norecorddurationnormalSum)==0){
				table += '<td>0%</td>';
			}else{
				table += '<td>'+((recorddurationnormalSum*100.0/(recorddurationnormalSum+norecorddurationnormalSum)).toFixed(2))+'%</td>';
			}
			if(totalSum==0){
				table += '<td>0%</td>';
			}else{
				table += '<td>'+((lalnormalSum*100.0/totalSum).toFixed(2))+'%</td>';
			}
			if(jobtotalSum==0){
				table += '<td>0%</td>';
			}else{
				table += '<td>'+((jobnormalSum*100.0/jobtotalSum).toFixed(2))+'%</td>';
			}
			table += '<td>'+scoreSum.toFixed(2)+'</td>'
			+'<td></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();
		
	 
	}
}