var windowId,proName = window.location.pathname.split("/")[1],sysUrl = "http://"+window.location.host+"/"+proName,toEdit;
//var result=[12,11,10,9,8,7,6,5,4,3,2,1];
var result=["12月","11月","10月","09月","08月","07月","06月","05月","04月","03月","02月","01月"];
var treeSelectId = "-1";
$(function(){
	initCountTime();
	$("#datetimeStart").datebox("setValue",$.getTodayStart(0,"00:00:00"));
	$("#datetimeEnd").datebox("setValue",$.getTodayEnd("23:59:59"));
	
	initTree();	
	initGrid();	
});

//加载列表
function initGrid(){	
	toolbar = [
	      {
		        text:'统计列表',
		        iconCls:'icon-search',
		        handler:function(){
		        	showList();
		        }
	      },{
		        text:'统计图',
		        iconCls:'icon-search',
		        handler:function(){
		        	showBarChart();
		        }
	      },{
				text:"导出Excel",
				iconCls:"icon-search",
				handler:function(){
					showExport("excel");
				}
		   },{
				text:"导出PDF",
				iconCls:"icon-search",
				handler:function(){
					showExport("pdf");
				}
		   },{
			    text:"计算公式",
				iconCls:"icon-search",
				handler:function(){
					lookJsgs();
				}
		   },{
			    text:"打印",
				iconCls:"icon-search",
				handler:function(){
					dayin();
				}
		   }
	];
	showList();
}

//加载统计时间
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();
			}
		}
	});
}

