var windowId,proName = window.location.pathname.split("/")[1],sysUrl = "http://"+window.location.host+"/"+proName,toEdit;
var num=0;
$(function(){
	initDefault();	
});
//默认
function initDefault(){	
	
	initGrid();
}
//查询条件
function getQueryParams(){
	var sParam = {};
	
	sParam.LIKEalarmrulename = $('#LIKEalarmrulename').textbox("getValue");
	
	return sParam;
}
//加载列表
function initGrid(){	
	var toolbar = [
	{
    	text	:	'查询',
        iconCls	:	'icon-search',
        handler	:	doSearch
    },{
        text	:	'增加',
        iconCls	:	'icon-add',
        handler	:	doAdd
    },{
        text	:	'修改',
        iconCls	:	'icon-cut',
        handler	:	doEdit
    },{
        text	:	'删除',
        iconCls	:	'icon-delete',
        handler	:	doDelete_batch
    },{
        text	:	'启用',
        iconCls	:	'icon-start',
        handler	:	switchOpen
    },{
        text	:	'停止',
        iconCls	:	'icon-end',
        handler	:	switchClose
    }/*,{
        text	:	'告警时间级别',
//      iconCls	:	'icon-start',
        handler	:	alarmTime
    }*/,{
    	text	:	'告警联动',
//       iconCls	:	'icon-end',
    	handler	:	alarmMsg
    }];
	$('#tableGrid').datagrid({
		toolbar : toolbar,
		singleSelect:true,
		rownumbers:true,
		queryParams:getQueryParams(),
		url : 'ywalarmruleinfoAction!listYwalarmruleinfoByPage.do',
		columns : [[
		    {
				field: 'A',
				checkbox:'true',
				width:30
			},
		    {field:'alarmruleid',title:'alarmruleid',hidden:true,width:120, 
				formatter:function showClick(value,record,num){ 
					return "<a  href='javascript:void(0);' class='ahref' onclick='doUpdate("+num+")'>"+value+"</a>";
				}
 			},
			{field:'alarmrulename',title:'告警规则名称',hidden:false,width:120},
			{field:'isenablemc',title:'是否启用',hidden:false,width:80},
			{field:'alarmsourcemc',title:'告警来源',hidden:false,width:120},
			{field:'alarmtype',title:'告警类型',hidden:false,width:220,
				formatter:function showClick(value,record,num){ 
					var alarmTypeMc = '';
//					console.log("alarmTypeMc: ",record,value);
					var alarmSource = record.alarmsource;
					var types = value.toString().split(",");			
					var len = types.length;
					var typeMc = "";
					for(var i=0; i<len; i++){
						var type = types[i];
						type = getAlarmtypeMc(alarmSource,type);
						typeMc += type+",";			
					}							
					return typeMc.substr(0,typeMc.length-1);
				}
			},
			{field:'alarmgrademc',title:'告警等级',hidden:false,width:80},
			{field:'alarmtriggermc',title:'告警时触发',hidden:false,width:80},
			{field:'alarmmaxcount',title:'最大告警次数',hidden:true,width:90},
			{field:'autounalarmtime',title:'自动消警时间间隔',hidden:true,width:120},						
			{field:'remarks',title:'备注',hidden:false,width:150},		
		]],
		
		onClickRow:function(index,row){
			num=index;
			setchecked();
		},
		onLoadSuccess:function(){
			$("#tableGrid").datagrid("selectRow",num);
			setchecked();			
		}
	});
}

function getAlarmtypeMc(alarmSource, type){
	if(alarmSource == '1'){					// 监控告警
		if(type=='2'){
			type = "网络异常"
		}else if(type=='3'){
			type = "设备不在线"
		}else if(type=='4'){
			type = "视频抽帧异常"
		}else if(type=='5'){
			type = "视频质量诊断异常"
		}else if(type=='6'){
			type = "录像异常"
		}
	}else if(alarmSource == '2'){			// 服务器告警
		if(type=='2'){
			type = "主机不在线或程序异常"
		}else if(type=='3'){
			type = "CPU异常"
		}else if(type=='4'){
			type = "内存异常"
		}else if(type=='5'){
			type = "硬盘异常"
		}else if(type=='6'){
			type = "超时未上报"
		}
	}else if(alarmSource == '3'){			// 应用系统告警
		if(type=='1'){
			type='应用不在线';
		}else if(type=='2'){
			type='应用异常';
		}
	}else if(alarmSource == '4'){			// 存储告警
		if(type=='1'){
			type='存储无法连接';
		}else if(type=='2'){
			type='存储上水位报警';
		}
	}
	/*if(alarmSource == '1'){					// 监控告警
		if(type=='101'){
			type = "网络异常"
		}else if(type=='102'){
			type = "设备不在线"
		}else if(type=='104'){
			type = "视频抽帧异常"
		}else if(type=='105'){
			type = "视频质量诊断告警"
		}else if(type=='107'){
			type = "录像异常"
		}
	}else if(alarmSource == '2'){			// 服务器告警
		if(type=='201'){
			type = "主机不在线或程序异常"
		}else if(type=='202'){
			type = "CPU异常"
		}else if(type=='203'){
			type = "内存异常"
		}else if(type=='204'){
			type = "硬盘异常"
		}
	}else if(alarmSource == '3'){			// 应用系统告警
		if(type=='1'){
			type='应用不在线';
		}else if(type=='2'){
			type='应用异常';
		}
	}else if(alarmSource == '4'){			// 存储告警
		if(type=='1'){
			type='存储无法连接';
		}else if(type=='2'){
			type='存储上水位报警';
		}
	}*/
	return type;
}

