//初始化数据data对象
var pageData;
$(function(){
	// 图片路径转换
	var proName = top.window.location.pathname.split("/")[1];
	var sysUrl = "http://"+window.location.host+"/"+proName;
	var picProxyGetUrl = sysUrl+"/sourceProxy?fileType=picUrlProxy&picUrl=";
    //页面全局搜索条件
	var params = {}; 
	var num;
	params.occurTime = '1';	  //默认时间今天
	params.accidentState = '99'; //默认状态全部
	params.page = num ===undefined?0:(num-1)*limit ;
	params.rows = 6;
	
	var startDate = laydate.render({ 
		elem: '#startTime' ,
		type: 'date',
		max: "2099-12-31",
		done: function(value, dates) {
			endDate.config.min = {
				year: dates.year,
				month: dates.month - 1, 
				date: dates.date,
				hours: 0,
				minutes: 0,
				seconds: 0
			};
		}
	});
	var endDate = laydate.render({ 
		elem: '#endTime', 
		type: 'date',
		min: "1970-1-1", 
		done: function(value, dates) {
			startDate.config.max = {
				year: dates.year,
				month: dates.month - 1, 
				date: dates.date,
				hours: 0,
				minutes: 0,
				seconds: 0
			}
		}
	});
	$("#timeTab").on('click', 'li', function() {
		$(this).addClass('active').siblings('li').removeClass('active')
		if($(this).attr('data-c')=="4"){
			$('#timeDiv').slideDown('slow');
		}else{
			$('#timeDiv').slideUp('slow');
		}
	})
	$("#ulState").on('click', 'li', function() {
		$(this).addClass('active').siblings('li').removeClass('active')
	})
	
	
	//pushlet填充数据
	function pushletFillData(datas) {
		resetSearchQuery();  //重新执行一次查询操作
	}
	
	//列表中查看按钮事件
	$('#tab-list').on('click', '.tab-look', function() {
		var data_val = $(this).attr('data-val');
		if(typeof data_val == "string") {
			data_val = JSON.parse(data_val);
		}
		var graphic=parent.MapUtil.getGraphic({"jd":data_val.jd,"wd":data_val.wd});
		if(graphic!=null){
			parent.MapAPI.getMap().centerAt(graphic.geometry).then(function(){
				parent.MapAPI.getMap().infoWindow.setTitle(graphic.getInfoTemplate().title);
				parent.MapAPI.getMap().infoWindow.setContent(graphic.getInfoTemplate().content);
				parent.MapAPI.getMap().infoWindow.setFeatures([graphic]);
				});
			var mapClick=parent.MapAPI.getMap().on("click",function(e){
				var point =parent.MapAPI.getMap().toMap(e.screenPoint);
				if(e.graphic){
					parent.MapAPI.getMap().infoWindow.show(point, parent.MapAPI.getMap().getInfoWindowAnchor(point));
					mapClick.remove();
				}
			});
			}
		var url = top.sysUrl+"/bigscreen/plan/plan.jsp?accidentId="+data_val.accidentid;
		url = top.sysUrl+"/yw/szmap/business/nplan/plan.jsp";
	 	windowid = top.$.createWin({
			 title	: 	'交通事件处理',
			 width  :  '700',
			 height :  '420',
			 data   : data_val,
			 url	:  url
		 });
	}); 
	
	// 确认告警
	$('#tab-list').on('click', '.tab-confim', function() {
		var that = this;
		var data_val = $(this).attr('data-val');
		data_val = JSON.parse(data_val);
		var params = {};
		params.accidentState = 4;           //已处理
		params.accidentId = data_val.accidentId;
		params.alarmType = data_val.eventType;
		params.planGrade = data_val.alarmLevel;
		params.tmpDeviceId = data_val.vdId+"-"+data_val.channelId;
		$.ajax({
			type: "post",
			url: "trafficaccidentinfoAction!update_Trafficaccidentinfo_plan.do",
			dataType: "json",
			data: params,
		}).done(function(res) {
			top.$.showMsg("状态已变更为【 确认报警】");
			$(that).parent().parent().siblings('ul.btm-ul1').children(':last')
			.children(':first').html("已处理").css("color","green");
			$(that).attr("disabled",'disabled');
			$(that).parent().next().children(':first').attr("disabled",'disabled');
		});	
	});
				
	// 忽略告警
	$('#tab-list').on('click', '.tab-ignore', function() {
		var that = this;
		var data_val = $(this).attr('data-val');
		data_val = JSON.parse(data_val);
		var params = {};
		params.accidentState = 3;
		params.accidentId = data_val.accidentId;
		$.ajax({
			type: "post",
			url: "trafficaccidentinfoAction!update_Trafficaccidentinfo_plan.do",
			dataType: "json",
			data: params,
		}).done(function(res) {
			//console.log(res);
			top.$.showMsg("状态已变更为【忽略报警】");
			
			$(that).parent().parent().siblings('ul.btm-ul1').children(':last')
			.children(':first').html("已忽略").css("color","green");
			$(that).attr("disabled",'disabled');
			$(that).parent().prev().children(':first').attr("disabled",'disabled');
			
		});
		
	});
	
	//点击关闭按钮后操作事件，点击确认、忽略后操作事件
	function resetSearchQuery(){
		var page_num = params.page;
		$.ajax({
			type: "post",
			url: "bigScreenAction!getAlarmEvent.do",
			dataType: "json",
			data: params,
		}).done(function(res) {
			if(res.total) {
				childFillData(res.listData)
				if (page_num === undefined) {
                    $("#page").initPage(res.totalCount, 1, function (index) {
                    	searchRequest(page, index);
        			});
                }else{
                	$("#page").initPage(res.totalCount, page_num, function (index) {
                    	searchRequest(page, index);
        			});
                }
			}
		});
	}
	
	
	//进入页面后先执行一次查询操作。
	$('#tab-btn-search').on('click',searchHandler).trigger('click');
	function searchHandler(){
		params = {};  //页面搜索条件
		var timeLi = $("#timeTab").children('.active').attr('data-c');
		var stateLi = $("#ulState").children('.active').attr('data-c');
		if(timeLi == 4){
			var startTime = $('startTime').val();
			var endTime = $("#endTime").val();
			params.startTime = startTime;
			params.endTime = endTime;	
			$('#timeDiv').slideUp('slow');
		}else{
			params.occurTime = timeLi;	
		}
		params.accidentState = stateLi;
		var usersearch = $("#tab-search").val(); //搜索框
		params.tdmc = $.trim(usersearch);
		params.pageNum = num === undefined?0:(num-1)*limit ;
		params.rows = 6;
		$.ajax({
			type: "post",
			url: "bigScreenAction!getAlarmEvent.do",
			dataType: "json",
			data: params,
		}).done(function(res) {
			if(res.totalCount) {
				childFillData(res.listData)
				if (num === undefined) {
                    $("#page").initPage(res.totalCount, 1, function (index) {
                    	searchRequest(page, index);
        			});
                }
			}else{
				$("#tab-list").empty(); 
				 $("#page").empty(); 
			}
		});
	}
	//轮播图
	var a = parent.$(".view").closest('.swiper-container');
	var viewSwiper = new Swiper('.view .swiper-container', {
		onSlideChangeStart: function() {
			updateNavPosition()
		}
	})
	$('.view .arrow-left,.preview .arrow-left').on('click', function(e) {
		e.preventDefault()
		if(viewSwiper.activeIndex == 0) {
			viewSwiper.swipeTo(viewSwiper.slides.length - 1, 1000);
			return
		}
		viewSwiper.swipePrev()
	})
	$('.view .arrow-right,.preview .arrow-right').on('click', function(e) {
		e.preventDefault()
		if(viewSwiper.activeIndex == viewSwiper.slides.length - 1) {
			viewSwiper.swipeTo(0, 1000);
			return
		}
		viewSwiper.swipeNext()
	})
	var previewSwiper = new Swiper('.preview .swiper-container', {
		visibilityFullFit: true,
		slidesPerView: 'auto',
		onlyExternal: true,
		onSlideClick: function() {
			viewSwiper.swipeTo(previewSwiper.clickedSlideIndex)
		}
	})
	function updateNavPosition() {
		$('.preview .active-nav').removeClass('active-nav')
		var activeNav = $('.preview .swiper-slide').eq(viewSwiper.activeIndex).addClass('active-nav')
		if(!activeNav.hasClass('swiper-slide-visible')) {
			if(activeNav.index() > previewSwiper.activeIndex) {
				var thumbsPerNav = Math.floor(previewSwiper.width / activeNav.width()) - 1
				previewSwiper.swipeTo(activeNav.index() - thumbsPerNav)
			} else {
				previewSwiper.swipeTo(activeNav.index())
			}
		}
	}
	//============================== 上一页  下一页  点击事件 start====================================	  	
	parent.$("#dd").find('div #btn_pre').click(function(){          // 上一页
		var accId = parent.$('#btn_qrbj').attr("data-id");     // 得到 accId				
		var total = pageData.length;
		var pre = 0;
		for(var i=0; i < pageData.length; i++){
			var record = pageData[i];
			if(accId == record.accidentId){
				pre = i;
				break;
			}
		}
		if(pre > 0){
			upDown(pageData[pre-1]);
		}else{
			alert("已经是第一条");
		}
		
	});
	parent.$("#dd").find('div #btn_down').click(function(){			// 下一页
		var accId = parent.$('#btn_qrbj').attr("data-id");     // 得到 accId		
		var total = pageData.length;
		var pre = pageData.length;
		for(var i=0; i < pageData.length; i++){
			var record = pageData[i];
			if(accId == record.accidentId){
				pre = i;
				break;
			}
		}
		if(pre < pageData.length-1){
			upDown(pageData[pre+1]);
		}else{
			alert("已经是最后一条");
		}
		
	});
	
	function upDown(data_val) {	 // 分页数据渲染		
		if(typeof data_val == "string") {
			data_val = JSON.parse(data_val);
		}
		//获取图片路径
		var imgPath = data_val.eventSmallUrl; 
		var sz_imgPath=new Array(); 
		var firstImg = '';
		var allImg = '';
		if(imgPath != null){
			sz_imgPath = imgPath.split('$');
			firstImg = sz_imgPath[0];
			//循环显示小图
			for(var k=0;k<sz_imgPath.length;k++){
				allImg+='<img src="'+$.getPicProxyUrl(sz_imgPath[k])+'" alt=""  width="130" height="100" onerror="$.loadErrorPic(this);">';
			}
		}
		parent.$("#dd").find('.info-ul').html('<li>相机名称：'+data_val.tdmc+'</li><li>报警时间：'+data_val.occurTime+'</li>'+
											  '<li>事件类型：'+data_val.eventName+'</li><li>警情等级：'+data_val.alarmLevelName+'</li>'+
											  '<li>道路名称：'+data_val.roadName+'</li><li>隧道名称：'+data_val.tunnelName+'</li>'+
											  '<li>起止桩号：'+data_val.startPile+'</li>'+
											  '<li>处理状态：'+data_val.accidentName+'</li>');
		//大图
		parent.$("#dd").find('div.pc-img-topimg img').eq(0).attr('src',picProxyGetUrl+firstImg);
		parent.$("#dd").find('div.pc-img-btm').html(allImg);
		//将本页面搜索条件放到弹窗中，执行关闭时重新查询一次。
		var v_param = JSON.stringify(params); 
		parent.$('#dd').find('div .div-img>ul').eq(0).attr('data-query',v_param)
		//判断确认报警、忽略报警按钮是否显示
		if(data_val.accidentName != '未处理'){
			parent.$("#dd").find('div #btn_qrbj').hide();
			parent.$("#dd").find('div #btn_hlbj').hide();
		}else{
			parent.$("#dd").find('div #btn_qrbj').show();
			parent.$("#dd").find('div #btn_hlbj').show();
		}
		//将摄像头设备编号、通道编号、通道名称信息填充至按钮
		var data_channel = data_val.vdId+'$'+data_val.channelId+'$'+data_val.tdmc;
		parent.$("#dd").find('div .div-img-title li').attr('data-channel',data_channel);
		parent.$("#dd").find('div .div-img-title li').attr('data-time',data_val.occurTime);
		//点击查看隐藏视频和回放div，显示图片div层
		parent.$("#dd").find('div .pc-img').show();
		parent.$("#dd").find('div .pc-video').hide();
		parent.$("#dd").find('div .pc-recordvideo').hide();
		parent.$("#dd").find('div .div-img-title li').eq(0).addClass('active');
		parent.$("#dd").find('div .div-img-title li').eq(1).removeClass('active');
		parent.$("#dd").find('div .div-img-title li').eq(2).removeClass('active');
		//确认报警、忽略报警按钮中，把当前记录id放在data-id标签中
		parent.$("#dd").find('div .div-info input').attr('data-id',data_val.accidentId);
		parent.$("#dd").dialog({
			title: '事件详情',
			width: 710,
			top: 60,
			left: 350,
			closed: false,
			cache: false,
			//  href: 'get_content.php',
			modal: true,
			onClose:function(){    //关闭窗口事件
                resetSearchQuery();
            }  
		});
	}
//=============================上一页  下一页  点击事件 end====================================


// pushlet数据叠加
function addPusData(pusData){
	var rest;
	var totalCount;
	$.ajax({
		type  	 : "post",
		async 	 : false,
		url      : "bigScreenAction!getAlarmEvent.do",
		dataType : "json",
		data     : params,				
	}).done(function(res) {
		if(res.totalCount){
			totalCount = res.totalCount;
			if(pusData.length > 0){
				rest = pusData.concat(res.listData);
			}else{
				rest = res.listData;
			}
			if(rest.length > 6){
				rest = rest.slice(0,6);
			}
			childFillData(rest);
			$("#page").initPage(totalCount, 1, function (index) {
            	searchRequest('', index);
			});
		}
	})
}
});