$.extend($.fn.datagrid.methods,
		{
	renderAlarmOverviewData:function(n, g, h){
		 var m = n.parent(".datagrid-view:eq(0)"),c;
         var k = m.prev("div").append("<table cellspacing=0 cellpadding=0 style='display:inline-block;height:26px;float:right;'><tbody><tr/></tbody></table>").children("table:eq(1)").find("tbody tr");
         var b = m.parent().height();
         var o = m.parent().width();
         if (!m.next("div.imgcontainer").html()) {
             c = $("<div class='imgcontainer' style='overflow-y:auto; width:99%;height:" + (b - 70) + "px;'></div>");
             m.after(c)
         } else {
             c = m.next("div.imgcontainer")
         }
         if (!g) {
             return
         }
         var f = 0,l = [],e,d,
         j = this;
         var nowTime = getNowTime("-");
         var TABLE='<table  cellspacing="0"  width="90%"  cellpadding="0"  border="1"  align="center"  style="text-align:center;margin:0 auto;	border:1px solid #827d7d;font-size:12px;">\
		           				<thead>\
						        	 <tr style="height: 40px;">\
										<td colspan="10" style="font-size:14px;font-weight:bold;border:none">工单情况统计</td>\
									</tr>\
						     		<tr style="border-top: 1px solid #827d7d;">\
										<td colspan="10" style="text-align:right;border:none;padding: 15px;">制表时间：'+nowTime+'</td>\
									</tr>\
									<tr>\
		           						<td>序号</td>\
	    	 							<td>行政区划</td>\
	    	 							<td>工单总数</td>\
	    	 							<td>驳回工单</td>\
	    	 							<td>挂起工单</td>\
	    	 							<td>未完成工单</td>\
	    	 							<td>已完成工单</td>\
	    	 							<td>工单完成率</td>\
	    	 							<td>及时完成数</td>\
	    	 							<td>及时完成率</td>\
		           					</tr>\
			           			</thead>\
        	 	<tbody>'
										
		 var zs = 0;
         var bhzs = 0;
         var gqzs = 0;
         var wwczs = 0;
         var ywczs = 0;
         var jswczs = 0;
         
         var total = g.totalSize;
         if(total!=null && total>0){
        	 for (; (g.data[f]); f++) {
             	
         	 	var gdzs = g.data[f].gdzs;
         	 	var bhgd = g.data[f].bhgd;
         	 	var gqgd = g.data[f].gqgd;
         	 	var wwcgd = g.data[f].wwcgd;        	 	
         	 	var ywcgd = g.data[f].ywcgd;
         	 	var jswcgd = g.data[f].jswcgd;
         	 	
         	 	var wcl = 0;
         	 	if(gdzs != 0){
         	 		wcl = ywcgd/gdzs;
         	 	}
         	 	if(wcl != 0){
         	 		wcl = wcl*100; 
         	 		wcl = wcl.toFixed(2)+"%";
         	 	}
         	 	
         	 	var jswcl = 0;
         	 	if(gdzs != 0){
         	 		jswcl = jswcgd/gdzs;
         	 	}
         	 	if(jswcl != 0){
         	 		jswcl = jswcl*100; 
         	 		jswcl = jswcl.toFixed(2)+"%";
         	 	}
         	 	zs = zs + parseInt(gdzs);
         	 	bhzs = bhzs + parseInt(bhgd);
         	 	gqzs = gqzs + parseInt(gqgd);
         	 	wwczs = wwczs + parseInt(wwcgd);
         	 	ywczs = ywczs + parseInt(ywcgd);
         	 	jswczs = jswczs + parseInt(jswcgd);
         	TABLE+='<tr>\
 		        		<td>'+(f+1)+'</td>\
 				 		<td>'+g.data[f].bmmc+'</td>\
 				 		<td>'+gdzs+'</td>\
 				 		<td>'+bhgd+'</td>\
 				 		<td>'+gqgd+'</td>\
 				 		<td>'+wwcgd+'</td>\
 				 		<td>'+ywcgd+'</td>\
 				 		<td>'+wcl+'</td>\
 				 		<td>'+jswcgd+'</td>\
 				 		<td>'+jswcl+'</td>\
         	 		 <tr>'
          }
          var zwcl = 0;
          var zjswcl = 0;
          if(zs != 0){
         	 zwcl =  ywczs/zs;
         	 zjswcl = jswczs/zs;
          }
          if(zwcl != 0){
         	 zwcl = zwcl*100; 
         	 zwcl = zwcl.toFixed(2)+"%";
  	 	 }
          if(zjswcl != 0){
         	 zjswcl = zjswcl*100; 
         	 zjswcl = zjswcl.toFixed(2)+"%";
          }
          TABLE+="<tr>" +
          			"<td colspan='2'>总计</td>" +
          			"<td>"+zs+"</td>" +
          			"<td>"+bhzs+"</td>" +
          			"<td>"+gqzs+"</td>" +
          			"<td>"+wwczs+"</td>" +
          			"<td>"+ywczs+"</td>" +
          			"<td>"+zwcl+"</td>" +
          			"<td>"+jswczs+"</td>" +
          			"<td>"+zjswcl+"</td>" +
          		"</tr>";
         }else{
        	 TABLE+="<tr><td colspan='10'>暂无数据</td></tr>";
         }
         
         TABLE+= "</tbody></table>";
         c.html('<div class="img-box"  style="margin:0 auto;">'+ TABLE+'</div>')
     }
});

