var detailWindow,detailWindowId =$.uniqueId(),windowId,proName = window.location.pathname.split("/")[1],sysUrl = "http://"+window.location.host+"/"+proName,toEdit;

//var proName = top.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"));
	$("#deviceChoose").combobox({
		onSelect:function(value){
			openDevice($("#deviceType").combobox("getValue"),value);
		}
	});
	initSelect();
	initGrid();
});
//查询条件
function getQueryParams(){
	var sParam = {};
	sParam.LIKEalarmdevicename = $('#deviceName').textbox("getValue").trim();	
	sParam.alarmdevicetype = $('#deviceType').textbox("getValue"); 
	sParam.deviceChoose = $('#deviceChoose').textbox("getValue"); 
	var processStatus = $('#processStatus').textbox("getValue"); 
	sParam.alarmgrade = $('#alarmLevel').textbox("getValue");
	sParam.alarmtype = $('#alarmType').textbox("getValue"); 
	var startTime = $('#startTime').datetimebox("getValue");	
	var endTime = $('#endTime').datetimebox("getValue");	
	var tableparam = "";
	if (processStatus == '1') { // 待处理
		sParam.processstatus = '900';
	} else if (processStatus == '2') { // 处理中
		tableparam += " AND processstatus in ('901','902','904','905','906','907','908','909','910','913')";
	} else if (processStatus == '3') { // 已处理
		tableparam += " AND processstatus in ('903','912','911','914')";
	}
	if(!(startTime==null||startTime==""||startTime==undefined)){
		tableparam += " AND alarmtime >= '" +startTime + "'";
	}
	if(!(endTime==null||endTime==""||endTime==undefined)){
		tableparam += " AND alarmtime <= '" +endTime + "'";
	}
	sParam.tableparam = tableparam;
	sParam.order = "order by alarmtime desc ";
	return sParam;
}
//加载列表
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
	},{
		text:'忽略告警',
		iconCls:'icon-ignoreWarning',
		handler:ignoreAlarm
	},{
		text:'工单上报',
		iconCls:'icon-Workorderreport',
		handler:reportOrder
	},{
			text:'新增告警',
			iconCls:'icon-Workorderreport',
			handler:insertAlarm
		}];
	showList();
	
}

