$(function(){
	// 一级行业select控件初始化	 
    var firstIndSelect = $('select[name="firstInd"]').select2({
    	placeholder: "请输入一级行业",
    	allowClear: true,
    	width:'286px',
    	ajax:{
    		url: _PUBLIC_ +'ad-select/top_category_by_type.do',
    		dataType:'json',
    		quietMillis:100,
    		data:function(params){
    			return {
    				name : params.term,
    				type : 0, //栏目管理
    				pageNo : params.page || 1,
    				pageSize : 20
    			}
    		},
    		processResults: function (data, params) {
    			params.page = params.page || 1;
    			return {
    		        results: data.results,
    		        pagination: {
    		          more: (params.page * 20) < data.total
    		        }
    		    };
    		},
    		cache: true
    	}
    });
    	
    //解绑二级行业select控件初始化
    $('select[name="firstInd"]').live('change',function(){
    	$('select[name="secondInd"]').html('<option value=""></option>');
    });
    		
    // 二级行业select控件初始化	 
    var secondIndSelect = $('select[name="secondInd"]').select2({
    	placeholder: "请输入二级行业",
    	allowClear: true,
    	width:'286px',
    	ajax:{
    		url: _PUBLIC_ +'ad-select/second_category_by_type.do',
    		dataType:'json',
    		quietMillis:100,
    		data:function(params){
    			return {
    				name : params.term,
    				type : 0, //栏目管理,
    				parentName : $('#firstInd').val(), 
    				pageNo : params.page || 1,
    				pageSize : 20
    			}
    		},
    		processResults: function (data, params) {
    			params.page = params.page || 1;
    			return {
    		        results: data.results,
    		        pagination: {
    		          more: (params.page * 20) < data.total
    		        }
    		    };
    		},
    		cache: true
    	}
    });

    $('select[name="showEnv"]').select2({
        placeholder: "请选择播出环境",
        allowClear: true,
        width: '286px'
    });

    // 播出媒体
	var mediaNameSelect = $('select[name="mediaName"]').select2({
		placeholder: "请输入播出媒体",
		allowClear: true,
		width:'286px',
		ajax:{
			url: _PUBLIC_ +'ad-media/select/list.do',
			dataType:'json',
			quietMillis:100,
			data:function(params){
				return {
					name : params.term,
					pageNo : params.page || 1,
					pageSize : 20
				}
			},
			processResults: function (data, params) {
				params.page = params.page || 1;
				return {
			        results: data.results,
			        pagination: {
			          more: (params.page * 20) < data.total
			        }
			    };
			},
			cache: true
		}
	});
    
    $('select[name="type"]').select2({
        placeholder: "请选择类型",
        allowClear: true,
        width: '100px'
    });
});

var cur_brand = '',cur_secondInd = '',cur_type = '' , cur_type_name= '';

function getBrandDetail(){
	// 媒体分布
	getMediaChartsData();
	// 广告分布
	getTVChartsData();
    // 二级行业品牌频次分布
	getSecondIndChartsFrequencyData();
	// 二级行业品牌时长分布
	getSecondIndChartsDurationData();
	// 产品T30排序分布
    getProductRankList();
    // 栏目T30排序分布
    getPlatformRankList();
    // 修改产品名称
	changeTagName();
}

  // 获取对标对象
function itemCheck(o){
	var item = $("input[name='item']:checked"), ids = [] , productNameList = [],productTypeList = [];
	if(item.length > 3){
		alert("最多选择三个对标产品。");
		$(o).attr("checked", false);
		$.checkbox();
		return false;
	}
	item.each(function(){
	    var type = $(this).attr('data-type');
		var data = $(this).val().split("_");
		ids.push(data[0]);
		productTypeList.push(type);
		productNameList.push(data[1]);
	});
	if(productTypeList.length > 0 && (new Set(productTypeList)).size != 1){
        alert("请选择同是产品或栏目对标分析。");
        $(o).attr("checked", false);
		$.checkbox();
		return false;
    }
	if((new Set(productNameList)).size != productNameList.length){
        alert("已存在，请选择不同的对标产品。");
        $(o).attr("checked", false);
		$.checkbox();
		return false;
    }
	$.cookie.set("benchCheckNum",ids.join(","));
}

 // 对标
