var cur_brand = '',cur_type = 1,program_arr = [],brand_arr = [];

function getBrandDetail(){
	getPlacementDetailList(1);
	getPieData(cur_type);
	getRatingCharts(cur_type);
	getNetChart(cur_type,'');
	getDoubanChart(cur_type);
	getRankList(cur_type);
	changeTagName();
}

function itemCheck(o){
	var item = $("input[name='item']:checked"), ids = [];
	item.each(function(){
		ids.push($(this).val());
	});
	if(item.length > 2){
		alert("请选择两个对标的品牌。");
		$(o).attr("checked", false);
		$.checkbox();
		return false;
	}
	$.cookie.set("benchCheckNum",ids.join(","));
}

function setBenchmark(){
	var item = $("input[name='item']:checked"), ids = [];
	if(item.length <= 0){
		alert("请至少选择一个对标的品牌。");
		return false;
	}
	if(item.length > 2){
		alert("请选择两个对标的品牌。");
		return false;
	}
	item.each(function(){
		ids.push($(this).val());
	});
	window.open("benchmarking.do?ids="+encodeURIComponent(ids.join("|")),"new");
}

/**
 * 切换时间
 */
function changeTab(day){
	var end_date = '', start_date = '';
	if(day > 0){
		end_date = new Date().addDate(-1).Format("yyyy-MM-dd"),
		start_date = new Date(end_date).addDate(-day).Format("yyyy-MM-dd");
		$('#start_time').val(start_date);
		$('#end_time').val(end_date);
	}else{
		$('#start_time').val('');
		$('#end_time').val('');
	}
	$(".text").input();
	getBrandAnalysisList(1);
	/*getPlacementDetailList(1);
	getPieData(cur_type);
	getRatingCharts(cur_type);
	getNetChart(cur_type,'');
	getDoubanChart(cur_type);
	getRankList(cur_type);
	changeTagName();*/
}

function changeType(type){
	if(type == 4){
		$('#tv_title').hide();
		$('#tv_div').hide();
	}else{
		$('#tv_title').show();
		$('#tv_div').show();
	}
	cur_type = type;
	getBrandDetail();
	changeTagName();
}

function changeBrand(brand){
	cur_brand = brand;
	getBrandDetail();
}


function getBrandAnalysisList(page){
	page = page || 1;
	var pageSize = "10", data = {
		"pageNo": page,
		"pageSize": pageSize,
		"keyword": $("#keyword").val(),
		"type": $("#type").val(),
		"second_ind":$("#second_ind").val(),
		"beginDate": $("#start_time").val(),
		"endDate": $("#end_time").val()
	}, html = "";
	$("#brand_analysis_page, #brand_analysis_list").empty();
	ajax("ajax_special_analysis_list.do",data,function(res){
		if(res.code == 1 && res.data.records.length > 0){
			$.each(res.data.records, function(index, item){
				if(index == 0){
					cur_brand = item.brand;
				}
				html += "<tr data-brand='"+item.brand+"'>"+
					"<td>"+$.orderNum(page,pageSize,index)+"</td>"+
					"<td>"+item.mediaName+"</td>"+
                    "<td>"+item.showTime+"</td>"+
					"<td>"+item.showDate+"</td>"+
					"<td>"+item.showEnv+"</td>"+
					"<td>"+item.tvName+"</td>"+
					"<td>"+item.showDuration+"</td>"+
					"<td>"+item.productName+"</td>"+
					"<td>"+item.brandName+"</td>"+
					"<td>"+item.firstInd+"</td>"+
					"<td>"+item.secondInd+"</td>"+
					"<td>"+item.advMaster+"</td>"+
					"<td>"+item.phone+"</td>"+
					"<td>"+item.price+"</td>"+
					"<td><input type='checkbox' class='checkbox {click:itemCheck}' name='item' "+($.cookie.get("benchCheckNum").indexOf(item.brand) != -1 ? 'checked':'')+" value='"+item.brand+"' /><label></label></td>"+
				"</tr>";
			});
			$("#brand_analysis_list").html(html);
			$.radio();
			$.checkbox();
			var newpage = new createPage(res.data.total,page,pageSize,3,"brandAnalysisPageGo");
			$("#brand_analysis_page").html(newpage.pageHtml);
			$('#brand_analysis_count').html(res.data.count);
			/**
			 * 点击事件
			 */
			$("#brand_analysis_list>tr>td:not(td:last-child)").on("click",function(){
				$(this).closest("tr").addClass("active").siblings().removeClass("active");
				changeBrand($(this).closest("tr").data("brand"));
			});
			$("#brand_analysis_list>tr:eq(0)>td:eq(1)").click();
		}else{
			$("#brand_analysis_list").info("暂无数据。");
			$('#brand_analysis_count').html(0);
		}
	});
}

