/**
 * 
 */
var videoblock;
var recordblock;
$(function(){
	initTime();
	var winId	= getUrlParam("winId");
	var records = top.$("#"+winId).panel("options").data;
	console.log(winId,records);
	
	//播放实时视频
	window.WebRtcServer && WebRtcServer.connectServer();
	(window !== top.WebRtcServer.reqPage) && top.WebRtcServer.setReqPage(window);
	initBodyEvent();

	var sbbh = records.sbbh;
	var tdbh = records.tdbh;
	var tdmc = records.tdmc;
	var deviceId = records.xh;
//	var curDate = records.curDate;
	var sbip = records.sbip;
	var cjmc = records.cjmc;
	
	$("#channelname").text(tdmc);
	$("#videonum").text(tdbh);
	$("#channelnum").text(sbbh);
	$("#sbip").text(sbip);
	$("#cjmc").text(cjmc);
//	$("#currentstate").text(data.currentstatename);
	
//	webrtc_startVideo(sbbh,tdbh,tdmc);
	if(records.video == '1'){				// 播放实时视频		
		$('div.pc-video').show();
		$('div.pc-recordvideo').hide();
//		webrtc_startVideo('201808091236525951','1','窗口高架_01');
		webrtc_startVideo(sbbh,tdbh,tdmc);
	}else if(records.video == '2'){			// 播放历史视频
		$("#searchDate").datebox("setValue",$.getTodayStart(0,"00:00:00"));
		$("#recordBtn").show();
		$('div.pc-recordvideo').show();
		$('div.pc-video').hide();
		var curDate = $("#searchDate").val();
		webrtc_startRecord(sbbh,tdbh,tdmc,curDate)
	}
	//关闭视频
	parent.$(".panel-tool-close").on("click",function(){
		unloadWindow();
	})
	parent.$(".l-btn-text").on("click",function(){
		unloadWindow();
	})
	//确认告警
 	$("#btn_qrya").on("click",function(){
 		
 		var params = {};
 		params.occurTime = $("#occurTime").html();
 		params.alarmType = $("#alarmType").val();
 		params.alarmLevel = $("#alarmLevel").val();
 		params.deviceId = deviceId;
 		params.vdId = sbbh;
 		params.channelId = tdbh;
 //		console.log(jietu())
 		params.imgBase64 = jietu();//imgSrcToBase64($("#abc")[0]);
 //		console.log("提交参数：",params);
 		
 		
 		unloadWindow();
 		top.$("#"+winId).dialog('close');         // 关闭窗口
 		$.ajax({
 			 type:'post',
 			 dataType : 'json',
 			 data:params,
 			 url : 'trafficaccidentinfoAction!insert_Trafficaccidentinfo.do',
 			 success:function(data){
 				console.log(data);
 				if(data.result==="success"){
 					changeState();
 					top.$.showMsg("操作成功");				
 				}else{
 					top.$.showMsg("异常");
 				}
 			 },
 			 error:function(){
 				 top.$.showMsg("异常");
 			 }
 		});	
 	});
	
 	
 // 忽略告警
	$('#btn_qxya').click(function(){
		unloadWindow();
		top.$("#"+winId).dialog('close');         // 关闭窗口
	})
 	
	
	/*$("#btn_jietu").on("click",function(){
		$("#abc").attr("src",jietu());
		console.log("hhhhhhhh")
		changeState();
		console.log("hhhhhhhh")
 	})*/
});
	
function getUrlParam(name){
  	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");    
  	var search = window.location.search.substr(1);
  	var href = window.location.href;
  	if(href.indexOf("?")>=0){
  		search = href.substr(href.indexOf("?")+1);
  	}
  	var r = search.match(reg);    
  	if (r != null) return decodeURI(r[2]); return null;    
}

//实时视频
function initBodyEvent(){
	$(window).on("focus",function(){
		(window !== top.WebRtcServer.reqPage) && top.WebRtcServer.setReqPage(window);
	});
}

//实时播放视频组件
function initBlock(){
	var uuid = $.uniqueId();
	videoblock = $.videoBlock({
		uuid : uuid,
		title : "",
		$baseContainer : $("#video"),
		$content:$("#video"),
		serverConnection : top.serverConnection,
		monid : null,
		isRunning : false,
		onRightClick : $.noop()
	});
	BlockCacher.addBlock(videoblock);
	$("#video video").attr("id",videoblock.videoId);
	console.log('实时视频============',videoblock);
}
function webrtc_startVideo(sbbh,tdbh,tdmc){
	initBlock();
	console.log('实时视频参数=='+sbbh+'，'+tdbh+'，'+tdmc);
	videoblock.setFdId(sbbh).setChannelId(tdbh).setHideTitle(tdmc).startMonitor();
}

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";
	/*		var start ="00:10:50";
	var end ="00:11:50";*/
	barInit(startTime,endTime);
	webrtc_startRecord(record.videonum,record.channelnum,record.channelname,startTime,endTime);//设备编号$通道编号$通道名称信息
}

