var cwindowId,proName = window.location.pathname.split("/")[1],sysUrl = "http://"+window.location.host+"/"+proName,toEdit;
var winId	= $.getUrlParam("winId");
var datas = top.editInfo;

var videoblock;
var recordblock;
var videodata={videonum:datas.alarmdeviceid,channelnum:datas.channelnum,channelname:datas.alarmdevicename};
$(function(){
	// 根据设备类型设置展示效果
	if (datas.alarmdevicetype == "2") {
		$("#alarm-tab-info").show();
		$("#btninfo").show();
		$("#btnpic").hide();
		$("#alarm-tab").hide();
	} else {
		$("#alarm-tab-info").hide();
		$("#btninfo").hide();
		$("#btnpic").show();
		$("#alarm-tab").show();
	}
	initGetData();
	loadDetail();
	initBlock();
	initRecordBlock();
	initAlarmTab();
//	initAlarmInfo();
//	initHistoryContent();
});

// 根据选择数据加载信息
function loadDetail() {
	$("#deviceId").text(datas.alarmdevicename);
	$("#deviceType").text(datas.alarmdevicetypename);
	$("#time").text(datas.alarmtime);
	$("#unit").text(datas.xzmc);
	$("#deviceFault").text(datas.alarmreason);
	$("#deviceStatus").text(CommonData.jobprocessstate[datas.processstatus]);

	$("#deviceIdInfo").text(datas.alarmdevicename);
	$("#deviceTypeInfo").text(datas.alarmdevicetypename);
	$("#timeInfo").text(datas.alarmtime);
	$("#unitInfo").text(datas.xzmc);
	$("#deviceFaultInfo").text(datas.alarmreason);
	$("#deviceStatusInfo").text(CommonData.jobprocessstate[datas.processstatus]);
	// 加载图片
	var proName = window.location.pathname.split("/")[1];
	var sysUrl = "http://"+window.location.host+"/"+proName;
	var picProxyGetUrl = sysUrl+"/sourceProxy?fileType=picUrlProxy&picUrl="+datas.pictureurl;
	$("#picture img").attr("src",picProxyGetUrl);
	if (datas.alarmdevicetype == "2") {
		loadMachinecurrentstate(datas.alarmdeviceid);
	}
}
function formatter1(date){
	if (!date){return '';}
	return $.fn.datebox.defaults.formatter.call(this, date);
}
function parser1(s){
	if (!s){return null;}
	return $.fn.datebox.defaults.parser.call(this, s);
}
function getQueryParams(){
	var sParam = {};
//	alert(datas);
	if (datas.alarmdevicetype == 1) {
		sParam.alarmdeviceid = datas.alarmdeviceid;
		sParam.channelnum = datas.channelnum;
	} else {
		sParam.alarmdeviceid = datas.alarmdeviceid;
	}

	sParam.order = " ORDER BY a.alarmtime DESC";
	return sParam;
}

// 初始化根据alarmdeviceid获取数据
function initGetData() {
	$.ajax({
		type:'post',
		dataType : 'json',
		url : 'ywalarmeventinfoAction!query_YwalarmeventinfoDetail.do',
		data:getQueryParams(),
		success:function(resultData){
			//console.log(resultData);
			// 填充列表数据
			for(var i=0; i < resultData.length; i++) {
				var tr="<tr><td>" + (i + 1) + "</td><td>" + (resultData[i].alarmgradename == null ? "" : resultData[i].alarmgradename) + "</td><td>" + CommonData.jobprocessstate[(resultData[i].processstatus == null ? "" : resultData[i].processstatus)] + "</td><td>" + resultData[i].alarmtime + "</td><td id='alarmreasonTip' title='"+ (resultData[i].alarmreason == null ? "" : resultData[i].alarmreason) +"'  class='easyui-tooltip' ><div>"+ (resultData[i].alarmreason == null ? "" : resultData[i].alarmreason) +"</div></td></tr>";
				$("#alarmHistoryContent").append(tr);
			}
		}
	});
}

// 忽略告警
function ignoreAlarm() {
//	alert("忽略告警");
//	var selRows = $('#showAlarmList').datagrid('getChecked'); 
//	console.log("忽略：",selRows);
//	if(selRows===null || selRows.length < 1){
//		$.showMsg('请先选择一行! ');
//		 return;
//	}else{		
//		
//	}
	cwindowId = top.$.createWin({
		title	: 	'忽略告警',
		width	:  	450,
		height	: 	200,
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:sureIgnore
		}],
		url	:	sysUrl+"/yw/homepage/ignorecase.jsp"
	 });
}

