var proName = window.location.pathname.split("/")[1];
var sysUrl = "http://"+window.location.host+"/"+proName;
var displayType = "list";
var toolbar = [];
$(function() {
	$("#startTime").datetimebox("setValue",$.getTodayStart(0,"00:00:00"));
	$("#endTime").datetimebox("setValue",$.getTodayEnd("23:59:59"));
//	initXzNameTree();
	
	$("#deviceType").combobox({
		onChange:function(newValue,oldValue){
			changeDisplayByDevice(newValue);
    	}
	});
	$("#deviceChoose").combobox({
		onSelect:function(value){
			openDevice("1",value);
		}
	});
	$("#machineChoose").combobox({
		onSelect:function(value){
			openDevice("2",value);
		}
	});
	initSelect();
	initGrid();
});

//增加
function openDevice(type,value){
	var text=value.text.trim();
	if(text!="全部"){
		WindowId = top.$.createWin({
			title	: 	'增加信息',
			width	:  	1050,
			height	: 	600,
			data    : type,
			buttons:  [{
				text:$.fn.textbox.defaults.ok,
				handler:saveNodeInfo
			}],
			url	:	sysUrl+"/yw/alarmWorkbench/alarmWorkbenchDeviceChoose.jsp"
		});
	}
}

function saveNodeInfo(){
	var data = top.$("#"+WindowId).panel("options").data;
	var win		=	top.$.getTopWindowById(WindowId);
	top.$("#"+WindowId).dialog('close');
	var rows =win.$('#sbtdspsrInfo')[0].contentWindow.getSelectedRows(); 
	var result="";
	for(var i=0,len=rows.length;i<len;i++){
		if(i==len-1){
			result+=rows[i].sbbh+"_"+rows[i].tdbh;
		}else{
			result+=rows[i].sbbh+"_"+rows[i].tdbh+",";
		}
	}
	if(data=="1"){
		$('#deviceChoose').combobox('setValue', result);
		$('#deviceChoose').combobox('setText', result);
	}else{
		$('#machineChoose').combobox('setValue',result);
		$('#machineChoose').combobox('setText', result);
	}
}
$.extend($.fn.datagrid.methods,
		{
	renderMonitorData: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;
         for (; (g.data[f]); f++) {
//             g.data[f].oprStatusStr = g.data[f].oprStatus == 0 ? "正常": "异常";
             g.data[f].oprStatusColor = 'style="color:' + (g.data[f].oprStatus == 0 ? "blue;": "red;") + '"';
//             g.data[f].picturepath = sysUrl+"/sourceProxy?fileType=picUrlProxy&picUrl="+g.data[f].picturepath;

//             g.data[f].picturepath = $.getPicProxyUrl(g.data[f].picturepath);
//             l.push('<div class="view-item" style="width:300px;position:relative;"><div class="showAlarmType" style="top: -15px;right: 4px;width: 67px; color: white;z-index: 10; height: 40px;background: #1612263b;font-size: 14px;font-weight: bolder;position:absolute;text-align: center; line-height: 40px;">'+g.data[f].oprStatusStr+'</div>' + '<img  src="' + (g.data[f].picturepath) + '" onerror="javascript:$.loadErrorPic(this);" style="width:218px;"/><div>' + "<p>相机名称:&nbsp;" + (g.data[f].channelname || "无") + "</p>" + "<p>抓拍时间:&nbsp;" + (g.data[f].runtime || "") + "</p>" + "<p>告警类型:&nbsp;<span " + g.data[f].oprStatusColor + ">" + (g.data[f].oprStatusStr || "") + "</span></p>" + '<p><a href="javascript:void(0);" tag=' + g.data[f].id + ' class="ahref" onclick="oprStatus(this,0);" >标记正常</a> &nbsp;&nbsp;&nbsp; <a href="javascript:void(0);" tag=' + g.data[f].id + ' class="ahref" onclick="oprStatus(this,1);" >标记异常</a>&nbsp;&nbsp;&nbsp; <a href="javascript:void(0);" tag=' + g.data[f].id + ' class="ahref" onclick="oprStatus(this,2);" >重点关注</a></p>' + "</div></div>")
            if(g.data[f].videolabelstatusname==null){
            	l.push('<div class="view-item" style="width:220px;position:relative;">'
            			+' <div class="showAlarmType" style="top: -15px;right: 4px;width: 67px; color: white;z-index: 10; height: 40px;background: #1612263b;font-size: 14px;font-weight: bolder;position:absolute;text-align: center; line-height: 40px;display:none;">'+g.data[f].videolabelstatusname+'</div>' 
            			+ '<img onclick="detailVideoQuality(\''+g.data[f].id+'\');"  src="' + (g.data[f].picturepath) + '" onerror="javascript:$.loadErrorPic(this);" style="width:218px;"/><div style="width:218px;">' + "<p>相机名称:&nbsp;" + (g.data[f].channelname || "无") + "</p>" + "<p style='line-height:20px;'>抓拍时间:&nbsp;" + (g.data[f].runtime || "") + "</p>" + "<p style='line-height:20px;'>告警类型:&nbsp;<span " + g.data[f].oprStatusColor + ">" + (g.data[f].videostatusname || "") + "</span></p>" + labelstatusRender(g.data[f].id,g.data[f].videolabelstatusname) + "</div></div>")
            }else{
            	l.push('<div class="view-item" style="width:220px;position:relative;">'
            			+' <div class="showAlarmType" style="top: -15px;right: 4px;width: 67px; color: white;z-index: 10; height: 40px;background: #1612263b;font-size: 14px;font-weight: bolder;position:absolute;text-align: center; line-height: 40px;">'+g.data[f].videolabelstatusname+'</div>' 
            			+ '<img onclick="detailVideoQuality(\''+g.data[f].id+'\');" src="' + (g.data[f].picturepath) + '" onerror="javascript:$.loadErrorPic(this);" style="width:218px;"/><div style="width:218px;">' + "<p>相机名称:&nbsp;" + (g.data[f].channelname || "无") + "</p>" + "<p style='line-height:20px;'>抓拍时间:&nbsp;" + (g.data[f].runtime || "") + "</p>" + "<p style='line-height:20px;'>告警类型:&nbsp;<span " + g.data[f].oprStatusColor + ">" + (g.data[f].videostatusname || "") + "</span></p>" + labelstatusRender(g.data[f].id,g.data[f].videolabelstatusname) + "</div></div>")
            }
         }
         c.html('<div class="img-box">' + l.join("") + "</div>")
     }
});
//加载列表
function initGrid(){	
	toolbar = [{
        text:'查询',
        iconCls:'icon-search',
        handler:function(){doSearch();}
    },
    {
		text:'图片列表',
		iconCls:'icon-showPic',
		handler:showPicture
	},
    {
		text:'普通列表',
		iconCls:'icon-showList',
		handler:showList
	},
    {
		text:'统计',
		iconCls:'icon-showStatics',
		handler:showStatics
	},
    {
		text:'导出',
		iconCls:'icon-download',
		handler:doExport
	}];
	showList();
	
}
//图片展示
function showPicture(){
	$("#searchGridPicDiv").show();
	$("#searchGridListDiv").hide();
	$("#searchGridStaticsDiv").hide();
	displayType = "picture";
	if($('#deviceType').textbox("getValue")=="1"){//监控设备
		$('#searchGridPic').datagrid({
			toolbar : toolbar,
			bodyCls:'pic-datagrid',
			queryParams:getQueryParams(),
			url : 'ywvideotaskrunresultAction!listYwvideotaskrunresultByPage.do',
			onLoadSuccess:function(data){
				if(data){
					data.data=data.rows;
					data.totalSize=data.total;
					$('#searchGridPic').datagrid("renderMonitorData",data);
				}
			},
			rownumbers:true,
		});
	}else if($('#deviceType').textbox("getValue")=="2"){
		$('#searchGridPic').datagrid({
			toolbar : toolbar})
	}
	
}
//统计展示
function showStaticsLine(staticsType){
	var param = {};
	if($('#deviceType').textbox("getValue")=="1"){
		param = getQueryParams();
	}else if($('#deviceType').textbox("getValue")=="2"){
		var startTime = $('#startTime').datetimebox("getValue");	
		var endTime = $('#endTime').datetimebox("getValue");
		var tableparam = "";
		if(!(startTime==null||startTime==""||startTime==undefined)){
			tableparam += " AND countDate >= '" +startTime + "'";
		}
		if(!(endTime==null||endTime==""||endTime==undefined)){
			tableparam += " AND countDate <= '" +endTime + "'";
		}
//		param.machineFailureType = $("#machineFailureType").textbox("getValue");
		param.tableparam = tableparam;
	}
	param.staticsType = staticsType;
	param.deviceType = $('#deviceType').textbox("getValue");
	$("#deviceAnalysisGraphChartBoxTime li").removeClass("active");
	$.ajax({
		url : "ywvideotaskrunresultAction!videoStatisticsLine.do",
		dataType : "JSON",
		type : "POST",
		data : param,
		success : function(res){
			if(res){
				var xData = [];
				var yData = [];
				if(staticsType=="1"){//按小时
					xData = ['01','02','03','04','05','06','07','08','09',
					             '10','11','12','13','14','15','16','17','18','19',
					             '20','21','22','23','24'
					             ];		
					yData = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
					$("#deviceAnalysisGraphChartBoxTime li").eq(0).addClass("active");
				}else if(staticsType=="2"){//按天
					xData = ['1','2','3','4','5','6','7','8','9',
					             '10','11','12','13','14','15','16','17','18','19',
					             '20','21','22','23','24','25','26','27','28','29','30','31'
					             ];				
					yData = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];			
					$("#deviceAnalysisGraphChartBoxTime li").eq(1).addClass("active");
				}else{//按月
					xData = ['1','2','3','4','5','6','7','8','9',
					             '10','11','12'
					             ];			
					yData = [0,0,0,0,0,0,0,0,0,0,0,0];			
					$("#deviceAnalysisGraphChartBoxTime li").eq(2).addClass("active");
				}
				res.forEach(function(item){	
					if(item!=null && item.xData!=null){
						var index = 0;
						if(item.xData.indexOf("0")==0){
							index = parseInt(item.xData.substring(1))
						}else{
							index = parseInt(item.xData)
							
						}
						yData.splice(index-1,1,item.num);	
						
					}
				});
				var data={"title":"告警趋势分析",
						xAxis:xData,
						legend:[{name:"",data:yData,"color":"#00accb"}]
				}
			//	EchartsBase.data={"title":"本周运维告警统计",xAxis: ["监控","NVR","服务器","应用系统"],"legend":[{"name":"Doset","data":[5, 20, 36, 50],"color":"#00accb"},{"name":"Yeland","data":[51, 210, 36, 10],"color":"#fa102a"}]};

				EchartsBase.lineChart(
			 			{
			 			id:"searchGridStaticsEchartLine",
			 			data:data
			 	});
			}
			
			console.log(res)
		}
	});
}
function showStatics(){
	$("#searchGridStaticsDiv").show();
	$("#searchGridPicDiv").hide();
	$("#searchGridListDiv").hide();
	displayType = "statics";
	$('#searchGridStatics').datagrid({ toolbar : toolbar});
	if($('#deviceType').textbox("getValue")=="1"){//监控设备
		//统计
		//折线图 
		
		showStaticsLine("1");
		//饼状图
		$.ajax({
			url : "ywvideotaskrunresultAction!videoStatistics.do",
			dataType : "JSON",
			type : "POST",
			data : getQueryParams(),
			success : function(res){
				if(res!=null){
					var data={"title":"设备故障类型占比分析",
							data:[
							      {name:"网络异常",value:res.networkerrorNum,color:"#fe0000"},
							      {name:"信号异常",value:res.nosignalstatusNum,color:"#e16616"},
							      {name:"图像清晰异常",value:res.videonoisestatusNum,color:"#f6a518"},
							      {name:"图像对比异常",value:res.imgcontraststatusNum,color:"#e36d6d"},
							      {name:"颜色检测异常",value:res.imgcolorstatusNum,color:"#754599"},
							      {name:"亮度检测异常",value:res.imglightstatusNum,color:"#84ccc9"},
							      {name:"视频冻结异常",value:res.videofreezestatusNum,color:"#60b631"},
							      {name:"镜头抖动",value:res.videojitterstatusNum,color:"#add597"},
							      {name:"视频剧变异常",value:res.videoupheavalstatusNum,color:"#24b8e8"},
							      {name:"编码异常",value:res.videocodeerrorstatusNum,color:"#c0bebf"},
							      {name:"噪声雪花异常",value:res.videonoisestatusNum,color:"#c8da2e"},
							      {name:"滚动条纹异常",value:res.videorollstripestatusNum,color:"#c8da2e"}
							     //,{name:"执行异常",value:res.runstatusNum,color:"#c8da2e"}
							      ]
					};		
				 	EchartsBase.alarmWorkbenchPieChart(
				 			{
				 			id:"searchGridStaticsEchartPie",
				 			data:data
				 	});
				}
				console.log("resresres",res);
			}
		});
	}else if($('#deviceType').textbox("getValue")=="2"){
		showStaticsLine("1");
	}
	
}
//列表展示
function showList(){
	$("#searchGridListDiv").show();
	$("#searchGridPicDiv").hide();
	$("#searchGridStaticsDiv").hide();
	displayType = "list";
	if($('#deviceType').textbox("getValue")=="1"){//监控设备
		$('#searchGridList').datagrid({
			toolbar : toolbar,
			singleSelect:true,
			queryParams:getQueryParams(),
			url : 'ywvideotaskrunresultAction!listYwvideotaskrunresultByPage.do',
			columns : [[
					    {
							field: 'A',
							checkbox:'true',
							width:30
						},
					    {field:'id',title:'id',hidden:true,width:120, 
							formatter:function showClick(value,record,num){ 
								return "<a  href='javascript:void(0);' class='ahref' onclick='doUpdate("+num+")'>"+value+"</a>";
							}
			 			},
						{field:'runsetid',title:'运行批次id',hidden:true,width:120},
						{field:'taskid',title:'任务id',hidden:true,width:120},
						{field:'taskname',title:'任务名称',hidden:false,width:120},
						{field:'tasktypename',title:'任务类型',hidden:false,width:120},
						{field:'channelsetid',title:'通道集合id',hidden:true,width:120},
						{field:'channelname',title:'通道名称',hidden:false,width:120},
						{field:'videonum',title:'设备编号',hidden:false,width:120},
						{field:'channelnum',title:'通道编号',hidden:false,width:60},
						{field:'picturepath',title:'有无图片',hidden:false,width:60,
							formatter:function showClick(value,record,num){ 
								if(value){
									return "有";
								}else{
									return "无";
								}
							}
						},
						{field:'picturebyte',title:'图片-设计需要',hidden:true,width:120},
						{field:'isonline',title:'是否在线',hidden:true,width:60},
						{field:'isonlinename',title:'是否在线',hidden:false,width:60},
						{field:'playfail',title:'播放失败',hidden:true,width:120},
						{field:'networkerror',title:'网络异常',hidden:true,width:60,},
						{field:'networkerrorname',title:'网络异常',hidden:false,width:60,
							formatter:function showClick(value,record,num){
								return transStatus(value+"");
//								return "<div style='height:15px;width:15px;background-color:#fe0000;margin:0 auto;'></div>";
						}},
						{field:'nosignalvalue',title:'无信号检测值',hidden:true,width:110,
							/*formatter:function(value,record,num){ 
								var value="90";
								value = value.indexOf('%')>0 ? value.replace("%",""):value;
								return $.gridProgressBar(value+"%",100*value/100.00); 
							}	*/
						},
						{field:'nosignalstatus',title:'无信号检测状态',hidden:false,width:95,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'imgclearvalue',title:'图像清晰检测值',hidden:true,width:95},
						{field:'imgclearstatus',title:'图像清晰检测状态',hidden:false,width:110,
							formatter:function showClick(value,record,num){ 
								return transStatus(value);
							}
						},
						{field:'imgcontrastvalue',title:'图像对比检测值',hidden:true,width:95},
						{field:'imgcontraststatus',title:'图像对比检测状态',hidden:false,width:110,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'imgcolorvalue',title:'颜色检测值',hidden:true,width:70},
						{field:'imgcolorstatus',title:'颜色检测状态',hidden:false,width:90,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'imglightvalue',title:'亮度检测值',hidden:true,width:120},
						{field:'imglightstatus',title:'亮度检测状态',hidden:false,width:120,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'videofreezevallue',title:'视频冻结检测值',hidden:true,width:120},
						{field:'videofreezestatus',title:'视频冻结检测状态',hidden:false,width:120,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'videojittervalue',title:'镜头抖动检测值',hidden:true,width:120},
						{field:'videojitterstatus',title:'镜头抖动检测状态',hidden:false,width:120,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'videoupheavalvalue',title:'视频剧变检测值',hidden:true,width:120},
						{field:'videoupheavalstatus',title:'视频剧变检测状态',hidden:false,width:120,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'videocodeerrorvalue',title:'编码异常检测值',hidden:true,width:120},
						{field:'videocodeerrorstatus',title:'编码异常检测状态',hidden:false,width:120,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'videonoisevalue',title:'噪声雪花检测值',hidden:true,width:120},
						{field:'videonoisestatus',title:'噪声雪花检测状态',hidden:false,width:120,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'videorollstripevalue',title:'滚动条纹检测值',hidden:true,width:120},
						{field:'videorollstripestatus',title:'滚动条纹检测状态',hidden:false,width:120,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'videostatus',title:'监控状态',hidden:false,width:120,
							formatter:function showClick(value,record,num){ 
								return transStatus(value+"");
							}
						},
						{field:'failurecause',title:'故障原因',hidden:false,width:120},
						{field:'runstatusname',title:'执行状态',hidden:false,width:120},
						{field:'runtime',title:'执行时间',hidden:false,width:120},
						{field:'createaccount',title:'创建人员',hidden:true,width:120},
						{field:'createtime',title:'创建日期',hidden:true,width:120},
						{field:'modifyaccount',title:'修改人员',hidden:true,width:120},
						{field:'modifytime',title:'修改日期',hidden:true,width:120},
						{field:'remarks',title:'备注',hidden:true,width:120},
						{field:'extend1',title:'扩展1',hidden:true,width:120},
						{field:'extend2',title:'扩展2',hidden:true,width:120},
						{field:'extend3',title:'扩展3',hidden:true,width:120},
						{field:'extend4',title:'扩展4',hidden:true,width:120}
					]]
		});
	}else if($('#deviceType').textbox("getValue")=="2"){
		$('#searchGridList').datagrid({
			toolbar : toolbar,
			singleSelect:true,
			queryParams:getQueryParams(),
			url : 'ywmachinestatusinfoAction!get_ywmachinestatusinfo.do',
			columns : [[
			    {
					field: 'A',
					checkbox:'true',
					width:30
				},
			    {field:'machinestatusid',title:'machinestatusid',hidden:true,width:120, 
					formatter:function showClick(value,record,num){ 
						return "<a  href='javascript:void(0);' class='ahref' onclick='doUpdate("+num+")'>"+value+"</a>";
					}
	 			},
				{field:'machinename',title:'机器名称',hidden:false,width:120},
				{field:'machineip',title:'设备ip',hidden:false,width:120},
				{field:'zjzt',title:'主机状态',hidden:false,width:60,
					formatter:function showClick(value,record,num){ 
		//				console.log("主机：",value,record);
	 					if(value==1){
							return "<div style='height:15px;width:15px;background-color:green;margin:0 auto;'></div>";				
						}else if(value==0){
							return "<div style='height:15px;width:15px;background-color:#fe0000;margin:0 auto;'></div>";						
						}else{
							return value;
						}
					}
				},
				{field:'cpuzt',title:'cpu使用率',hidden:false,width:120,
					formatter:function(value,record,num){ 
						var cpu = record.cpusyl;
						if(cpu != null){
							cpu = cpu.indexOf('%')>0 ? cpu.replace("%",""):cpu;
							if(value == 0){
								return '<div class="progress"><div class="progress-value"  style="background-color:red;width: ' + (cpu || 0) + 'px;"><div class="progress-text">' + (cpu+"%" || "") + "</div></div></div>"
							}else {
								return $.gridProgressBar(cpu+"%",100*cpu/100.00);
							}						
						}else{
							return "未知";
						}
						
					}	
				},
				{field:'nczt',title:'内存使用率',hidden:false,width:250,
					formatter:function(value,record,num){ 
						var nc = record.ncsyl;
						var ncrl = record.ncrl;
						var sync = "";
						if(nc != null){
							nc = nc.indexOf('%')>0 ? nc.replace("%",""):nc;
							sync = (ncrl * nc)/100;
							if(value == 0){
								return '<div class="progress">'+
											'<div class="progress-value"  style="background-color:red;width: ' + (nc || 0) + 'px;">'+
												'<div class="progress-text">' + (nc+"%" || "") + "</div>" +
											"</div>" + 
											"<div style='position: relative;left: 105px; top: -18px;'>"+sync+"G / "+ncrl+"G(总)</div>"+
										"</div>";
							}else {
								return '<div class="progress">'+
											'<div class="progress-value"  style="width: ' + (nc || 0) + 'px;">'+
												'<div class="progress-text">' + (nc+"%" || "") + "</div>" +
											"</div>" +
											"<div style='position: relative;left: 105px; top: -18px;'>"+sync+"G / "+ncrl+"G(总)</div>"+
										"</div>";
								
							}
						//	return $.gridProgressBar(nc+"%",100*nc/100.00);
						}else{
							return "未知";
						}
						 
					}		
				},
				{field:'ypzt',title:'硬盘使用率',hidden:false,width:250,
					formatter:function(value,record,num){ 
						var yp = record.ypsyl;
						var yprl = record.yprl;
						var ypsy="";					
						if(yp != null){
							yp = yp.indexOf('%')>0 ? yp.replace("%",""):yp;
							ypsy = (yprl * yp)/100;
							if(value == 0){
								return '<div class="progress">'+
											'<div class="progress-value"  style="background-color:red;width: ' + (yp || 0) + 'px;">'+
												'<div class="progress-text">' + (yp+"%" || "") + "</div>" +
											"</div>" + 
											"<div style='position: relative;left: 105px; top: -18px;'>"+ypsy+"G / "+yprl+"G(总)</div>"+
										"</div>";						
							}else {
								return '<div class="progress">'+
											'<div class="progress-value"  style="width: ' + (yp || 0) + 'px;">'+
												'<div class="progress-text">' + (yp+"%" || "") + "</div>" +
											"</div>" + 
											"<div style='position: relative;left: 105px; top: -18px;'>"+ypsy+"G / "+yprl+"G(总)</div>"+
										"</div>";
							} 
						}else{
							return "未知";
						}
						
					}	
				},
				{field:'statusuptime',title:'检测时间',hidden:false,width:125},
				
			]]
		});
	}
	
}
function doSearch() {
	if(displayType=="list"){
		showList();
	}else if(displayType=="picture"){
		showPicture();
	}else{
		showStatics();
	}
//	$('#searchGrid').datagrid('load', getQueryParams());
}