brandAnalysisPageGo = getBrandAnalysisList;



function getPlacementDetailList(page){
	page = page || 1;
	var pageSize = "10",keyword =  $("#keyword").val(),beginDate = $("#start_time").val(),
		endDate = $("#end_time").val(),data = {
		"type": $("#type").val(),
		"pageNo": page,
		"pageSize": pageSize,
		"keyword": keyword,
		"beginDate": beginDate,
		"endDate": endDate
	}, html = "";
	$("#placement_detail_page, #placement_detail_list").empty();
	ajax("ajax_placement_detail_list.do",data,function(res){
		if(res.code == 1 && res.list.length > 0){
			$.each(res.list, function(index, item){
				//广告形式，1节目冠名2特约播映3互动支持4合作伙伴5指定产品6指定用车7其他
				var f = ['','冠名','特约','互动支持','合作伙伴','指定产品','指定用车','其他'];
				var forms = item.form ? item.form.split(",") : [] ,t_tmp = [];
				for(var i in forms){
					t_tmp.push(f[ forms[i] ]);
				}
				var platforms = item.platform ? item.platform.split(",") : [];
				platforms = unique(platforms);
				html += "<tr data-id='"+item.id+"'>"+
					"<td>"+$.orderNum(page,pageSize,index)+"</td>"+
					"<td>"+item.brand+"</td>"+
					"<td>"+(item.advertiser ? item.advertiser : '-')+"</td>"+
					"<td>"+(item.second_ind ? item.second_ind : '-')+"</td>"+
					"<td>"+(item.first_ind ? item.first_ind : '-')+"</td>"+
					"<td>"+item.program_name+"</td>"+
					"<td>"+(item.show_time ? item.show_time : '-')+"</td>"+
					"<td>"+ ((item.type == 1 || item.type == 2) ? "第" + item.show_phase +"期" : (item.episode ? "第"+ item.episode+"集" : '-'))+"</td>"+
					"<td>"+(platforms?platforms.join(','):'-')+"</td>"+
					"<td>"+(item.net_platform ? (item.net_platform.split(',').length > 2 ? '全网' : item.net_platform) : '-')+"</td>"+
					"<td>"+t_tmp.join(',')+"</td>"+
					"<td><span class='orange'>"+item.total+"</span></td>"+
					"<td>"+item.sum_frequency+"</td>"+
					"<td>"+item.sum_length+"</td>"+
					"<td>"+item.price+"</td>"+
				"</tr>";
			});
			$("#placement_detail_list").html(html);
			var newpage = new createPage(res.count,page,pageSize,3,"placementDetailPageGo");
			$("#placement_detail_page").html(newpage.pageHtml);
			$('#placement_detail_count').html(res.count);
			/**
			 * 点击事件
			 */
			$("#placement_detail_list>tr>td").on("click",function(){
				$(this).closest("tr").addClass("active").siblings().removeClass("active");
				var url = 'open_show_analyse.do?id='+$(this).closest("tr").data("id");
				url += '&name='+name;
				url += '&beginDate='+beginDate;
				url += '&endDate='+endDate;
				$.openWindow('',url, 960, 610, true, null, 'auto');
			});
		}else{
			$("#placement_detail_list").info("暂无数据。");
			$('#placement_detail_count').html(0);
		}
	});
}

placementDetailPageGo = getPlacementDetailList;