function sureIgnore(){
	var win = $.getTopWindowById(cwindowId);
	var hlyy = win.$('#hlyy').val();
//	console.log("忽略原因：",hlyy);
	var selRows = datas; 
//	console.log("忽略：",selRows);
	var flag = false;
	var alarmdevicetype = selRows.alarmdevicetype;
	var alarmeventid = selRows.alarmeventid;
	var alarmdeviceid = selRows.alarmdeviceid;
	var channelnum;
	if (selRows.channelnum != null) {
		var channelnum = selRows.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.$("#"+cwindowId).dialog('close');
		top.framewindow.dialog('close');
		var pro=top.$("iframe[src='"+ top.sysUrl +"/yw/homepage/homepage.jsp']");
		pro[0].contentWindow.showAlarmList();
	}else{
		$.showMsg("操作失败！");
		top.$("#"+cwindowId).dialog('close');
	}
}

// 工单上报
function reportOrder() {
//	alert("工单上报");
//	var selRows = $('#showAlarmList').datagrid('getChecked'); 
//	console.log("忽略：",selRows);
//	if(selRows===null || selRows.length != 1){
//		$.showMsg('请先选择一行! ');
//		 return;
//	}
//	var selectRow = $('#showAlarmList').datagrid('getSelected');  
	cwindowId = top.$.createWin({
		title	: 	'工单上报',
		width	:  	1000,
		height	: 	600,
		buttons:  [{
			text:$.fn.textbox.defaults.ok,
			handler:saveOrder
		}],
		data  :  datas,
//		url	:	sysUrl+"/yw/orders/ywrepairjobinfo/ywrepairjobinfo_show.jsp"
		url : sysUrl + "/yw/repairmanage/ywworkorder/ywreportorder.jsp"
	 });
	// 关闭窗口
	top.framewindow.dialog('close');
}

function saveOrder(){
	var win		=	$.getTopWindowById(cwindowId);
	var jq		=	win.$;
	var model   =   $.getFormValues("order",cwindowId);		// 得到 工单接收人和单位
	
	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').val();			// 接收人联系方式
	var faultdescription = jq('#faultdescription').val();		// 故障描述
	
	var sel = datas;

	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.$("#"+cwindowId).dialog('close');
				 var pro=top.$("iframe[src='"+ top.sysUrl +"/yw/homepage/homepage.jsp']");
				 pro[0].contentWindow.showAlarmList();
			 }else{
				 $.showMsg("操作失败！"); 
			 }
		 }	 	
	}) 
}

function initAlarmTab(){
	$(window).on("focus",function(){
		(window !== top.WebRtcServer.reqPage) && top.WebRtcServer.setReqPage(window);
	});
	$('#alarm-tab').tabs({
		onSelect: function(title,index){
			if(index==0){
				$("#recordBtn").hide();
			}else if(index==2){
				$("#searchDate").datebox("setValue",$.getTodayStart(0,"00:00:00"));
				$("#recordBtn").show();
				unloadWindow();
				var myDate = new Date();
				var currDate = myDate.getFullYear()+"-"+(myDate.getMonth()+1)+"-"+myDate.getDate();
				var startTime = currDate+" 00:00:00";
				var endTime = currDate+" 23:59:59";
				ProgressBar.init({
					startTime:new Date(startTime),
					endTime:new Date(endTime),
					totalSecond:86400
				});
				webrtc_startRecord(datas.alarmdeviceid,datas.channelnum,datas.alarmdevicename,startTime,endTime);
			}else if(index==1){
				$("#recordBtn").hide();
				unloadWindow();
				webrtc_startVideo(datas.alarmdeviceid,datas.channelnum,datas.alarmdevicename);
			}
		}
	});
}
function initAlarmInfo(){
/*	$.ajax({
		type:'post',
		dataType : 'json',
		url : 'ywalarmeventinfoAction!query_YwalarmeventinfoDetail.do',
		data:{
		},
		success:function(flag){
			if(flag == "success"){
				$.showMsg("操作成功！");
				doSearch();
			}else{
				$.showMsg("操作失败！");
			}
		}
	});*/
	$("#picture img").attr("src","http://localhost:8080/impyw/frame/assets/images/nopic.png");
	$("#deviceId").html("滨文路相机");
	$("#deviceType").html("前端设备");
	$("#time").html("2015-01-01 15:00:00");
	$("#unit").html("服务区1");
	$("#deviceFault").html("视频遮挡");
	$("#deviceStatus").html("未派发");
}
function initHistoryContent(){
	var tr="<tr><td>序号</td><td>告警时间</td><td>告警等级</td><td>故障类型</td><td>工单状态</td><td>操作</td></tr>";
	for(var i=0;i<10;i++){
		$("#alarmHistoryContent").append(tr);
	}
}