//全局搜索
function searchRequest(page, num){
	params = {};
	var timeLi = $("#timeTab").children('.active').attr('data-c');
	var stateLi = $("#ulState").children('.active').attr('data-c');
	if(timeLi == 4){
		var startTime = $('startTime').val();
		var endTime = $("#endTime").val();
		params.startTime = startTime;
		params.endTime = endTime;	
	}else{
		params.occurTime = timeLi;	
	}
	params.accidentState = stateLi;
	var usersearch = $("#tab-search").val(); //搜索框
	params.tdmc = $.trim(usersearch);
	params.pageNum = num;
	params.rows = 6;
	$.ajax({
		type: "post",
		url: "bigScreenAction!getAlarmEvent.do",
		dataType: "json",
		data: params,
	}).done(function(res) {
		if(res.totalCount) {
			childFillData(res.listData)
			if (num === undefined) {
                $("#page").initPage(res.totalCount, 1, function (index) {
                	searchRequest(page, index);
    			});
            }else{
            	 $("#page").initPage(res.totalCount, num, function (index) {
                    	searchRequest(page, index);
        			});
            }
		}
	});
}

//iframe页面填充数据
function childFillData(datas) {
	if(typeof datas == "string") {
		datas = JSON.parse(datas);
	}
	datas.forEach(function(item,i){
		item.index = i;
		var str = JSON.stringify(item);
		item.str = str;
	})
	//将当前数据赋值给全局页面数据pagedata
	pageData = datas;
	changeUrl(datas); //修改图片链接
	var innerText = doT.template($("#pttab").text());
	$('#tab-list').html(innerText(datas));
}