function getPieData(type){
	var data = {
			"type" : type,
			"brand": cur_brand,
			"name": $("#keyword").val(),
			"beginDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		};
	program_arr = [];
	ajax("list_program_placement4Brand.do",data,function(res){
		if(res.code == 1 && res.list.length > 0){
			var legend = [];
			var series_frequency = [];
			var series_length = [];
			$.each(res.list, function(index, item){
				var program = "《"+item.program_name+"》" + ((type == 1 || type == 2) ? ("-" + (res.adMode[item.form-1] != undefined ? res.adMode[item.form-1].val : "")) : '');
				legend.push(program);
				program_arr.push(item.program_name);
				var lv1 = {
						value:item.frequency, 
						name:program
				};
				series_frequency.push(lv1);
				var lv2 = {
						value:item.length, 
						name:program
				};
				series_length.push(lv2);
				if(index > 13){
					return false;
				}
			});
			trend_pie("频次分布",legend,series_frequency,'frequency_pie');
			trend_pie("时长分布",legend,series_length,'length_pie');
		}else{
			$("#frequency_pie,#length_pie").info("暂无数据。", true);
		}
	},false);
}

function getRatingCharts(type){
	getRatingChart(type,1,1);
	getRatingChart(type,2,1);
}

function getRatingRatio(obj){
	getRatingChart(cur_type,1,$(obj).val())
}

function getRatingRatio2(obj){
	getRatingChart(cur_type,2,$(obj).val())
}

/**
 * 电视频道品牌软广植入受众人群一览
 * @param type 1综艺 2栏目 3电视剧 4电影
 * @param rateType 1：35城  2:29城
 * @param ratioValue 1：4岁以上   2：A18-45  3:F18-45     
 */
function getRatingChart(type,rateType,ratioValue){
	var data = {
			"type" : type,
			"rateType" : rateType,
			"brand": cur_brand,
			"name": $("#keyword").val(),
			"beginDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		};
	ajax("list_program_rating4Brand.do",data,function(res){
		if(res.code == 1 && res.list.length > 0){
			var legend = ['收视率(%)','到达率(000)'],xdata = [],ydata = [],ys = [];
			if(type == 3){
				$('#rating_ratio_div_1').hide();
				$('#rating_ratio_div_2').hide();
			}else{
				$('#rating_ratio_div_1').show();
				$('#rating_ratio_div_2').show();
			}
			$.each(res.list, function(index, item){
				var program = "《"+item.program_name+"》" + ((type == 1 || type == 2) ? ("-" + (res.adMode[item.form-1] != undefined ? res.adMode[item.form-1].val : "")) : '');
				xdata.push(program);
				if(ratioValue == 2){
					ydata.push(item.audience_rating_20_45);
					ys.push(item.avg_num_20_45);
				}else if(ratioValue == 3){
					ydata.push(item.audience_rating_18_45_woman);
					ys.push(item.avg_num_18_45_woman);
				}else if(ratioValue == 4){
					ydata.push(item.audience_rating_18_30_woman);
					ys.push(item.avg_num_18_30_woman);
				}else if(ratioValue == 5){
					ydata.push(item.audience_rating_20_45_man);
					ys.push(item.avg_num_20_45_man);
				}else{
					ydata.push(item.audience_rating_4);
					ys.push(item.avg_num_4);
				}
				if(index > 8){
					return false;
				}
			});
			trendBarWithLine(legend,xdata,ydata,ys,(rateType==1?'rating_35':'rating_29'));
		}else{
			$("#"+(rateType==1?'rating_35':'rating_29')).info("暂无数据。",true);
		}
	},false);
}


/**
 * 网络综艺节目植入效果一览
 */
function getNetChart(type,platform){
	var data = {
			"platform":platform,
			"type" : type,
			"brand": cur_brand,
			"name": $("#keyword").val(),
			"beginDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		};
	ajax("list_program_net_data4Brand.do",data,function(res){
		if(res.code == 1 && res.list.length > 0){
			var legend = ['点击率(千万)','网站评分(分)'],xdata = [],ydata = [],ys = [],platforms = [],html = "";
			
			$.each(res.list, function(index, item){
				var program = "《"+item.program_name+"》" + ((type == 1 || type == 2) ? ("-" + (res.adMode[item.form-1] != undefined ? res.adMode[item.form-1].val : "")) : '');
				xdata.push(program);
				platforms.push(item.platform_name);	
				xdata = unique(xdata);
				if(xdata.length > 9){
					return false;
				}
			});
//			xdata = unique(xdata);
			$.each(res.list, function(index, item){
				var program = "《"+item.program_name+"》" + ((type == 1 || type == 2) ? ("-" + (res.adMode[item.form-1] != undefined ? res.adMode[item.form-1].val : "")) : '');
				for(var i in xdata){
					if(xdata[i] == program){
						ydata[i] = ((ydata[i] ? ydata[i] : 0)*100 + item.click_times*100) / 100;
						ys[i] = item.score || "";
					}
				}
				//ydata.push(item.click_times);
				//ys.push(item.score);
			});
			if(platform == ''){
				html += '<input type="radio" name="net_ratio" class="radio {click:clickNetRatio}" value="" checked/><label>综合</label>&nbsp;&nbsp;&nbsp;&nbsp;';
				platforms = unique(platforms);
				for(var i in platforms){
					html += "<input type='radio' name='net_ratio' class='radio {click:clickNetRatio}' value='"+platforms[i]+"' /><label>"+platforms[i]+"</label>&nbsp;&nbsp;&nbsp;&nbsp;";
				}
				$('#platform_ratios').html(html).attr("align","center");
			}
			trendBarWithLine(legend,xdata,ydata,ys,'net_chart');
		}else{
			$("#net_chart").info("暂无数据。",true);
		}
		$.radio();
	},false);
}


function clickNetRatio(obj){
	getNetChart(cur_type,$(obj).val());
}

/**
 * 植入综艺豆瓣网评价
 */
function getDoubanChart(type){
	var data = {
			"type" : type,
			"brand": cur_brand,
			"name": $("#keyword").val(),
			"beginDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		};
	ajax("list_program_douban_data4Brand.do",data,function(res){
		if(res.code == 1 && res.list.length > 0){
			var legend = ['评论人数(万)','豆瓣评分(分)'],xdata = [],ydata = [],ys = [];
			$.each(res.list, function(index, item){
				var program = "《" +item.program_name+"》" + ((type == 1 || type == 2) ? ("-" + (res.adMode[item.form-1] != undefined ? res.adMode[item.form-1].val : "")) : '');
				xdata.push(program);
				ydata.push(item.comment_count);
				ys.push(item.score);
				if(index > 8) {
					return false;
				}
			});
			trendBarWithLine(legend,xdata,ydata,ys,'douban_chart');
		}else{
			$("#douban_chart").info("暂无数据。",true);
		}
	},false);
}


/**
 * 产品专题广告投放排名
 */
function getRankList(type){
	var data = {
			"type" : type,
			"name": $("#keyword").val(),
			"beginDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		},html="";
	ajax("list_special_product_rank.do",data,function(res){
		if(res.code == 1 && res.data){
			if(res.data.programRankList.length > 0){
				var list = sortProgramRankList(res.data.programRankList,program_arr);
				$.each(list, function(index, item){
					html += "<tr class='"+(isInArray2(program_arr, item.program_name) ? 'trHover':'')+"'>"+
						"<td>"+item.rank+"</td>"+
						"<td>"+item.program_name+"</td>"+
						"<td>"+item.frequency+"</td>"+
						"<td>"+item.length+"</td>"+
					"</tr>";
				});
				$("#program_rank_list").html(html);
			}else{
				$("#program_rank_list").info("暂无数据。");
			}
			
			if(res.data.brandRankList.length > 0){
				var list2 = sortBrandRankList(res.data.brandRankList);
				html = '';
				$.each(list2, function(index, item){
					html += "<tr class='"+(cur_brand == item.brand ? 'trHover':'')+"'>"+
						"<td>"+item.rank+"</td>"+
						"<td>"+item.brand+"</td>"+
						"<td>"+item.frequency+"</td>"+
						"<td>"+item.length+"</td>"+
					"</tr>";
				});
				$("#brand_rank_list").html(html);
			}else{
				$("#brand_rank_list").info("暂无数据。");
			}
		}else{
			$("#program_rank_list, #brand_rank_list").info("暂无数据。");
		}
	},false);
}

/**
 * 查询品牌植入排名
 * @param oldList 传入全部数组
 * @param curArray 
 * @returns {Array} 返回排名数组
 */
function sortProgramRankList(oldList,curArray){
	var newList = new Array(),top = 0;
	for(var i = 0; i < oldList.length ; i++){
		if(oldList[i].program_name == curArray[0]){
			top = oldList[i].rank;
			break;
		}
	}
	var start = (top - 9  > 0) ? top - 9 : 1;
	var end = (start + 19 > oldList.length) ? oldList.length : start + 19;
	if(end - start + 1 < 20){
		start = start - (20 - 1 - end + start);
	}
	
	for(var i = 0,j = 0;i < oldList.length; i++){
		if(oldList[i].rank >= start && oldList[i].rank <= end){
			newList[j] = oldList[i];
			j ++;
		}
	}
	return newList;
}


function sortBrandRankList(oldList){
	var newList = new Array(),top = 0;
	for(var i = 0; i < oldList.length ; i++){
		if(oldList[i].brand == cur_brand){
			top = oldList[i].rank;
			break;
		}
	}
	var start = (top - 9  > 0) ? top - 9 : 1;
	var end = (start + 19 > oldList.length) ? oldList.length : start + 19;
	if(end - start + 1 < 20){
		start = start - (20 - 1 - end + start);
	}
	for(var i = 0,j = 0;i < oldList.length; i++){
		if(oldList[i].rank >= start && oldList[i].rank <= end){
			newList[j] = oldList[i];
			j ++;
		}
	}
	return newList;
}


function changeTagName(){
	$("span[name='brand_tag']").html("《"+cur_brand+"》");
	$("span[name='type_tag']").html(cur_type.toString().decode(1,"综艺节目",2,"栏目",3,"电视剧",4,"电影",""));
	$("span[name='tv_tag']").html(cur_type.toString().decode(1,"电视综艺",2,"电视栏目",3,"电视剧",4,"植入电影",""));
	$("span[name='net_title1']").html(cur_type.toString().decode(1,"网络综艺节目植入效果一览",2,"网络栏目植入效果一览",3,"电视剧软植效果一览",4,"植入电影点击率一览",""));
	$("span[name='net_title2']").html(cur_type.toString().decode(1,"植入综艺豆瓣网评价",2,"植入栏目豆瓣网评价",3,"电视剧软植豆瓣评价",4,"植入电影豆瓣评分一览",""));
}