function searchVideo(){
	unloadWindow();
	var serdate = $('#searchDate').val();
	var serdateArr=serdate.split("-");
	serdateArr[1]=serdateArr[1].substring(1,2);
	serdate=serdateArr.join("-");
	var startTime = serdate+" 00:00:00";
	var endTime = serdate+" 23:59:59";
	ProgressBar.init({
		startTime:new Date(startTime),
		endTime:new Date(endTime),
		totalSecond:86400
	});
	webrtc_startRecord(datas.alarmdeviceid,datas.channelnum,datas.alarmdevicename,startTime,endTime);
}

// 加载服务器当前状态
function loadMachinecurrentstate(currentstateid) {
	$.ajax({
		type : 'post',
		dataType : 'json',
		url : 'ywmachinecurrentstateAction!get_Ywmachinecurrentstate.do',
		data : {'currentstateid':currentstateid, 'tableparam':' limit 1'},
		success : function(res){
			//console.log("返回结果：",res)
			//cpu状态
			var cpuhtml='';
			var cpuusage = res.cpuusage;
			var cpuzt = res.cpustatus;
			if(cpuusage == null || cpuusage == ''){
				if(cpuzt == "1"){
					cpuzt = "正常";
				}else if(cputzt == '0'){
					cpuzt = "异常";
				}
			}else{
				cpuusage = cpuusage.indexOf('%')>0 ? cpuusage.replace("%",""):cpuusage;
				if(cpuzt == "1"){
					cpuzt = "正常";
					cpuhtml = '<div class="progress" style="width:140px"><div class="progress-value"  style="background-color:red;width: ' + (cpuusage || 0) + 'px;"><div class="progress-text"  style="border:1px solid red;">' + (cpuusage+"%" || "") + "</div></div></div>"
				}else if(cpuzt == '0'){
					cpuzt = "异常";
					cpuhtml = $.gridProgressBar(cpuusage+"%",100*cpuusage/100.00);
				}
			}					
			$('#cpuzt').html(cpuzt);
			$('#cpu').append(cpuhtml);
			cpuGrap(cpuusage)
			$("#cpuTitle").html(cpuzt);
			if(cpuzt=='正常'){
				$("#cpuTitle").parent().css("color","#000");
			}

			// 内存状态
			var nchtml = '';
			var memorytotal = res.memorytotal;
			var memoryusage = res.memoryusage;
			var nczt = res.memorystate;
			if(memorytotal == null || memorytotal == ''){
				if(memoryusage != null && memoryusage != ''){
					memoryusage = memoryusage.indexOf('%')>0 ? memoryusage.replace("%",""):memoryusage;
					if(nczt == 0){
						nczt = '异常';
						nchtml = '<div class="progress" style="width:140px">'+
						'<div class="progress-value"  style="border:1px solid red;background-color:red;width: ' + (memoryusage || 0) + 'px;">'+
						'<div class="progress-text"  style="border:1px solid red;">' + (memoryusage+"%" || "") + "</div>" +
						"</div>" + 
						"</div>";
					}else if(nczt == 1){
						nczt = '正常';
						nchtml = '<div class="progress" style="width:140px">'+
						'<div class="progress-value"  style="width: ' + (memoryusage || 0) + 'px;">'+
						'<div class="progress-text">' + (memoryusage+"%" || "") + "</div>" +
						"</div>" +
						"</div>";
					}
				}
			}else{
				var ncrl = res.memorytotal.toUpperCase();
				var dw = "G";
				if(ncrl.indexOf('G') > 0){
					ncrl = ncrl.replace("G","");
					dw = "G";
				}else if(ncrl.indexOf('M') > 0){
					ncrl = ncrl.replace("M","");
					dw = "M";
				}else if(ncrl.indexOf('KB') > 0){
					ncrl = ncrl.replace("KB","");
					dw = "KB";
				}
				var sync = "";
				if(memoryusage != null && memoryusage != ''){
					memoryusage = memoryusage.indexOf('%')>0 ? memoryusage.replace("%",""):memoryusage;
					sync = (ncrl * memoryusage)/100;
					sync = sync.toFixed(2);
					if(nczt == 0){
						nczt = '异常';
						nchtml = '<div class="progress" style="width:140px">'+
						'<div class="progress-value"  style="background-color:red;width: ' + (memoryusage || 0) + 'px;">'+
						'<div class="progress-text"  style="border:1px solid red;">' + (memoryusage+"%" || "") + "</div>" +
						"</div>" + 
						"<div style='position: relative;left: 105px; top: -18px;'>"+sync+dw+" / "+ncrl+dw+"(总)</div>"+
						"</div>";
					}else if(nczt == 1){
						nczt = '正常';
						nchtml = '<div class="progress" style="width:140px">'+
						'<div class="progress-value"  style="width: ' + (memoryusage || 0) + 'px;">'+
						'<div class="progress-text">' + (memoryusage+"%" || "") + "</div>" +
						"</div>" +
						"<div style='position: relative;left: 105px; top: -18px;'>"+sync+dw+" / "+ncrl+dw+"(总)</div>"+
						"</div>";
					}
				}
			}
			var radio=sync+dw+" / "+ncrl+dw;
			$('#nczt').html(nczt);
			$('#nc').append(nchtml);
			memoryGrap(memoryusage,radio);
			$("#memoryTitle").html(nczt);
			if(nczt== '正常'){
				$("#memoryTitle").parent().css("color","#000");
			}

			// 硬盘状态				
			var yphtml = '';
			var harddisktotal = res.harddisktotal;
			var harddiskusage = res.harddiskusage;
			var ypzt = res.harddiskstate;
			if(harddisktotal == null || harddisktotal == ''){
				if(harddiskusage != null && harddiskusage != ''){
					harddiskusage = harddiskusage.indexOf('%')>0 ? harddiskusage.replace("%",""):harddiskusage;
					if(ypzt == 0){
						ypzt = '异常';
						yphtml = '<div class="progress" style="width:140px">'+
						'<div class="progress-value"  style="background-color:red;width: ' + (harddiskusage || 0) + 'px;">'+
						'<div class="progress-text"  style="border:1px solid red;">' + (harddiskusage+"%" || "") + "</div>" +
						"</div>" + 
						"</div>";
					}else if(ypzt == 1){
						ypzt = '正常';
						yphtml = '<div class="progress" style="width:140px">'+
						'<div class="progress-value"  style="width: ' + (harddiskusage || 0) + 'px;">'+
						'<div class="progress-text">' + (harddiskusage+"%" || "") + "</div>" +
						"</div>" +
						"</div>";
					}
				}
			}else{
				var yprl = res.harddisktotal.toUpperCase();
				var dw = "G";
				if(yprl.indexOf('G') > 0){
					yprl = yprl.replace("G","");
					dw = "G";
				}else if(yprl.indexOf('M') > 0){
					yprl = yprl.replace("M","");
					dw = "M";
				}else if(yprl.indexOf('KB') > 0){
					yprl = yprl.replace("KB","");
					dw = "KB";
				}
				var sy = "";
				if(harddiskusage != null && harddiskusage != ''){
					harddiskusage = harddiskusage.indexOf('%')>0 ? harddiskusage.replace("%",""):harddiskusage;
					sy = (yprl * harddiskusage)/100;
					sy = sy.toFixed(2);
					if(ypzt == 0){
						ypzt = '异常';
						yphtml = '<div class="progress" style="width:140px">'+
						'<div class="progress-value"  style="background-color:red;width: ' + (harddiskusage || 0) + 'px;">'+
						'<div class="progress-text"  style="border:1px solid red;">' + (harddiskusage+"%" || "") + "</div>" +
						"</div>" + 
						"<div style='position: relative;left: 105px; top: -18px;'>"+sy+dw+" / "+yprl+dw+"(总)</div>"+
						"</div>";
					}else if(ypzt == 1){
						ypzt = '正常';
						yphtml = '<div class="progress" style="width:140px">'+
						'<div class="progress-value"  style="width: ' + (harddiskusage || 0) + 'px;">'+
						'<div class="progress-text">' + (harddiskusage+"%" || "") + "</div>" +
						"</div>" +
						"<div style='position: relative;left: 105px; top: -18px;'>"+sy+dw+" / "+yprl+dw+"(总)</div>"+
						"</div>";
					}
				}
			}
			var radio=sy+dw+" / "+yprl+dw;
			$('#ypzt').html(ypzt);
			$('#yp').append(yphtml);
			harddiskGrap(harddiskusage,radio);
			$("#diskTitle").html(ypzt);
			if(ypzt=='正常'){
				$("#diskTitle").parent().css("color","#000");
			}
		}		
	});
}