function setchecked(){
	var selRows = $('#tableGrid').datagrid('getSelected');
	if(selRows){
		var alarmruleid = selRows.alarmruleid;
		var alarmtype = selRows.alarmtype;		
		var alarmsource = selRows.alarmsource;
		$("#alarmdeviceInfo").prop("src",'../../alarmtaskmanage/alarmruleinfodevice/ywalarmrulefordevice.jsp?alarmruleid='+alarmruleid+"&alarmtype="+alarmtype+"&alarmsource="+alarmsource);
	}
	
}

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

			},
			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].alarmruleid);
		}
		top.$.dlg.confirm('你确认要删除吗?',function(){ 
		    $.ajax({
				 type:'post',
				 dataType : 'json',
				 url:'ywalarmruleinfoAction!batch_delete_Ywalarmruleinfo.do',
				 data:{keyword	:	keyword.join(",")},
				 success:function(flag){
				 	if(flag=="success"){
						$.showMsg("操作成功！");
					 	doSearch();
					}else{
						$.showMsg("操作失败！");
					}
				}
			 });
		}); 
	}
}
//查询
function doSearch(){	
	$('#tableGrid').datagrid('load',getQueryParams());
}
//增加
function doAdd(){
	toEdit=false;
	windowId = top.$.createWin({
		title	: 	'增加信息',
		width	:  	650,
		height	: 	400,
		onClose:function(){
			var win		=	$.getTopWindowById(windowId);
			win.unloadWindow();
		},
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:saveNodeInfo
		}],
		url	:	sysUrl+"/yw/alarmtaskmanage/alarmrule/ywalarmruleinfo_show.jsp"
	 });			
}
//修改
function doUpdate(index){
	toEdit=true;
	var selRows = $('#tableGrid').datagrid('getRows')[index];
	windowId = top.$.createWin({
		title	: 	'修改信息',
		width	:  	650,
		height	: 	400,
		data   	:   selRows,
		onClose:function(){
			var win		=	$.getTopWindowById(windowId);
			win.unloadWindow();
		},
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:saveNodeInfo
		}],
		url	:	sysUrl+"/yw/alarmtaskmanage/alarmrule/ywalarmruleinfo_show.jsp"
	});
}
//保存
function saveNodeInfo(){
	var win		=	$.getTopWindowById(windowId);
	var jq		=	win.$;
	var model   =   $.getFormValues("childform",windowId);
//	console.log("增加",model);
	 var alarmtypes = jq('#alarmtype').combobox('getValues');
	 var alarmtype = alarmtypes.join(',')
	 model.alarmtype = alarmtype;
//	 console.log("类型：",alarmtype);
	if(!win.$('#childform').form('enableValidation').form('validate')){
      return;
	}
	model.remarks = jq('#remarks').val();
	if(toEdit){//修改
		model.XGTJalarmruleid = jq('#alarmruleid').val();

		//model.checkparam = " and xh='"+model.xh+"' ";
		$.ajax({
			type:'post',
			dataType : 'json',
			url:'ywalarmruleinfoAction!update_Ywalarmruleinfo.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:'ywalarmruleinfoAction!insert_Ywalarmruleinfo.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'))
	var selRows = $('#tableGrid').datagrid('getChecked'); 
	if(selRows.length > 1){
		$.showMsg('请先选择一行! ');
		 return;
	}
	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,
		onClose:function(){
			var win		=	$.getTopWindowById(windowId);
			win.unloadWindow();
		},
		 url	:	sysUrl+"/im/xx/ywalarmruleinfo_imp.jsp"
	 });
}
//导出
function doExport(){
	var model = getQueryParams();
	$.ajax({
		type : 'post',
		dataType : 'json',
		data : model,
		url : 'ywalarmruleinfoAction!count_Ywalarmruleinfo.do',
		success : function(value) {
			if(!$.isNull(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 model = getQueryParams();
	var downParam = "";
	document.excelForm.action = 'ywalarmruleinfoAction!exp_Ywalarmruleinfo.do?'+downParam;
	document.excelForm.submit(); 
}

function switchOpen(){
	var selRows = $('#tableGrid').datagrid('getChecked');
	var ids = '';
	if(selRows===null || selRows.length<1){
		$.showMsg('请先选择一行! ');
		return;
	}else{
		selRows.forEach(function(item){
			ids += item.alarmruleid+',';
		})
	    $.ajax({
			 type:'post',
			 dataType : 'json',
			 url:'ywalarmruleinfoAction!edit_Ywalarmruleinfo.do',
			 data:{'ids':ids,'isenable':1},
			 success:function(res){
			 	if(res=="success"){
					$.showMsg("操作成功！");
				 	doSearch();
				}else{
					$.showMsg("操作失败！");
				}
			}
		 });
	}
}
function switchClose(){
	var selRows = $('#tableGrid').datagrid('getChecked');
	var ids = '';
	if(selRows===null || selRows.length<1){
		$.showMsg('请先选择一行! ');
		return;
	}else{
		selRows.forEach(function(item){
			ids += item.alarmruleid+',';
		})
	    $.ajax({
			 type:'post',
			 dataType : 'json',
			 url:'ywalarmruleinfoAction!edit_Ywalarmruleinfo.do',
			 data:{'ids':ids,'isenable':0},
			 success:function(res){
			 	if(res=="success"){
					$.showMsg("操作成功！");
				 	doSearch();
				}else{
					$.showMsg("操作失败！");
				}
			}
		 });
	}
}

function alarmTime(){
	var selRows = $('#tableGrid').datagrid('getSelected'); 
	console.log("alarmTime：",selRows);
	var alarmruleid = selRows.alarmruleid;
	windowId = top.$.createWin({
		title	: 	'增加信息',
		width	:  	600,
		height	: 	360,
		onClose:function(){
			var win		=	$.getTopWindowById(windowId);
			win.unloadWindow();
		},
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:saveTime
		}],
		url	:	sysUrl+"/yw/alarmtaskmanage/alarmrule/alarmTime.jsp?alarmruleid="+alarmruleid
	 });	
}

function saveTime(){
	var win		=	$.getTopWindowById(windowId);
	var params = win.SetAlarmLevel.getValueGroup();
	
	$.ajax({
		type : 'post',
		dataType : 'json',
		url : 'ywalarmrulefortimeAction!batch_insert.do',
		data : JSON.stringify(params),
		success : function(res){
			console.log(res,"===",windowId);
			if(res=="success"){
				$.showMsg("操作成功！");
				top.$("#"+windowId).dialog('close');
			}else{
				$.showMsg("操作失败！");
			}
		}
	})	
}

function alarmMsg(){
	var selRows = $('#tableGrid').datagrid('getSelected'); 
	console.log("alarmTime：",selRows);
	var alarmruleid = selRows.alarmruleid;
	windowId = top.$.createWin({
		title	: 	'短信联动',
		width	:  	760,
		height	: 	420,
		onClose:function(){
			var win		=	$.getTopWindowById(windowId);
			win.unloadWindow();
		},
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:savePhoneMsg
		}],
//		url	:	sysUrl+"/yw/alarmtaskmanage/alarmlink/alarmlink.jsp?alarmruleid="+alarmruleid
		url	:	sysUrl+"/yw/alarmtaskmanage/alarmlink/ywalarmrulelinksms_show.jsp?alarmruleid="+alarmruleid
	 });	
}
function savePhoneMsg(){
	var win		=	$.getTopWindowById(windowId);	
	var selRows = $('#tableGrid').datagrid('getSelected'); 
	var msg = win.$('#smscontent').val();
	var phonenum = win.$('#phonenum').textbox('getValue');
	var alarmruleid = selRows.alarmruleid;
	
	$.ajax({
		type : 'post',
		dataType : 'json',
		url : 'ywalarmrulelinksmsAction!insert_Ywalarmrulelinksms.do',
		data : {'alarmruleid':alarmruleid, 'phonenum':phonenum, 'smscontent':msg},
		success : function(res){
			if(res=="success"){
				$.showMsg("操作成功！");
				top.$("#"+windowId).dialog('close');
			}else{
				$.showMsg("操作失败！");
			}
		}
	})
	
	
	
}