function getQueryParams(){
	var sParam = {};
	var startTime = $('#startTime').datetimebox("getValue");	
	var endTime = $('#endTime').datetimebox("getValue");	
	var tableparam = "";
	sParam.deviceType = $('#deviceType').textbox("getValue"); 
	if(sParam.deviceType=="1"){//监控设备
		if(!(startTime==null||startTime==""||startTime==undefined)){
			tableparam += " AND runtime >= '" +startTime + "'";
		}
		if(!(endTime==null||endTime==""||endTime==undefined)){
			tableparam += " AND runtime <= '" +endTime + "'";
		}
		if($("#failureType").textbox("getValue")!=""){
			tableparam += " AND "+$("#failureType").textbox("getValue")+"=0 ";
		}
		sParam.order = "order by runtime desc ";
		sParam.deviceChoose = $('#deviceChoose').textbox("getValue"); 
		sParam.videostatus = "0" 
		sParam.failureType = $('#failureType').textbox("getValue"); 
	}else if(sParam.deviceType=="2"){//服务器设备  
		sParam.machinedevicestatus = "0" 
		/*if(!(startTime==null||startTime==""||startTime==undefined)){
			tableparam += " AND statusuptime >= '" +startTime + "'";
		}
		if(!(endTime==null||endTime==""||endTime==undefined)){
			tableparam += " AND statusuptime <= '" +endTime + "'";
		}*/
		/*if($("#machineFailureType").textbox("getValue")!=""){
			tableparam += " AND "+$("#machineFailureType").textbox("getValue")+"=0 ";
		}*/
		sParam.startTime = startTime;
		sParam.endTime = endTime;
		sParam.order = "order by statusuptime desc ";
	}
	
	sParam.tableparam = tableparam;
	sParam.alarmLevel = $('#alarmLevel').textbox("getValue"); 
	
	return sParam;
}