function harddiskGrap(data,radio){
	var myChart = echarts.init(document.getElementById('diskGrap'));
	var color="#1fba44";
	if(data>50){
		color="#d51717";
	}
	option = {
	    series: [{
	    	name:'访问来源',
	    	type:'pie',
	    	radius: ['50%', '70%'],
	    	label: {
	    		normal: {
	    			show: false,
	    			position: 'left'
	    		},
	    		emphasis: {
	    			show: false,
	    			textStyle: {
	    				fontSize: '10',
	    				fontWeight: 'bold'
	    			}
	    		}
	    	},
	    	labelLine: {
	    		normal: {show: true}
	    	},
	    	data:[
	    		{value:data, name:data+'%\n'+radio,label:{show:true,fontSize:10,color:color,position:"center",align:"center",verticalAlign :"bottom"},itemStyle:{color:color}},
	    		{value:100-data, name:'',itemStyle:{color:'#bfbfbf'}},
	    	]
	    }]
	};
	myChart.setOption(option, true);
}

function memoryGrap(data,radio){
	var myChart = echarts.init(document.getElementById('memoryGrap'));
	var color="#1fba44";
	if(data>50){
		color="#d51717";
	}
	option = {
		series: [{
			name:'访问来源',
			type:'pie',
			radius: ['50%', '70%'],
			label: {
				normal: {
					show: false,
					position: 'left'
				},
				emphasis: {
					show: false,
					textStyle: {fontWeight: 'bold'}
				}
			},
			labelLine: {
				normal: {show: true}
			},
			data:[
				{value:data, name:data+'%\n'+radio,label:{show:true,color:color,position:"center",align:"center",verticalAlign :"bottom"},itemStyle:{color:color}},
				{value:100-data, name:'',itemStyle:{color:'#bfbfbf'}},
			]
		}]
	};
	myChart.setOption(option, true);
}