function setBenchmark(){
	var item = $("input[name='item']:checked"), ids = [], productNameList = [], productTypeList = [];
	if(item.length <= 0){
		alert("请至少选择一个对标的产品。");
		return false;
	}
	if(item.length > 3){
		alert("最多选择三个对标的产品。");
		return false;
	}
	item.each(function(){
		var type = $(this).attr('data-type');
		var data = $(this).val().split("_");
		ids.push(data[0]);
	    productTypeList.push(type);
		productNameList.push(data[1]);
	});
	if(productTypeList.length > 0 && (new Set(productTypeList)).size != 1){
        alert("请选择同是产品或栏目对标分析。");
		return false;
    }
	if((new Set(productNameList)).size != productNameList.length){
        alert("已存在，请选择不同的对标产品。");
		return false;
    }
	window.open("benchmarking.do?type="+productTypeList[0]+"&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);
}

// 获取选中产品--并显示分析
function changeBrand(brand,secondInd,type){
	cur_brand = brand;
	cur_secondInd = secondInd;
	cur_type = type;
	cur_type_name = (type == '0' ? "产品" : "栏目");
	getBrandDetail();
}


// 一级行业select控件初始化	 
var firstIndSelect = $('select[name="firstInd"]').select2({
	placeholder: "请输入一级行业",
	allowClear: true,
	width:'286px',
	ajax:{
		url: _PUBLIC_ +'ad-select/top_category_by_type.do',
		dataType:'json',
		quietMillis:100,
		data:function(params){
			return {
				name : params.term,
				type : 0, //栏目管理
				pageNo : params.page || 1,
				pageSize : 20
			}
		},
		processResults: function (data, params) {
			params.page = params.page || 1;
			return {
		        results: data.results,
		        pagination: {
		          more: (params.page * 20) < data.total
		        }
		    };
		},
		cache: true
	}
});
	
//解绑二级行业select控件初始化
$('select[name="firstInd"]').live('change',function(){
	$('select[name="secondInd"]').html('<option value=""></option>');
});
		
// 二级行业select控件初始化	 
var secondIndSelect = $('select[name="secondInd"]').select2({
	placeholder: "请输入二级行业",
	allowClear: true,
	width:'286px',
	ajax:{
		url: _PUBLIC_ +'ad-select/second_category_by_type.do',
		dataType:'json',
		quietMillis:100,
		data:function(params){
			return {
				name : params.term,
				type : 0, //栏目管理,
				parentName : $('#firstInd').val(), 
				pageNo : params.page || 1,
				pageSize : 20
			}
		},
		processResults: function (data, params) {
			params.page = params.page || 1;
			return {
		        results: data.results,
		        pagination: {
		          more: (params.page * 20) < data.total
		        }
		    };
		},
		cache: true
	}
});

// 专题广告电视投放一览
function getBrandAnalysisList(page){
	page = page || 1;
	var pageSize = "10", data = {
		"pageNo": page,
		"pageSize": pageSize,
		"startDate": $("#start_time").val(),
		"endDate": $("#end_time").val(),
		"type": $("#type").val(),
		"keyword": $.trim($("#keyword").val()),
		"mediaName": $("#mediaName").val(),
		"showEnv": $("#showEnv").val(),
	    "firstInd":$("#firstInd").val(),
		"secondInd":$("#secondInd").val(),
	}, html = "";
	$("#brand_analysis_page, #brand_analysis_list").empty();
	ajax("ajax_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.productName;
					cur_secondInd = item.secondInd;
					cur_type = item.type;
				}
				html += "<tr data-brand='"+item.productName+"' data-second_ind='"+item.secondInd+"' data-type='"+item.type+"'>"+
					"<td>"+$.orderNum(page,pageSize,index)+"</td>"+
					"<td>"+item.mediaName+"</td>"+
                    "<td>"+item.showTime+"</td>"+
					"<td>"+item.showDate+"</td>"+
					"<td>"+item.showEnvMsg+"</td>"+								
					"<td><a class='blue' href=javascript:void(0); onclick=toTheatreAnalysis('"+item.tvName+"') >"+item.tvName+"</a></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.id) != -1 ? 'checked':'')+" value='"+item.id+"_"+item.productName+"' data-type='"+item.type+"' /><label></label></td>"+
				"</tr>";
			});
			$("#brand_analysis_list").html(html);
			$('#brand_analysis_count').html(res.data.total);
			$.radio();
			$.checkbox();
			var newpage = new createPage(res.data.total,page,pageSize,3,"getBrandAnalysisList");
			$("#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"),$(this).closest("tr").data("second_ind"),$(this).closest("tr").data("type"));
			});
			$("#brand_analysis_list>tr:eq(0)>td:eq(1)").click();
			
		}else{
			$("#brand_analysis_list").info("暂无数据。");
			$("#frequency_pie,#length_pie").info("暂无数据。", true);
			$("#rating_35,#rating_29").info("暂无数据。", true);
			$("#net_chart,#douban_chart").info("暂无数据。", true);
			$("span[name='brand_tag']").html('“”');
			$("span[name='secondInd_tag']").html('“”');
			$('#brand_analysis_count').html(0);
		    // 产品T30排序分布
            getProductRankList();
            // 栏目T30排序分布
            getPlatformRankList();
		}
	});
}