function oprStatus(obj,videolabelstatus) {
	var id = $(obj).attr("id");
	var m = {};
	m.XGTJid = id;
	var html=$(obj).html().trim();
	if(html=='取消关注'){
		m.videolabelstatus = "-1";
	}else{
		m.videolabelstatus = videolabelstatus;
	}
	$.ajax({
		url:'ywvideotaskrunresultAction!updateVideolabelStatus.do',
		type:"post",
		dataType:"JSON",
		data : m,
		success:function(res){
			if(res){
				$(obj).parents(".view-item").find(".showAlarmType").html(html);
				$(obj).parents(".view-item").find(".showAlarmType").css("display","block");
				if(videolabelstatus==2){
					if(html=='重点关注'){
						$(obj).html('取消关注');
					}else{
						$(obj).html('重点关注');
					}
				}
			}
		}
	});
}

function initSelect(){
	//加载下拉框
	var alarmLevelArr = [
	                     {"id":"","text":"全部","selected":true},
	                     {"id":"1","text":"一级"},
	                     {"id":"2","text":"二级"},
	                     {"id":"3","text":"三级"},
	                     {"id":"4","text":"四级"},
	                     {"id":"5","text":"五级"}
	                     ];
	var deviceTypeArr = [
	                     {"id":"1","text":"监控设备","selected":true},
	                     {"id":"2","text":"服务器设备"}
	                     ];
	var deviceChooseArr = [
	                     {"id":"","text":"全部","selected":true},
	                     {"id":"2","text":"列表选择"}
	                     ];
	var failureTypeArr = [
	                      {"id":"","text":"全部","selected":true},
	                      {"id":"networkerror","text":"网络异常"},
	                      {"id":"nosignalstatus","text":"无信号异常"},
	                      {"id":"imgclearstatus","text":"图像清晰异常"},
	                      {"id":"imgcontraststatus","text":"图像对比异常"},
	                      {"id":"imgcolorstatus","text":"颜色检测异常"},
	                      {"id":"imglightstatus","text":"亮度检测异常"},
	                      {"id":"videofreezestatus","text":"视频冻结异常"},
	                      {"id":"videojitterstatus","text":"镜头抖动异常"},
	                      {"id":"videoupheavalstatus","text":"视频剧变异常"},
	                      {"id":"videocodeerrorstatus","text":"编码异常"},
	                      {"id":"videonoisestatus","text":"噪声雪花异常"},
	                      {"id":"videorollstripestatus","text":"滚动条纹异常"}
	                     ];
	var machineFailureTypeArr = [
	                      {"id":"","text":"全部","selected":true},
	                      {"id":"1","text":"主机异常"},
	                      {"id":"2","text":"cpu异常"},
	                      {"id":"3","text":"硬盘异常"},
	                      {"id":"4","text":"内存异常"},
	                      ];
	
	
	$("#alarmLevel").combobox( "loadData", alarmLevelArr);
	$("#deviceType").combobox( "loadData", deviceTypeArr);
	$("#deviceChoose").combobox( "loadData", deviceChooseArr);
	$("#machineChoose").combobox( "loadData", deviceChooseArr);
	$("#failureType").combobox( "loadData", failureTypeArr);
	$("#machineFailureType").combobox( "loadData", machineFailureTypeArr);
	
}