//工单上报
function reportOrder(){
	var selRows = $('#searchGridList').datagrid('getChecked'); 
//	console.log("忽略：",selRows);
	if(selRows===null || selRows.length < 1){
		$.showMsg('请先选择一行! ');
		 return;
	}
	if (selRows[0].processstatus != "900") {
		$.showMsg("工单已上报，请勿重复上报！");
		return;
	}
	if(selRows.length ==1){
		windowId = top.$.createWin({
			title	: 	'工单上报',
			width	:  	860,
			height	: 	420,
			buttons:  [{
				text:$.fn.textbox.defaults.ok,
				handler:saveOrder
			}],
			data  :  selRows[0],
//		url	:	sysUrl+"/yw/orders/ywrepairjobinfo/ywrepairjobinfo_show.jsp"
			url : sysUrl + "/yw/repairmanage/ywworkorder/ywreportorder.jsp"
		});
	}else{
		windowId = top.$.createWin({
			title	: 	'批量工单上报',
			width	:  	850,
			height	: 	400,
			buttons:  [{
				text:$.fn.textbox.defaults.ok,
				handler:saveBatchOrder
			}],
			data  :  selRows,
//		url	:	sysUrl+"/yw/orders/ywrepairjobinfo/ywrepairjobinfo_show.jsp"
			url : sysUrl + "/yw/repairmanage/ywworkorder/ywbatchreportorder.jsp"
		});
	}
}
//忽略告警
function ignoreAlarm(){
	var selRows = $('#searchGridList').datagrid('getChecked'); 
//	console.log("忽略：",selRows);
	if(selRows===null || selRows.length < 1){
		$.showMsg('请先选择一行! ');
		 return;
	}else{	
		if (selRows[0].processstatus != "900") {
			$.showMsg("工单已上报，请勿重复上报！");
			return;
		} else {
			windowId = top.$.createWin({
				title	: 	'忽略告警',
				width	:  	450,
				height	: 	200,
				buttons:  [{
					text:$.fn.textbox.defaults.ok,
					handler:sureIgnore
				}],
				url	:	sysUrl+"/yw/homepage/ignorecase.jsp"
			 });
		}
	}
}
function saveBatchOrder(){
}
function saveOrder(){
	var win		=	$.getTopWindowById(windowId);
	var jq		=	win.$;
	var model   =   $.getFormValues("order",windowId);		// 得到 工单接收人和单位
	
	if(model.jobacceptcompany==null || model.jobacceptcompany==""){
		$.showMsg('工单接收人单位不能为空 ');
		return;
	}
	if(model.jobacceptpeople==null || model.jobacceptpeople==""){
		$.showMsg('工单接收人不能为空 ');
		return;
	}
	var jobnum = jq('#jobnum').html();							// 工单编号
	var jobreportcompany = jq('#jobreportcompany').val();		// 上报人单位
	var jobreportpeople = jq('#jobreportpeople').html();		// 上报人
	var jobreportphone = jq('#jobreportphone').html();			// 上报人电话
	var jobreporttime = jq('#jobreporttime').html();			// 上报时间
	var jobacceptphone = jq('#jobacceptphone').html();			// 接收人联系方式

	if (jobacceptphone == "" || jobacceptphone == null) {
		$.showMsg('请到平台用户管理更新接收人联系电话');
		return;
	}
	var reg = /^[0-9]{11}$/;
	if (!reg.test(jobacceptphone)) {
		$.showMsg('请修改为有效11位接收人联系电话');
		return;
	}
	
	var faultdescription = jq('#faultdescription').val();		// 故障描述
	
	var sel = $('#searchGridList').datagrid('getSelected');

	model.jobnum = jobnum;
	model.jobsource = "1";
	model.alarmeventid = sel.alarmeventid;
	model.faultdevicetype = sel.alarmdevicetype;
	model.faultdevicename = sel.alarmdevicename;
	model.faultdeviceid = sel.alarmdeviceid;
	if (sel.channelnum != null) {
		model.channelnum = sel.channelnum;
	}
	faultpictureurl = sel.pictureurl;
	if(faultpictureurl != null){
		model.faultpictureurl = faultpictureurl;
	}
	model.faultgrade = sel.alarmgrade;
	model.faulttype = sel.alarmtype;
	model.faultdescription = faultdescription;
	model.faultoccurtime = sel.alarmtime;
	model.jobprocessstate = '901';				// 受理状态
	model.jobreportcompany = jobreportcompany;
	model.jobreportpeople = jobreportpeople;
	model.jobreportphone = jobreportphone;
	model.jobreporttime = jobreporttime;
	model.jobacceptphone = jobacceptphone;
//	console.log("order:",model);
	$.ajax({
		 type : 'post',
		 dataType : 'json',
		 url : 'ywrepairjobinfoAction!insert_Ywrepairjobinfo.do',
		 data : model,
		 success:function(res){
			 if(res == 'success'){					
				 $.showMsg("操作成功！");
				 top.$("#"+windowId).dialog('close');
				 showList();
			 }else{
				 $.showMsg("操作失败！"); 
			 }
		 }	 	
	}) 
}
function sureIgnore(){
	var win = $.getTopWindowById(windowId);
	var hlyy = win.$('#hlyy').val();
//	console.log("忽略原因：",hlyy);
	var selRows = $('#searchGridList').datagrid('getChecked'); 
//	console.log("忽略：",selRows);
	var flag = false;
	selRows.forEach(function(item){
		var alarmdevicetype = item.alarmdevicetype;
		var alarmeventid = item.alarmeventid;
		var alarmdeviceid = item.alarmdeviceid;
		var channelnum;
		if (item.channelnum != null) {
			channelnum = item.channelnum;
		}
		$.ajax({
			 type : 'post',
			 dataType : 'json',
			 url : 'ywalarmeventinfoAction!ignore_Ywalarmeventinfo.do',
			 data : {'processdescription':hlyy, 'alarmdevicetype':alarmdevicetype,'alarmeventid':alarmeventid,
				 	 'alarmdeviceid':alarmdeviceid,'channelnum':channelnum},
			 async : false,
			 success:function(res){
				 		if(res == 'success'){
				 			flag = true;
				 		}else{
				 			flag = false;
				 		}
			 		}			 	 
		})
		if(flag){
			$.showMsg("操作成功！");
			top.$("#"+windowId).dialog('close');
			showList()
		}else{
			$.showMsg("操作失败！");
			top.$("#"+windowId).dialog('close');
		}
	})
}
//新增告警
function insertAlarm (){

	// // 创建窗口
	// if(top.$("#" + detailWindowId + "").length > 0) {
	// 	top.$("#" + detailWindowId + "").html("");
	// }
	// detailWindow = top.$('<div id=' +detailWindowId+'/>');
	// createDetailWindow("detailWindow");
	// setTimeout(function(){
	// 	detailWindow.children('iframe').attr('src',sysUrl+'/yw/homepage/addAlarm.jsp');
	// 	detailWindow.dialog('open');
	// 	//top.editInfo = rows;
	// 	top.framewindow = detailWindow;
	// },100);
	toEdit=false;
	windowId = top.$.createWin({
		title	: 	'新增告警信息',
		width	:  	550,
		height	: 	420,
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			// handler:saveNodeInfo
		}],
		url	:	sysUrl+"/yw/homepage/addAlarm.jsp"
	});


}
//图片展示
function showPicture(){
	$("#searchGridPicDiv").show();
	$("#searchGridListDiv").hide();
	$("#searchGridStaticsDiv").hide();
	displayType = "picture";
	$('#searchGridPic').datagrid({
		toolbar : toolbar,
		bodyCls:'pic-datagrid',
		queryParams:getQueryParams(),
		url : 'ywalarmeventinfoAction!listYwalarmeventinfoByPage.do',
		onLoadSuccess:function(data){
			if(data){
				data.data=data.rows;
				data.totalSize=data.total;
				$('#searchGridPic').datagrid("renderMonitorData",data);
			}
		},
		rownumbers:true,
	});
	
}
//统计展示
function showStatics(){
	$("#searchGridStaticsDiv").show();
	$("#searchGridPicDiv").hide();
	$("#searchGridListDiv").hide();
	displayType = "statics";
	$('#searchGridStatics').datagrid({ toolbar : toolbar});
	var param = getQueryParams();
	param.order = "";
	//折线图 
	showStaticsLine("1");
	//饼状图
	$.ajax({
		url : "ywalarmeventinfoAction!statisticPieChart.do",
		dataType : "JSON",
		type : "POST",
		data : param,
		success : function(res){
			if(res){
				var alarmArr = [];
				var total = 0;
				for(var i in res){
					//console.log(res[i]);
					total += res[i].num;
					alarmArr.push(
							{
								name  : res[i].name,
								value : res[i].num,
								color : colorObj[res[i].alarmtype+""]
							}		
					)
				}
				$("#deviceAnalysisGraphChartCount").text(total);
				var data={"title":"设备故障类型占比分析",
						data : alarmArr,
//						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);
		}
	});
	
}
//统计展示
function showStaticsLine(staticsType){
	var param = getQueryParams();
	param.order = "";
	param.staticsType = staticsType;
	$("#deviceAnalysisGraphChartBoxTime li").removeClass("active");
	$.ajax({
		url : "ywalarmeventinfoAction!alarmStatisticsLine.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 showList(){
	$("#searchGridListDiv").show();
	$("#searchGridPicDiv").hide();
	$("#searchGridStaticsDiv").hide();
	displayType = "list";
	$('#searchGridList').datagrid({
		toolbar : toolbar,
		singleSelect:true,
		rownumbers:true,
		queryParams:getQueryParams(),
		url : 'ywalarmeventinfoAction!listYwalarmeventinfoByPage.do',
		columns : [[
		    {
				field: 'A',
				checkbox:'true',
				width:30
			},
		    {field:'alarmeventid',title:'alarmeventid',hidden:true,width:120, 
				formatter:function showClick(value,record,num){ 
					return "<a  href='javascript:void(0);' class='ahref' onclick='doUpdate("+num+")'>"+value+"</a>";
				}
 			},
			{field:'alarmruleid',title:'告警规则id',hidden:true,width:120},
			{field:'alarmrulename',title:'告警规则名称',hidden:true,width:120},
			{field:'alarmdevicetypename',title:'设备类型',hidden:false,width:100},
			{field:'alarmdevicename',title:'设备名称',hidden:false,width:145},
			{field:'alarmdeviceid',title:'告警设备编号',hidden:true,width:120},
			{field:'channelnum',title:'通道编号',hidden:true,width:120},
			{field:'alarmgradename',title:'告警级别',hidden:false,width:80,
				formatter:function showClick(value,record,num){ 
					var html="";
					var grade=record.alarmgrade;
					var backgroundColor="";
					if(grade==1||grade==2){
						backgroundColor='#ff0000;';
					} else {
						backgroundColor='#ff7a05;';
					}
					html= "<div style='background-color:"+backgroundColor+"width:70px;height:20px;color:white;text-align:center;line-height:20px;'>"+value+"</div>";
					return html;
				}
			},
			{field:'processstatus',title:'处理状态',hidden:false,width:120,
				formatter:function showClick(value,record,num){
					return CommonData.jobprocessstate[value];
				}
			},
			{field:'alarmtime',title:'告警时间',hidden:false,width:140},
			{field:'alarmtypename',title:'告警类型',hidden:true,width:120},
			{field:'alarmsubtypecode',title:'告警子类型',hidden:true,width:120},
			{field:'alarmsubtypename',title:'告警子类型编码名称',hidden:true,width:120},
			{field:'alarmreason',title:'告警描述',hidden:false,width:250},
			{field:'falutdtype',title:'故障描述',hidden:true,width:120},
			{field:'falutdescription',title:'故障描述',hidden:true,width:120},
			{field:'processtime',title:'处理时间',hidden:true,width:120},
			{field:'processaccount',title:'处理人员编号',hidden:true,width:120},
			{field:'processdescription',title:'处理描述',hidden:true,width:120},
			{field:'unalarmtime',title:'销警时间',hidden:true,width:120},
			{field:'completetime',title:'完成处理时间',hidden:true,width:120},
			{field:'completeaccount',title:'完成处理人员编号',hidden:true,width:120},
			{field:'pictureurl',title:'图片url路径',hidden:true,width:120},
			{field:'videourl',title:'视频url路径',hidden:true,width:120},
			{field:'relatetaskbatchnum',title:'处理人员编号',hidden:true,width:120},
			{field:'relatetasknum',title:'处理人员编号',hidden:true,width:120},
			{field:'accountnum',title:'客户编号',hidden:true,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},
			{field:'B',title:'操作',hidden:false,width:120,
				formatter:function(value,record,num){
        			return '<a href="javascript:;" style="background: #67c23a;color:white;padding: 2px,5px;" class="l-btn l-btn-small" onclick="alarmDetail('+num+')"  group="" id=""><span class="l-btn-left"><span class="l-btn-text">详情</span></span></a>';
				}
			}
		]]
	});
}

function alarmDetail(index){
	var rows = $('#searchGridList').datagrid('getRows')[index];
	if(top.$("#" + detailWindowId + "").length > 0) {
		top.$("#" + detailWindowId + "").html("");
	}
	detailWindow = top.$('<div id=' +detailWindowId+'/>');
	createDetailWindow("detailWindow");
	setTimeout(function(){
		detailWindow.children('iframe').attr('src',sysUrl+'/yw/alarmWorkbench/alarmdetail/alarmDetail.jsp');
		detailWindow.dialog('open');
		top.editInfo = rows;
		top.framewindow = detailWindow;
	},100);
}

function createDetailWindow(name){
	detailWindow.append('<iframe frameborder="no" name="'+ name +'" scrolling="no" style="border:none;width:100%;height:100%"></iframe>');
	detailWindow.dialog({
		title:'故障详情',
		width:694,
		closed:true,
		height:510,
		modal:true,
		buttons:[{
			text:$.fn.textbox.defaults.close,
			handler:function(){
				detailWindow.dialog('close');
			}
		}]
	});
}

//删除
function doDelete(){
	var selRows = $('#tableGrid').datagrid('getSelected'); 
	if(!selRows){
		$.showMsg('请先选择记录! ');
		return;
	}
	top.$.dlg.confirm('确认删除?',function(){
		$.ajax({
			type:'post',
			dataType : 'json',
			url:'ywalarmeventinfoAction!delete_Ywalarmeventinfo.do',
			data:{
				alarmeventid	:	selRows.alarmeventid

			},
			success:function(flag){
				if(flag == "success"){
					$.showMsg("操作成功！");
					doSearch();
				}else{
					$.showMsg("操作失败！");
				}
			}
		});
	});
}
//批量删除
function doDelete_batch(){
	var selRows = $('#tableGrid').datagrid('getChecked'); 
	var keyword = [];
	 if(selRows===null){
		$.showMsg('请先选择一行! ');
		 return;
	 }else{
		for(var i=0; i<selRows.length; i++){
			keyword.push(selRows[i].alarmeventid);
		}
		top.$.dlg.confirm('你确认要删除吗?',function(){ 
		    $.ajax({
				 type:'post',
				 dataType : 'json',
				 url:'ywalarmeventinfoAction!batch_delete_Ywalarmeventinfo.do',
				 data:{keyword	:	keyword.join(",")},
				 success:function(flag){
				 	if(!isNull(flag)){
						$.showMsg("操作成功！");
					 	doSearch();
					}else{
						$.showMsg("操作失败！");
					}
				}
			 });
		}); 
	}
}
//查询
function isNull(str){
	if(str==null || str=='' || str==" " || str=="null" || str == undefined){
		return true;
	}else{
		return false;
	}
}
function doSearch(){	
	if(displayType=="list"){
		showList();
	}else if(displayType=="picture"){
		showPicture();
	}else{
		showStatics();
	}
//	$('#tableGrid').datagrid('load',getQueryParams());
}
//增加
function doAdd(){
	toEdit=false;
	windowId = top.$.createWin({
		title	: 	'增加信息',
		width	:  	650,
		height	: 	300,
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:saveNodeInfo
		}],
		url	:	sysUrl+"/yw/ywalarmeventinfo/ywalarmeventinfo_show.jsp"
	 });
}
//修改
function doUpdate(index){
	toEdit=true;
	var selRows = $('#tableGrid').datagrid('getRows')[index];
	windowId = top.$.createWin({
		title	: 	'修改信息',
		width	:  	650,
		height	: 	300,
		data   	:   selRows,
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:saveNodeInfo
		}],
		url	:	sysUrl+"/yw/ywalarmeventinfo/ywalarmeventinfo_show.jsp"
	});
}
//保存
function saveNodeInfo(){
	var win		=	$.getTopWindowById(windowId);
	var jq		=	win.$;
	var model   =   $.getFormValues("childform",windowId);
	//console.log(model);
	if(!win.$('#childform').form('enableValidation').form('validate')){
      return;
	}
	if(toEdit){//修改
		model.XGTJalarmeventid = jq('#alarmeventid').val();

		//model.checkparam = " and xh='"+model.xh+"' ";
		$.ajax({
			type:'post',
			dataType : 'json',
			url:'ywalarmeventinfoAction!update_Ywalarmeventinfo.do',
			data:model,
			success:function(value){
				if(value=="success"){
					$.showMsg("操作成功！");
					top.$("#"+windowId).dialog('close');
					doSearch();
				}else if(value=="same"){
					$.showMsg("已存在！");
				}else{
					$.showMsg("操作失败！");
				}
			}
		});
	}else{
		//model.checkparam = " and xh='"+model.xh+"' ";
		$.ajax({
			type:'post',
			dataType : 'json',
			url:'ywalarmeventinfoAction!insert_Ywalarmeventinfo.do',
			data:model,
			success:function(value){
				if(value=="success"){
					$.showMsg("操作成功！");
					top.$("#"+windowId).dialog('close');
					doSearch();
				}else if(value=="same"){
					$.showMsg("已存在！");
				}else{
					$.showMsg("操作失败！");
				}
			}
		});
	}
}
//打开修改
function doEdit(){
	var selIndex = $('#tableGrid').datagrid('getRowIndex', $("#tableGrid").datagrid('getSelected'))
	if(selIndex==-1){
		$.showMsg('请先选择一行! ');
		 return;
	}else{
		doUpdate(selIndex);
	}		
}
//模板下载
function doTemplate(){
	var baseUrl = $.proPath();
	var downFile = baseUrl+"/down/down.xls";
	window.location.href= downFile;
}
//导入
function doImport(){
	toEdit=false;
	windowId = top.$.createWin({
		 id		:	$.uniqueId(),
		 title	: 	'导入',
		 width	:  	400,
		 height	: 	130,
		 url	:	sysUrl+"/im/xx/ywalarmeventinfo_imp.jsp"
	 });
}
//导出
function doExport(){
	var model = getQueryParams();
	$.ajax({
		type : 'post',
		dataType : 'json',
		data : model,
		url : 'ywalarmeventinfoAction!count_Ywalarmeventinfo.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 = 'ywalarmeventinfoAction!exp_Ywalarmeventinfo.do?downParam='+encodeURIComponent(downParam);
	document.excelForm.submit(); 
}
//选择设备列表
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:chooseDevice
			}],
			url	:	sysUrl+"/yw/alarmWorkbench/alarmWorkbenchDeviceChoose.jsp"
		});
	}
}
//选择设备处理函数
function chooseDevice(){
	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 = "";
	var text = "";
	var deviceType = $("#deviceType").combobox("getValue");
	for(var i=0;i<rows.length;i++){
		if(deviceType!="" && deviceType=="1"){
			result += rows[i].sbbh+"_"+rows[i].tdbh+",";
			text += rows[i].tdmc + ",";
		}else{
			result+=rows[i].machinenum+",";
			text += rows[i].machinename + ",";
		}
	}
	result = result.substring(0,result.length-1)
	text = text.substring(0,text.length-1)
	$('#deviceChoose').combobox('setValue', result);
	$('#deviceChoose').combobox('setText', text);
}
//初始化加载下拉框
function initSelect(){
	//加载下拉框
	$.ajax({
		url:" xtclAction!query_Xtcl_task.do",
		type:"post",
		dataType:"JSON",
		data : {"csdl":"ywAlarmProcessStatus,ywAlarmSource,ywAlarmRuleLevel"},
		success:function(res){
		//	console.log(res);
			if(res && res.length>0){
				var alarmTypeArr = [{"id":"","text":"全部","selected":true}];
				var processStatusArr = [{"id":"","text":"全部","selected":true}];
				var alarmDeviceTypeArr = [{"id":"","text":"全部","selected":true}];
				var alarmLevelArr = [{"id":"","text":"全部","selected":true}];
				for(i in res){
					if(res[i].csdl=="ywAlarmProcessStatus"){
						processStatusArr.push({"id":res[i].csdm,"text":res[i].csmc});
					}else if(res[i].csdl=="ywAlarmSource"){
						alarmDeviceTypeArr.push({"id":res[i].csdm,"text":res[i].csmc});

					}else if(res[i].csdl=="ywAlarmRuleLevel"){
						alarmLevelArr.push({"id":res[i].csdm,"text":res[i].csmc});
					}
				}
				var deviceChooseArr = [ {"id":"","text":"全部","selected":true},
					                     {"id":"1","text":"列表选择"}
				]
				$("#alarmLevel").combobox( "loadData", alarmLevelArr);
				$("#deviceType").combobox(					{
						data: alarmDeviceTypeArr,    // 查询部门下有审批工单权限的人
						textField: "text",
						valueField: "id",
						value: "",
							onChange: function (n, o) {
								if(!isNull(n)) {
									$('#alarmType').combobox('clear');//清空选中项
									$('#alarmType').combobox('loadData', {});//清空option选项
									$('#alarmType').combobox({
										url: 'xtclAction!queryXtcl_alarm.do?startLIKEcsdm=' + n,
										valueField: 'csdm',
										textField: 'csmc'
									});
								}
							}
					});
				$("#deviceChoose").combobox( "loadData", deviceChooseArr);
				$("#processStatus").combobox( "loadData", processStatusArr);

				    
			}
		}
	});
}
$.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
         }
         if(g.total<1){
        	 c.html('<div style="text-align:center;margin:80px 0 0 0;font-size:12px;" class="img-box">没有查询到符合条件的记录!</div>');
        	 return ;
         }
         var f = 0,
         l = [],
         e,
         d,
         j = this;
         for (; (g.data[f]); f++) {
        	 var row = g.data[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>")
             var proName = window.location.pathname.split("/")[1];
             var sysUrl = "http://"+window.location.host+"/"+proName;
             var picProxyGetUrl = sysUrl+"/sourceProxy?fileType=picUrlProxy&picUrl="+g.data[f].pictureurl;
    	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:block;">'+processstatusTransfor(g.data[f].processstatus)+'</div>' 
    			+ '<img onclick="detailVideoQuality(' + f + ');"  src="' + picProxyGetUrl + '" onerror="javascript:$.loadErrorPic(this);" style="width:218px;"/><div style="width:218px;">' + "<p>设备名称:&nbsp;" + (g.data[f].alarmdevicename || "无") + "</p>" + "<p style='line-height:20px;'>告警时间:&nbsp;" + (g.data[f].alarmtime || "") + "</p>" + "<p style='line-height:20px;'>告警类型:&nbsp;<span " + g.data[f].oprStatusColor + ">" + (g.data[f].alarmtypename || "") + "</span></p></div></div>")
         }
         c.html('<div class="img-box">' + l.join("") + "</div>")
     }
});

function processstatusTransfor(status) {
	if (status == '900') {
		return '待处理';
	} else if (status == '901' || status == '902' || status == '904' || status == '905' || status == '906' || status == '907' || status == '908' || status == '909' || status == '910' || status == '913') {
		return '处理中';
	} else if (status == '903' || status == '912' || status == '911' || status == '914') {
		return '已处理';
	}
}

function detailVideoQuality(index){
	var rows = $('#searchGridPic').datagrid('getRows')[index];
	if(top.$("#" + detailWindowId + "").length > 0) {
		top.$("#" + detailWindowId + "").html("");
	}
	detailWindow = top.$('<div id=' +detailWindowId+'/>');
	createDetailWindow("detailWindow");
	setTimeout(function(){
		detailWindow.children('iframe').attr('src',sysUrl+'/yw/alarmWorkbench/alarmdetail/alarmDetail.jsp');
		detailWindow.dialog('open');
		top.editInfo = rows;
		top.framewindow = detailWindow;
	},100);
}
var colorObj = {
		"1" : "#fe0000",
		"2" : "#e16616",
		"3" : "#754599",
		"4" : "#84ccc9"
}