// 媒体分布
function getMediaChartsData(){
	var data = {
			"type" : cur_type,
			"productName": cur_brand,
			"startDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		};
	ajax("media_dist.do",data,function(res){
		if(res.code == 1 && res.data.length > 0){
			
			var legend= [], series = [],xdata = [],ydata = [];
			var xOther = 0, yOther = 0;

			data1 = res.data.sort(function(a,b){
                return b.duration-a.duration;
            });

			$.each(data1, function(index, item){
				if (index >= 10){			
					yOther += item.duration;
					return true;
				}
			    legend.push(item.name);
                // 时长
                var lv2 = {
                    value: item.duration,
                    name : item.name
                };
                ydata.push(lv2);
			});

            data2 = res.data.sort(function(a,b){
                return b.total-a.total;
            });
			$.each(data2, function(index, item){
                if (index >= 10){
                    xOther += item.total;               
                    return true;
                }
                legend.push(item.name);
                // 频次
                var lv1 = {
                    value: item.total,
                    name : item.name
                };
                xdata.push(lv1);
            });

			// 其它
			if (xOther > 0){
				var temp = {
					value: xOther,
					name : '其它'
				};
				xdata.push(temp);
			}
			if (yOther > 0){
				var temp = {
					value: yOther,
					name : '其它'
				};
				ydata.push(temp);
			}
			drawPie("频次分布",xdata,'frequency_pie');
			drawPie("时长分布",ydata,'length_pie');
		}else{
			$("#frequency_pie,#length_pie").info("暂无数据。", true);
		}
	},false);
}


//电视剧分布
function getTVChartsData(){
	var data = {
			"type" : cur_type,
			"productName": cur_brand,
			"startDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		};
	ajax("tv_dist.do",data,function(res){
		if(res.code == 1 && res.data.length > 0){
            var legend= [], series = [],xdata = [],ydata = [];
			var xOther = 0, yOther = 0;

			data1 = res.data.sort(function(a,b){
                return b.duration-a.duration;
            });

			$.each(data1, function(index, item){
				if (index >= 10){			
					yOther += item.duration;
					return true;
				}
			    legend.push(item.name);
                // 时长
                var lv2 = {
                    value: item.duration,
                    name : item.name
                };
                ydata.push(lv2);
			});

            data2 = res.data.sort(function(a,b){
                return b.total-a.total;
            });
			$.each(data2, function(index, item){
                if (index >= 10){
                    xOther += item.total;               
                    return true;
                }
                legend.push(item.name);
                // 频次
                var lv1 = {
                    value: item.total,
                    name : item.name
                };
                xdata.push(lv1);
            });

			// 其它
			if (xOther > 0){
				var temp = {
					value: xOther,
					name : '其它'
				};
				xdata.push(temp);
			}
			if (yOther > 0){
				var temp = {
					value: yOther,
					name : '其它'
				};
				ydata.push(temp);
			}
			drawPie("频次分布",xdata,'rating_35');
			drawPie("时长分布",ydata,'rating_29');
		}else{
			$("#rating_35,#rating_29").info("暂无数据。", true);
		}
	},false);
}

//二级行业品牌频次分布TOP10
function getSecondIndChartsFrequencyData(){
	var data = {
			"type" : cur_type,
			"launch": 0, // 频次
			"secondInd": cur_secondInd,
			"startDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		};
	ajax("second_ind_dist.do",data,function(res){
		if(res.code == 1 && res.data.length > 0){
			var series_frequency = [], xOther = 0;				
			$.each(res.data, function(index, item){
				if (index >= 10){			
					xOther += item.total;
					return true;
				}
				var lv1 = {
					value: item.total, 				
				    name : item.name
				};
				series_frequency.push(lv1);
			});
		    // 其它
			if (xOther > 0){
				var temp = {
					value: xOther,
					name : '其它'
				};
				series_frequency.push(temp);
			}
			drawPie("频次分布",series_frequency,'net_chart');		
		}else{
			$("#net_chart").info("暂无数据。", true);
		}
	},false);
}

//二级行业品牌时长分布TOP10
function getSecondIndChartsDurationData(){
	var data = {
			"type" : cur_type,
			"launch": 1, // 时长
			"secondInd": cur_secondInd,
			"startDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		};
	ajax("second_ind_dist.do",data,function(res){
		if(res.code == 1 && res.data.length > 0){
		    var series_length = [], xOther = 0;
			$.each(res.data, function(index, item){
				if (index >= 10){			
					xOther += item.duration;
					return true;
				}
				var lv2 = {
					value:item.duration, 
					name:item.name
				};
				series_length.push(lv2);
			});	
			// 其它
			if (xOther > 0){
				var temp = {
					value: xOther,
					name : '其它'
				};
				series_length.push(temp);
			}
			drawPie("时长分布",series_length,'douban_chart');
		}else{
			$("#douban_chart").info("暂无数据。", true);
		}
	},false);
}

/**
 * 产品专题广告投放排名
 */
function getProductRankList(){
	var data = {
			"type" : 0,
			"startDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		},html="";
	    ajax("product_rank.do",data,function(res){
		if(res.code == 1 && res.data){
			if(res.data.length > 0){
				$.each(res.data, function(index, item){
					html += "<tr class='"+(cur_brand == item.productName && cur_secondInd == item.secondInd ? 'trHover':'')+"'>"+
						"<td>"+(index+1)+"</td>"+
						"<td>"+item.productName+"</td>"+
						"<td>"+item.secondInd+"</td>"+
						"<td>"+item.frequency+"</td>"+
						"<td>"+item.duration+"</td>"+
					"</tr>";
				});
				$("#program_rank_list").html(html);
			}else{
				$("#program_rank_list").info("暂无数据。");
			}
		}
	},false);
}

/**
 *   栏目专题广告投放排名
 */
function getPlatformRankList(){
	var data = {
			"type" : 1,
			"startDate": $("#start_time").val(),
			"endDate": $("#end_time").val()
		},html="";
	    ajax("product_rank.do",data,function(res){
		if(res.code == 1 && res.data){
			if(res.data.length > 0){
				$.each(res.data, function(index, item){
					html += "<tr class='"+(cur_brand == item.productName && cur_secondInd == item.secondInd ? 'trHover':'')+"'>"+
						"<td>"+(index+1)+"</td>"+
						"<td>"+item.productName+"</td>"+
						"<td>"+item.secondInd+"</td>"+
						"<td>"+item.frequency+"</td>"+
						"<td>"+item.duration+"</td>"+
					"</tr>";
				});
				$("#brand_rank_list").html(html);
			}else{
				$("#brand_rank_list").info("暂无数据。");
			}
		}
	},false);
}

// 扇形图显示
function drawPie(title,series, divId){
option = {
    tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    series: [
        {
			color: ['#1890FF','#F6BD16','#E8684A','#6DC8EC','#9270CA','#FF9D4D','#269A99','#73A0FA','#5AD8A6','#5D7092','#6DC8EC','#9270CA','#FF9D4D','#269A99'],
            name:title,
            type: 'pie',
            radius: '75%',
            center: ['50%', '50%'],
            data: series,
            emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
            }
        }
    ]
};

var myChart = echarts.init(document.getElementById(divId));
document.getElementById(divId).setAttribute('_echarts_instance_', '')
myChart.clear();
myChart.setOption(option);
}

// 修改产品名称
function changeTagName(){
	$("span[name='type_tag']").html(cur_type_name);
	$("span[name='brand_tag']").html('“'+cur_brand+'”');
	$("span[name='secondInd_tag']").html('“'+cur_secondInd+'”');
}

