$(document).ready(function(){
	//session 中获取角色，广告主id
	var ctx = $("#ctx").val();
	var role = $("#role").val();
	var advertiserId = $("#sessionadvertiserId").val();
	
	//定时器每秒调用一次当前时间()
	setInterval(function(){
		var date = new Date();
		$("#today").text(formatDate(date));
	},1000);
	
	if(role == "advertiser"){
		$(".chart-down-left").text("趋势图："+$("#sessionadvertiserName").val());
	}
	
	function formatDate(now)   {   
		var year = fnW(now.getFullYear());   
		var month = fnW(now.getMonth()+1);   
		var date = fnW(now.getDate());   
		var hour = fnW(now.getHours());   
		var minute = fnW(now.getMinutes())   
		var second = fnW(now.getSeconds()); 
		if(hour < 12)  
			return  year+"年"+month+"月"+date+"日      上午"+hour+":"+minute+":"+second;
		else 
			return  year+"年"+month+"月"+date+"日      下午"+hour+":"+minute+":"+second;
	}
	
	//补位 当某个字段不是两位数时补0
	function fnW(str){
		var num;
		str>=10?num=str:num="0"+str;
		return num;
	} 
	
	/*
	*根据时间选择,类型选择,广告主id,查询得到图表
	*	初始化一些数值
	*	
	*/
	var flow=[];flow[0] = [];flow[1] = [];flow[2] = [];flow[3] = [];//图表的纵坐标数据
	var labels = [];//图表的横坐标数据
	var tipLabel=new Array("Consume","Impression","Click","Rate");//折线的名字
	var consume=tipLabel[0];
	for (var i = 0; i < 24; i++) {  //默认的X轴的标签labels显示的是昨天的24个小时
		flow[0].push(0);//初始值设置为0;
		flow[1].push(0);//初始值设置为0;
		flow[2].push(0);//初始值设置为0;
		flow[3].push(0);//初始值设置为0;
		if(i<10){
			labels.push("0" + i);
		} else {
			labels.push(i);
		}
	}
	
	/*
	*更改日期的函数，所有更改日期的事件都是调用此函数
	*/
	function cb(start, end) { 
		$('#dateRangePicker').val(start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));//将日期显示在input标签里面
		searchAndDraw(start, end);
	}
	/*
	*查询数据和绘制折线图函数, 只要advertiserId和date改变,就调用此函数重新绘制图形
	*	@param 开始日期,结束日期
	*	操作:		更改日期,
	*			调用searchData函数查询数据
	*			调用drawDiagram函数绘制折线图
	*/
	function searchAndDraw(start, end){
		if(role == 'agent'){
			advertiserId = $('#selectedAdvertiserId3').val();
		}
		if(advertiserId != null){
			searchData(advertiserId,start, end);//调用searchData函数查询数据
		}
		var data = flow[0];	
		drawDiagram(labels,data,consume);//调用绘制图表函数，绘制图表
	}
	/*
	*	默认显示昨天,moment.js是时间日期处理插件,基于jquery
	*/
	cb(moment().subtract(1, 'days'),moment().subtract(1, 'days'));
	
	/*
	*	显示日历插件,jquery.dateRangePicker.js是双日期选择插件,基于jquery
	*		仅仅设置语言为cn, 最大选择日期问今天
	*		绑定一个确定按钮点击事件,回调函数,执行cb函数,更改日期,其实不用改,只不过是为了查询数据和绘制图表
	*/
	$('#dateRangePicker').dateRangePicker({  
		language:'cn',
		endDate:new Date()
	}).bind('datepicker-apply', function(evt, obj) {
		cb(moment(obj.date1), moment(obj.date2));
	});
	
	/*
    *发送ajax请求，查询数据
    * @param 广告主id,开始日期,结束日期 格式为YYYY-MM-DD
    * 将横坐标日期存储在labels数组中
    * 将纵坐标数据存储在flow数组中
    */
	function searchData(advertiserId,start,end){    
		//ajax请求的参数：param{advertiserId,startDate,endDate}
		var param = {
			"advertiserId" : advertiserId,
			"startDate" : start.format('YYYY-MM-DD'),
			"endDate" : end.format('YYYY-MM-DD'),
		}
		//发送ajax请求
		$.ajax({
			type : 'post',	//请求方式，post
			data : param,	//请求参数，param
			url : ctx+'/advertiser/main/dashboard/chart',	//请求url
			async : false,	//是否设置为异步请求
			cache : false,	//是否缓存
			dataType : 'json',	//数据类型为json
			success : function(data){ //请求成功回调函数处理，参数为返回回来的json数组
				//创建消费数，曝光数，点击数，点击率的数组，用于存储返回回来的数据，然后将这些数据存储在flow数组中，用于图表显示
				var consume = [];
				var impression = [];
				var click = [];
				var clickRate = [];
				//判断是数据按小时还是天显示
				if(start.format('YYYY-MM-DD') == end.format('YYYY-MM-DD')){
					labels = [];//清空labels数组
					//如果不是今天
					if(moment().format('YYYY-MM-DD') != start.format('YYYY-MM-DD')){
						for(var i=0;i<24;i++){ //循环给消费数，曝光数，点击数，点击率赋值，循环24次
							if(i<10){
								labels.push("0" + i);
							} else {
								labels.push(i);
							}
							$.each(data,function(key,value){//循环遍历返回的数据data,如果data.hour和当前时间点相等，将相应的值付给数组
								if(value.hour == i){
									consume[i] = value.totalConsume;
									impression[i] = value.totalImpression;
									click[i] = value.totalClick;
									clickRate[i] = value.clickRate;
								}
							});
							//未赋值，将相应的数组值赋0.
							if(consume[i] == null){ consume[i] = 0; }
							if(impression[i] == null){ impression[i] = 0; }
							if(click[i] == null){ click[i] = 0;	}
							if(clickRate[i] == null){ clickRate[i] = 0;	}
						}
					} else { //如果是今天
						var now_hour = new Date().getHours();
						for(var i=0;i<now_hour;i++){ //循环给消费数，曝光数，点击数，点击率赋值，循环24次
							if(i<10){
								labels.push("0" + i);
							} else {
								labels.push(i);
							}
							$.each(data,function(key,value){//循环遍历返回的数据data,如果data.hour和当前时间点相等，将相应的值付给数组
								if(value.hour == i){
									consume[i] = value.totalConsume;
									impression[i] = value.totalImpression;
									click[i] = value.totalClick;
									clickRate[i] = value.clickRate;
								}
							});
							//未赋值，将相应的数组值赋0.
							if(consume[i] == null){ consume[i] = 0; }
							if(impression[i] == null){ impression[i] = 0; }
							if(click[i] == null){ click[i] = 0;	}
							if(clickRate[i] == null){ clickRate[i] = 0;	}
						}
					}
					//如果是昨天或者今天,图表按小时显示数据，后端暂时没有写
					
				} else {
					labels = []; //清空labels数组
					var days = moment.duration(end.diff(start,'days'), 'days').asDays(); //计算选择了几天,利用moment.js相关函数
					for(var i=0;days>=0;i++,days--){ //循环给labels,消费数，曝光数，点击数，点击率赋值，循环days次
						labels[i] = moment(end).subtract(days, 'days').format('MM-DD');//将选择的日期赋值给label，格式为MM-DD，例如选择过去三天：labels=[09-21,09-22,09-23]						
						$.each(data,function(key,value){//循环遍历返回的数据data,如果data.reportDate和当前日期相等，将相应的值付给数组
							if(value.reportDate == moment(end).subtract(days, 'days').format('YYYY-MM-DD')){
								consume[i] = value.totalConsume;
								impression[i] = value.totalImpression;
								click[i] = value.totalClick;
								clickRate[i] = value.clickRate;
							}
						});
						//未赋值，将相应的数组值赋0.
						if(consume[i] == null){ consume[i] = 0; }
						if(impression[i] == null){ impression[i] = 0; }
						if(click[i] == null){ click[i] = 0;	}
						if(clickRate[i] == null){ clickRate[i] = 0;	}
					}
				}
				//将消费数，曝光数，点击数，点击率的数组赋值给flow数组的元素
				flow[0] = consume;
				flow[1] = impression;
				flow[2] = click;
				flow[3] = clickRate;
			},
			error : function (XMLHttpRequest, textStatus, errorThrown) { //url请求出错的回调函数
			    // 通常 textStatus 和 errorThrown 之中
			    // 只有一个会包含信息
				console.info('error');
			    this; // 调用本次AJAX请求时传递的options参数
			}
		});
	}
	/*
	*快速设置为(今天 昨天 过去7天 过去30天)
	*/
	$('#dashboard_chartContent .chart-up .right span.time').click(function(e){ //今天 昨天 过去七天 过去三十天触发函数
        e.preventDefault;
		$('#dashboard_chartContent .chart-up .right span').css('color','#344c67');
		$(this).css('color','#36aeea');
        var ind = $(this).index();
        switch (ind){
            case 0:
                cb(moment(),moment());
                break;
            case 1:
                cb(moment().subtract(1, 'days'),moment().subtract(1, 'days'));
                break;
            case 2:
                cb(moment().subtract(7, 'days'),moment().subtract(1, 'days'));
                break;
            case 3:
                cb(moment().subtract(30, 'days'),moment().subtract(1, 'days'));
                break;
        }
    });
	
	/*
	*四条折线(消费,曝光数,点击数,点击率),点击切换
	*/
	$('#dashboard_chartContent #right_radio input[type="radio"]').click(function(){
		var n = $(this).val();
		var data = flow[n];
		consume = tipLabel[n];
		var txt = '';
		if(n == 0){	txt = '消费（元）';	 }	
		if(n == 1){	txt = '曝光数（次）'; }
		if(n == 2){	txt = '点击数（次）'; }
		if(n == 3){	txt = '点击率（%）'; }
		$('#dashboard_chartContent .chart-down .chart-down-right').html(txt);
		drawDiagram(labels,data,consume);
	});
	
	/*
	*绘制折线图函数
	*	@param 横坐标数值，纵坐标数值，和折线的名字
	*/
	function drawDiagram(labels,data,consume){		
		$('#chart').highcharts({ 
			chart: { type: 'line' },
			title: { text: '' }, //标题
			//subtitle: { text: 'Source: WorldClimate.com' }, //副标题
			xAxis: { categories: labels }, 
			yAxis: { 
				title: { text: '' }, 
				plotLines: [{ value: 0, width: 1, color: '#808080' }]
			}, 
			tooltip: { crosshairs: true, shared: true }, 
			legend: { 
				enabled:false,
			},
			credits:{
				enabled:false,
			},
		
			series: [{ 
				name: consume, 
				data: data,
				color:'#36aeea',
				marker:{
					symbol: 'circle',
					fillColor:'#ffffff',
					lineColor:'#36aeea',
					lineWidth: 2,
					radius: 5,
				}
			}]
		}); 
	}
	
	/*
	*切换折线图和图表
	*/
	$("#diagramHead span:first-child").click(function(){
		$("#sheetContent").css("display","none");
		$("#diagramHead span:first-child").css("border-bottom","1px solid #ffffff");
		$("#dashboard_chartContent").css("display","block");
		$("#diagramHead span:last-child").css("border-bottom","1px solid #d5dee8");
	});
	$("#diagramHead span:last-child").click(function(){
		$("#dashboard_chartContent").css("display","none");
		$("#diagramHead span:first-child").css("border-bottom","1px solid #d5dee8");
		$("#sheetContent").css("display","block");
		$("#diagramHead span:last-child").css("border-bottom","1px solid #ffffff");
		var chooseDate = $('#dateRangePicker').val().split(' to ',2);
		var start = chooseDate[0];//转换为moment格式
		var end = chooseDate[1];//转换为moment格式
		var advertiserId = $('#selectedAdvertiserId3').val();
		var param = {
			'advertiserId':advertiserId,
			'startDate':start,
			'endDate':end,
		};
		var _url = ctx+'/advertiser/main/dashboard/list';
		$.post(_url,param,function(data){
			$('#sheetContent').html(data);
		});
	});
		
	/*
	*根据广告主id创建订单
	*/
	$('#right button.btn1').click(function(){
		if($("#isShowRight").val() == "0"){
			var advertiserId = null;
			//判断是广告主还是代理商
			if(role == "advertiser"){
				advertiserId = $("#sessionadvertiserId").val();
			} else {
				advertiserId = $('#selectedAdvertiserId2').val();
			}
			//如果没有选择广告主,弹出提示
			if((advertiserId == -1) || (advertiserId == null) || (advertiserId == "")){
				bootbox.alert('请选择广告主');
			} else {
				var _href = $(this).attr('href') + '?advertiserId=' + advertiserId;
				window.location.assign(_href);
			}
		}else{
			bootbox.alert('您没有创建订单的权限！');
		}
	});
	
	$("ul#advertiser_son_ul2 li").live("click",function(){
	 	$(this).parents('li').find('span').html($(this).html());
		$("#selectedAdvertiserId2").val($(this).attr("value"));
		$('#advertiser_son_ul2').hide(); //ul隐藏
	});
	
	//获取广告主的值
	if(role == "agent"){
		$("#advertiser_son_ul").hide();
		$("#advertiser_son_ul2").hide();
		$("#advertiser_son_ul3").hide();
		var _url = ctx+"/widget/selector/provide/advertiser?parentId="+$("#sessionagentId").val(); //请求地址
		getSelectData("advertiserul_span","advertiser_son_ul","advertiserul_box","全部广告主",_url);
		getSelectData("advertiserul_span2","advertiser_son_ul2","advertiserul_box2","请选择广告主",_url);
		getSelectData("advertiserul_span3","advertiser_son_ul3","advertiserul_box3","请选择广告主",_url);
	}else if(role == "advertiser"){
		$("#advertiserul_span").html($("#sessionadvertiserName").val());
		$("#selectedAdvertiserId").val($("#sessionadvertiserId").val());
		$("#advertiserul_span2").html($("#sessionadvertiserName").val());
		$("#selectedAdvertiserId2").val($("#sessionadvertiserId").val());
		$("#advertiserul_span3").html($("#sessionadvertiserName").val());
		$("#selectedAdvertiserId3").val($("#sessionadvertiserId").val());
	}
	
	$("ul#advertiser_son_ul li").live("click",function(){
	 	$(this).parents('li').find('span').html($(this).html());
		$("#selectedAdvertiserId").val($(this).attr("value"));
		$('#advertiser_son_ul').hide(); //ul隐藏
		var agentId = $("#agentId").val(); //获取代理商id
		var advertiserId = $('#selectedAdvertiserId').val();
		var param = {};
		if(advertiserId == -1) {
			param = {
				'agentId':agentId
			};
		} else {
			param = {
				'advertiserId':advertiserId
			};
		}
		//发送ajax请求
		$.ajax({
			type : 'post',	//请求方式，post
			data : param,	//请求参数，param
			url  : ctx+'/advertiser/main/dashboard/findCompareAjax',	//请求url
			async : false,	//是否设置为异步请求
			cache : false,	//是否缓存
			dataType : 'json',	//数据类型为json
			success : function(data){ //请求成功回调函数处理，参数为返回回来的json数组
				$('#accountBalance .dataFrame_data').text(data.balance);
				$('#exposure .dataFrame_data').text(data.totalImpression);
				$('#click .dataFrame_data').text(data.totalClick);
			},
			error : function (XMLHttpRequest, textStatus, errorThrown) { //url请求出错的回调函数
				console.info('error');
			}
		});
	});
	
	$("ul#advertiser_son_ul3 li").live("click",function(){
	 	$(this).parents('li').find('span').html($(this).html());
		$("#selectedAdvertiserId3").val($(this).attr("value"));
		$('#advertiser_son_ul3').hide(); //ul隐藏
		$('#dashboard_chartContent .chart-down .chart-down-left').html("趋势图："+$(this).html());
		var chooseDate = $('#dateRangePicker').val().split(' to ',2);
		var start = moment(chooseDate[0]);//转换为moment格式
		var end = moment(chooseDate[1]);//转换为moment格式
		searchAndDraw(start, end);
	});
	
	function getSelectData(target_spanId,target_sonulId,target_boxId,defaultName,url){
		$("#"+target_sonulId).append("<li value='-1' style='width:130px;'>"+defaultName+"</li>");
		$.getJSON( url, function(data) {
			var data_1 = data.advertiserList;
			$.each( data_1, function( key, val ) {
				$("#"+target_sonulId).append('<li class="selectop" value='+ val.value +'>' + val.label + '</li>');
			});
		});
		if($("#isShowRight").val() == "0"){
			$("#"+target_spanId).on("click",function(){
		 		if(role == "agent"){
		 			if($('#'+target_sonulId).height()>210){
		 				$('#'+target_sonulId).addClass("son_ul_change");
		 			};
		 			$('#'+target_sonulId).show(); //ul显示
		 		}
		 	});
		}else{
			if(target_spanId != "advertiserul_span2"){
				$("#"+target_spanId).on("click",function(){
			 		if(role == "agent"){
			 			if($('#'+target_sonulId).height()>210){
			 				$('#'+target_sonulId).addClass("son_ul_change");
			 			};
			 			$('#'+target_sonulId).show(); //ul显示
			 		}
			 	});
			}
		}
		$("#"+target_boxId).mouseleave(function(){
	 		$('#'+target_sonulId).hide(); //ul隐藏
	 		$('#'+target_sonulId).removeClass("son_ul_change");
	 	});
	}
});