function labelstatusRender(id,name){
	var $p = ""
	$.ajax({
		url:" xtclAction!query_Xtcl_task.do",
		type:"post",
		dataType:"JSON",
		async:false,
		data : {"csdl":"ywvideolabelstatus"},
		success:function(res){
			if(res){
				$p += '<p>';
				for(i in res){
					var $a = "";
					if(name=="重点关注" && res[i].csdm=="2"){
						$a = "<a href=\"javascript:void(0);\" id=\""+id+"\"  tag=\""+id+"\" class=\"ahref\" onclick=\"oprStatus(this,'-1');\" >取消关注</a>&nbsp;&nbsp;&nbsp;";
					}else{
						$a = "<a href=\"javascript:void(0);\" id=\""+id+"\"  tag=\""+id+"\" class=\"ahref\" onclick=\"oprStatus(this,'"+res[i].csdm+"');\" >"+res[i].csmc+"</a>&nbsp;&nbsp;&nbsp;";
					}
					$p +=$a;
				}
				$p += "</p>";
			}
		}
	});
	return $p;
}

function detailVideoQuality(id){

	var url = top.sysUrl+"/yw/videoalarm/itemPage/detailVideoQuality.jsp";
	windowid = top.$.createWin({
		 title	: 	'详情',
		 width  :  '720',
		 height :  '400',
		 data:id,
		 url	:  url,
		 onClose:function(){
			 var win		=	$.getTopWindowById(windowid);
			 for(var i = 0;i < win.BlockCacher.blockCache.length;i++){
					if(win.BlockCacher.blockCache[i].fdId && win.BlockCacher.blockCache[i].channelId != null){
						win.BlockUtil.stopMonitor(i);
					}
				}
		 }
	 });
}

function transStatus(data){
	if(data=="1"){
		return  "<div style='height:15px;width:15px;background-color:#60b631;margin:0 auto;'></div>";
	}
	return "<div style='height:15px;width:15px;background-color:#fe0000;margin:0 auto;'></div>";
}

function changeDisplayByDevice(newValue){
	if(newValue=="1"){//监控设备
		$("#failureTypeDiv").css("display","block");
		$("#deviceChooseDiv").css("display","block");
		$("#machineFailureTypeDiv").css("display","none");
		$("#machineChooseDiv").css("display","none");
	}else if(newValue=="2"){
		$("#machineFailureTypeDiv").css("display","block");
		$("#machineChooseDiv").css("display","block");
		$("#failureTypeDiv").css("display","none");
		$("#deviceChooseDiv").css("display","none");
	}
}
//导出
function doExport(){
	var model = getQueryParams();
	$.ajax({
		type : 'post',
		dataType : 'json',
		data : model,
		url : 'ywvideotaskrunresultAction!count_Ywvideotaskrunresult.do',
		success : function(value) {
			if(value){
				countExport(value);
			}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 = 'ywvideotaskrunresultAction!exp_Ywvideotaskrunresult.do?downParam='+downParam;
	document.excelForm.submit(); 
}