//查询条件
function getQueryParams(){
	var sParam = {};
	var countTime = $('#countTime').combobox("getText");
	var datetimeStart = $('#datetimeStart').datebox("getValue");
	var datetimeEnd = $('#datetimeEnd').datebox("getValue");


	var countMonth = "";
	var countDateStart = "";
	var countDateEnd = "";
	if(treeSelectId == '-1'){				// 本地目录
		treeSelectId = "";
	}
	
	var date=new Date();
	var year=date.getFullYear();
	var month=date.getMonth()+1;
	if("自定义时间"==countTime){
//		sParam.countMonth = $("#datetime").datebox("getValue");	
		countDateStart = datetimeStart;
		countDateEnd = datetimeEnd;
	}else{
		countMonth = countTime.replace("年","-").replace("月","");
		year = countMonth.substring(0,4);
		month = countMonth.substring(5,7);
//		console.log("截取：",year,month);
		if(month !=10 && month.indexOf("0")!=-1){					// 包含0
			month = month.substring(1);
		}	
		if(parseInt(month) < 10){
			countDateStart = year + "-0" + month+"-01";
		}else{
			countDateStart = year + "-" + month+"-01";
		}
		month = parseInt(month)+1;
		if(parseInt(month) > 12){
			year = parseInt(year)+1;
			countDateEnd =  year + "-01-01";
		}else if(month < 10){
			countDateEnd = year + "-0" + month+"-01";
		}else{
			countDateEnd = year + "-" + month+"-01";
		}
	}
	/*
	if(countTime.indexOf("年") != -1){				// 是当前月份
		if(month < 10){
			countDateStart = year + "-0" + month+"-01";
		}else{
			countDateStart = year + "-" + month+"-01";
		}
		month = month+1;
		if(month > 12){
			year = year+1;
			countDateEnd =  year + "-01-01";
		}else if(month < 10){
			countDateEnd = year + "-0" + month+"-01";
		}else{
			countDateEnd = year + "-" + month+"-01";
		}		
	}else if(countTime == 0){				// 自定义时间
		countDateStart = datetimeStart;
		countDateEnd = datetimeEnd;		
	}else{
		countMonth = result[countTime];
		countMonth = countMonth.replace("年","-").replace("月","-");
		year = countMonth.substring(0,4);
		month = countMonth.substring(5,7);
		if(month !=10 && month.indexOf("0")!=-1){					// 包含0
			month = month.substring(1);
		}	
		if(parseInt(month) < 10){
			countDateStart = year + "-0" + month+"-01";
		}else{
			countDateStart = year + "-" + month+"-01";
		}
		month = parseInt(month)+1;
		if(parseInt(month) > 12){
			year = parseInt(year)+1;
			countDateEnd =  year + "-01-01";
		}else if(month < 10){
			countDateEnd = year + "-0" + month+"-01";
		}else{
			countDateEnd = year + "-" + month+"-01";
		}
	}*/
	sParam.timeStart = countDateStart;
	sParam.timeEnd = countDateEnd;
	sParam.xzbh = treeSelectId;
//	console.log("查询：",sParam);
	return sParam;
}


//列表展示
function showList(){
	$("#searchGridListDiv").show();
	$("#searchGridPicDiv").hide();
	displayType = "list";
	$('#searchGridList').datagrid({
		toolbar : toolbar,
		bodyCls:'pic-datagrid',
		rownumbers:true,
		queryParams:getQueryParams(),
		url : 'yworderinfocountAction!listYworderinfocountByPage.do',
		columns : [[
			{field:'xzbh',title:'行政区划编号',hidden:false,width:120},
			{field:'bmmc',title:'行政区划名称',hidden:false,width:120},
			{field:'gdzs',title:'工单总数',hidden:false,width:75},
			{field:'bhgd',title:'驳回工单',hidden:false,width:50},
			{field:'gqgd',title:'挂起工单',hidden:false,width:75},					
			{field:'wwcgd',title:'未完成工单',hidden:false,width:70},
			{field:'ywcgd',title:'已完成工单',hidden:false,width:75},
			{field:'newnetwork',title:'工单完成率',hidden:false,width:75},//需计算
			{field:'jswcgd',title:'及时完成数',hidden:false,width:75},			
			{field:'networkcount',title:'及时完成率',hidden:true,width:120},//需计算
		]],
		onLoadSuccess:function(data){
//	    	  console.log("data",data)
			if(data){
				data.data=data.rows;
				data.totalSize=data.total;
				$('#searchGridList').datagrid("renderAlarmOverviewData",data);
			}
		},

	});	
}