//历史视频播放组件
function initRecordBlock(){
	var uuid = $.uniqueId();
	recordblock = $.recordblock({
		uuid : uuid,
		title : "",
		$baseContainer : $("#record"),
		$content:$("#record"),
		serverConnection : top.serverConnection,
		monid : null,
		isRunning : false,
		onRightClick : $.noop()
	});
	BlockCacher.addBlock(recordblock);
	$("#record video").attr("id",recordblock.videoId);
	//console.log('历史视频============',recordblock);
}
function webrtc_startRecord(sbbh,tdbh,tdmc,curDate){
	initRecordBlock();
	var playbackurl = "";
	var start_occur= "";
	var end_occur = "";
	var startTime = curDate+" 00:00:00";
	var endTime = curDate+" 23:59:59";
	start_occur = start_occurTime(startTime);
	end_occur = end_occurTime(endTime);	
	
//	console.log('回放视频参数=='+sbbh+'，'+tdbh+'，'+tdmc+'，'+curDate);
//	console.log('=回放录像时间start_occur = ' , start_occur);
//	console.log('=回放录像时间end_occur = ' , end_occur);
//	if($('#occurTime').html()){
		//curDate = $('#occurTime').html();
//	}
	//console.log(sbbh+"=回放录像时间="+curDate);
	
	setTimeout(function(){
		recordblock.setFdId(sbbh).setChannelId(tdbh).setHideTitle(tdmc).startPlayback(start_occur,0,end_occur,playbackurl,sbbh,tdbh,0);
	},300)
	//recordblock.setFdId(sbbh).setChannelId(tdbh).setHideTitle(tdmc).startPlayback(start_occur ,0,end_occur,playbackurl,sbbh,tdbh,0);
}
//关闭视频组件
//关闭视频组件
function unloadWindow(){
	/*for(var i = 0;i < BlockCacher.blockCache.length;i++){
		if(BlockCacher.blockCache[i].fdId && BlockCacher.blockCache[i].channelId != null){
			BlockUtil.stopMonitor(i);
		}
	}*/
	if(videoblock && videoblock.fdId && videoblock.channelId != null){
		//实时视频关闭
		videoblock.stopMonitor();
		videoblock.setRunning(false).setHideTitle("").setTitle("")
		.setFdId("").setChannelId("").setMonId(null);
		videoblock.setPeerConnection(null);
		videoblock.getVideoComp().src = "";
	}
	if(recordblock && recordblock.fdId && recordblock.channelId != null){
		//录像关闭
		recordblock.stopPlayback();
		recordblock.setRunning(false).setHideTitle("").setTitle("")
		.setFdId("").setChannelId("").setMonId(null);
		recordblock.setPeerConnection(null);
		recordblock.getVideoComp().src = "";
	}
}

//毫秒数转换
function timeChange(time){
	return Date.parse(new Date(time.replace(/-/g,"/")))/1000;
}
//事件开始事件，输入字符串时间前10秒
function start_occurTime(time){
	var dt=new Date(time.replace(/-/g,"/"));//将传入的日期格式的字符串转换为date
	var ndt=new Date(dt.getTime()-10000);//将转换之后的时间减去十秒
	//console.log('开始时间为：',ndt);
	return Date.parse(ndt)/1000;
}
//事件开始事件，输入字符串时间后10秒
function end_occurTime(time){
	var dt=new Date(time.replace(/-/g,"/"));//将传入的日期格式的字符串转换为date
	var ndt=new Date(dt.getTime()+10000);//将转换之后的时间减去十秒
	//console.log('结束时间为：',ndt);
	return Date.parse(ndt)/1000;
}

//初始化时间
function initTime(){
	var myDate = new Date();
	var month = myDate.getMonth()+1;
	if(month<10){
		month = "0"+month
	}
	var day = myDate.getDate();
	if(day<10){
		day = "0"+day;
	}
	var hours = myDate.getHours();
	if(hours<10){
		hours = "0"+hours;
	}
	var minutes = myDate.getMinutes();   
	if(minutes<10){
		minutes = "0"+minutes;
	}
	var seconds = myDate.getSeconds();
	if(seconds<10){
		seconds = "0"+seconds;
	}
	//报警时间
	$("#occurTime").html(myDate.getFullYear()+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds).attr("disabled","disabled");
}

//截图
function jietu(){
	var video = document.getElementById("video").getElementsByTagName("video");//获取前台要截图的video对象，
	var canvas = document.getElementById("jtCanvas");//获取前台的canvas对象，用于作图
	var ctx = canvas.getContext('2d');//设置canvas绘制2d图，
//	var width = 500;//设置canvas宽
//	var height = 500;//设置canvas高
	canvas.width = video[0].offsetWidth;
	canvas.height = video[0].offsetHeight;
//	console.log(video[0].offsetWidth)
	ctx.drawImage(video[0], 0, 0, video[0].offsetWidth, video[0].offsetHeight);//将video视频绘制到canvas中
	return canvas.toDataURL('image/jpg');//canvas的api中的toDataURL（）保存图像
}

function imgSrcToBase64(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img,0,0,img.width,img.height);
    return canvas.toDataURL("image/jpg");
}

function changeState(){
	var ff = parent.window.frames[0].document.getElementById("iframe-jklk-tab").contentWindow;
	var page = ff.document.getElementById('page');
	var pangNum = $(page).find('li.pageItemActive').html();	
//	console.log("========== pangNum：",pangNum);
	ff.searchRequest('',pangNum);
}

function barInit(start, end){
	ProgressBar.init({
		startTime:new Date(start),
		endTime:new Date(end),
		totalSecond:86400
	});
}