//图片url转换
function changeUrl(data) {
	data.forEach(function(item) {
		if(item.eventUrl != null) {
			var proName = top.window.location.pathname.split("/")[1];
			var sysUrl = "http://" + window.location.host + "/" + proName;
			item.eventUrl = sysUrl + "/sourceProxy?fileType=picUrlProxy&picUrl=" + item.eventUrl;
		}
	})
}

//目标物 框选
function showTarget(that){
	var point = JSON.parse($(that).attr("data-val"));
	var w = parseInt($(that).width()) ;
	var h = parseInt($(that).height()) ; 
	var divY = point.locationY;
	var divX = point.locationX;
	var divH = point.locationHeight;
	var divW = point.locationWidth;
	var index = point.index;
	var flag = true;
	if(ifNull(divY) || ifNull(divX) || ifNull(divH) || ifNull(divW)){			// 为空不做处理
		flag = false;
	}else{
		divY = h * divY + index * 70.2 + 80;
		divX = w * divX + 10;
		divH = h * divH;
		divW = w * divW;
	}
	if(flag){
		var div = "<div class='hhhh' style='width:"+ divW +"px;height:"+ divH +"px;border:1px solid red;position:absolute;top:"+ divY +"px;left:"+ divX +"px;'>";		
		$(that).parent().append(div)
	}
}

function ifNull(str){
	if(str == null){
		return true
	}else if(str == ''){
		return true
	}else if(str == ' '){
		return true;
	}else{
		return false;
	}
}