function showBarChart(){
	
	$.ajax({
		type : 'post',
		dateType : 'json',
		url : 'yworderinfocountAction!count_showBar.do',
		data : getQueryParams(),
		success : function(res){
//			console.log("结果：",res);
			if(res){
				$("#searchGridPicDiv").show();
				$("#searchGridListDiv").hide();
				$("#searchGridPic").remove();
				$("#searchGridPicDiv").append($("<div id='searchGridPic'  style='height:100%;width:100%;'></div>"));
				var xData=[];
				var gdzs=[];
				var bhzs=[];
				var gqzs=[];
				var wwczs=[];
				var ywczs=[];
				var jswczs=[];
				res.forEach(function(item,index){
	//				console.log(index,item);
					xData[index] = item.bmmc;
					gdzs[index] = item.gdzs;
					bhzs[index] = item.bhgd;
					gqzs[index] = item.gqgd;
					wwczs[index] = item.wwcgd;
					ywczs[index] = item.ywcgd;
					jswczs[index] = item.jswcgd;
				})
				var data={
						"title":"工单情况统计",
						"xAxis": xData,
						"legend":[
						          {"name":"工单总数", "data":gdzs,  "color":"blue"},
						          {"name":"驳回工单", "data":bhzs, "color":"pink"},
						          {"name":"挂起工单", "data":gqzs, "color":"yellow"},
						          {"name":"未完成工单", "data":wwczs, "color":"red"},
						          {"name":"已完成工单", "data":ywczs, "color":"brown"},
						          {"name":"及时完成数", "data":jswczs, "color":"green"},
						        ]};
				$('#searchGridStatics').datagrid({ toolbar : toolbar});
				EchartsBase.barChart({
					id:"searchGridPic",
					data:data
				});
			}
		}
	})
}


function showExport(type){

	var model = getQueryParams();
	$.ajax({
		type : 'post',
		dataType : 'json',
		data : model,
		url : 'yworderinfocountAction!count_Yworderinfocount.do',
		success : function(value) {
			if(value){
				countExport(value,type);
			}else if(value==0){
				$.showMsg("暂无数据！");
			}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 model = getQueryParams();
	var downParam = "";
	
	var timeStart = model.timeStart;
	var timeEnd = model.timeEnd;
	var xzbh = model.xzbh; 	
	downParam = "xzbh="+xzbh+"&timeStart="+timeStart+"&timeEnd="+timeEnd;
	if(type=="pdf"){
		document.excelForm.action = 'yworderinfocountAction!expPDF_Yworderinfocount.do?'+downParam;
	}else {
		document.excelForm.action = 'yworderinfocountAction!exp_Yworderinfocount.do?'+downParam;
	}
	document.excelForm.submit(); 
}

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($("#deviceName"), setting, data);
            }
        }
    });

}

function zTreeOnClick(event, treeid, treeNode) {
    treeSelectId = treeNode.id;
}


function lookJsgs(index) {
	windowId = top.$.createWin({
		title : '计算公式',
		width  :  '400',
		height :  '200',
		url : sysUrl+"/yw/operationcount/videoarchivecount/orderinfocount/lookJsgs.jsp"
	});
}