function cpuGrap(data){
	var myChart = echarts.init(document.getElementById('cpuGrap'));
	var color="#1fba44";
	if(data>50){
		color="#d51717";
	}
	option = {
		tooltip : {
			formatter: "{a} <br/>{b} : {c}%"
		},
		toolbox: {
			feature: {}
		},
		series: [{
			name: '业务指标',
			radius:'80%',
			type: 'gauge',
			splitNumber:0,
			axisTick:{show:false},
			splitLine:{show:false},
			axisLine:{
				lineStyle:{
					width:3,
					color:[[0.5,{
						type: 'linear',
						colorStops: [{
							offset: 0, color: '#4db51d' // 0% 处的颜色
						}, {
							offset: 1, color: '#dcd018' // 100% 处的颜色
						},],
						globalCoord: false // 缺省为 false
					}],[1,{
						type: 'linear',
						colorStops: [{
							offset: 0, color: '#dcd018' // 0% 处的颜色
						}, {
							offset: 1, color: '#cd2a0e' // 100% 处的颜色
						},],
					}]]
				}
			},
			detail:{show:false},
			axisLabel:{show:false},
			startAngle:220,
			pointer:{show:false},
			data: [{value: data, name: ''}]
		},
		{
			name: 'cpu使用率',
			type: 'gauge',
			splitNumber:2,
			radius:"70%",
			axisLine:{
				show:true,
				lineStyle:{
					color:[[0.5,{
						type: 'linear',
						colorStops: [{
							offset: 0, color: '#4db51d' // 0% 处的颜色
						}, {
							offset: 1, color: '#dcd018' // 100% 处的颜色
						},],
						globalCoord: false // 缺省为 false
					}],[1,{
						type: 'linear',
						colorStops: [{
							offset: 0, color: '#dcd018' // 0% 处的颜色
						}, {
							offset: 1, color: '#cd2a0e' // 100% 处的颜色
						},],
					}]]
				}
			},
			splitLine :{show:false
			},
			axisTick:{show:false},
			axisLabel:{
				distance:-60,
				color:"cd2a0e"
			},
			pointer:{
				length:'50%',
				width:4
			},
			detail: {fontSize:12,formatter:'CPU:{value}%',offsetCenter:[0,'80%'],color:color},
			data: [{value: data, name: ''}]
		}]
	};

	option.series[0].data[0].value =data;
	myChart.setOption(option, true);
}