function getNowTime(flag){
	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();
	var minsec = date.getMilliseconds(); //获取当前毫秒数(0-999)
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;
    hour = hour < 10 ? '0' + hour : hour;
    second = second < 10 ? '0' + second : second;
    if(flag == "-"){
    	return year +"-"+ month +"-"+ day +" "+ hour +":"+ minute +":"+ second;
    }else{
    	return "" + year + month + day + hour + minute + second + minsec;
    }
    
}

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 : 'yworderinfocountAction!listYworderinfocountByPage.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 f=0
		var g = {"data":data.rows};
		var total = data.total;
		
		if(total>0){
			var nowTime = getNowTime("-");
	         var TABLE='<table  cellspacing="0"  width="90%"  cellpadding="0"  border="1"  align="center"  style="text-align:center;margin:0 auto;	border:1px solid #827d7d;font-size:12px;">\
			           				<thead>\
							        	 <tr style="height: 40px;">\
											<td colspan="10" style="font-size:14px;font-weight:bold;border:none">工单情况统计</td>\
										</tr>\
							     		<tr style="border-top: 1px solid #827d7d;">\
											<td colspan="10" style="text-align:right;border:none;padding: 15px;">制表时间：'+nowTime+'</td>\
										</tr>\
										<tr>\
			           						<td>序号</td>\
		    	 							<td>行政区划</td>\
		    	 							<td>工单总数</td>\
		    	 							<td>驳回工单</td>\
		    	 							<td>挂起工单</td>\
		    	 							<td>未完成工单</td>\
		    	 							<td>已完成工单</td>\
		    	 							<td>工单完成率</td>\
		    	 							<td>及时完成数</td>\
		    	 							<td>及时完成率</td>\
			           					</tr>\
				           			</thead>\
	        	 	<tbody>'
											
			 var zs = 0;
	         var bhzs = 0;
	         var gqzs = 0;
	         var wwczs = 0;
	         var ywczs = 0;
	         var jswczs = 0;
	         
  	        	 for (; (g.data[f]); f++) {
	             	
	         	 	var gdzs = g.data[f].gdzs;
	         	 	var bhgd = g.data[f].bhgd;
	         	 	var gqgd = g.data[f].gqgd;
	         	 	var wwcgd = g.data[f].wwcgd;        	 	
	         	 	var ywcgd = g.data[f].ywcgd;
	         	 	var jswcgd = g.data[f].jswcgd;
	         	 	
	         	 	var wcl = 0;
	         	 	if(gdzs != 0){
	         	 		wcl = ywcgd/gdzs;
	         	 	}
	         	 	if(wcl != 0){
	         	 		wcl = wcl*100; 
	         	 		wcl = wcl.toFixed(2)+"%";
	         	 	}
	         	 	
	         	 	var jswcl = 0;
	         	 	if(gdzs != 0){
	         	 		jswcl = jswcgd/gdzs;
	         	 	}
	         	 	if(jswcl != 0){
	         	 		jswcl = jswcl*100; 
	         	 		jswcl = jswcl.toFixed(2)+"%";
	         	 	}
	         	 	zs = zs + parseInt(gdzs);
	         	 	bhzs = bhzs + parseInt(bhgd);
	         	 	gqzs = gqzs + parseInt(gqgd);
	         	 	wwczs = wwczs + parseInt(wwcgd);
	         	 	ywczs = ywczs + parseInt(ywcgd);
	         	 	jswczs = jswczs + parseInt(jswcgd);
	         	TABLE+='<tr>\
	 		        		<td>'+(f+1)+'</td>\
	 				 		<td>'+g.data[f].bmmc+'</td>\
	 				 		<td>'+gdzs+'</td>\
	 				 		<td>'+bhgd+'</td>\
	 				 		<td>'+gqgd+'</td>\
	 				 		<td>'+wwcgd+'</td>\
	 				 		<td>'+ywcgd+'</td>\
	 				 		<td>'+wcl+'</td>\
	 				 		<td>'+jswcgd+'</td>\
	 				 		<td>'+jswcl+'</td>\
	         	 		 <tr>'
	          }
	          var zwcl = 0;
	          var zjswcl = 0;
	          if(zs != 0){
	         	 zwcl =  zwcl/zs;
	         	 zjswcl = jswczs/zs;
	          }
	          if(zwcl != 0){
	         	 zwcl = zwcl*100; 
	         	 zwcl = zwcl.toFixed(2)+"%";
	  	 	 }
	          if(zjswcl != 0){
	         	 zjswcl = zjswcl*100; 
	         	 zjswcl = zjswcl.toFixed(2)+"%";
	          }
	          TABLE+="<tr>" +
	          			"<td colspan='2'>总计</td>" +
	          			"<td>"+zs+"</td>" +
	          			"<td>"+bhzs+"</td>" +
	          			"<td>"+gqzs+"</td>" +
	          			"<td>"+wwczs+"</td>" +
	          			"<td>"+ywczs+"</td>" +
	          			"<td>"+zwcl+"</td>" +
	          			"<td>"+jswczs+"</td>" +
	          			"<td>"+zjswcl+"</td>" +
	          		"</tr>";
	         
	         
	         TABLE+= "</tbody></table>";
		}else{
			return;
		}
 		
		
 		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();
		
	 
	}
}