$(function() {
	var Record = function() {
		this.baseUrl = "http://api.lolbox.duowan.com/api/v2/player/";
		this.boxServerName = encodeURIComponent($.cookie("boxServerName"));
		this.boxPlayerName = encodeURIComponent($.cookie("boxPlayerName"));
		this.serverName = encodeURIComponent(getURLParam("serverName"));
		this.playerName = encodeURIComponent(getURLParam("playerName"));
		this.historyId = getURLParam("historyId");
		this.gameZone = getURLParam("gameZone");
		this.userId = getURLParam("userId");
		this.boxUserId = $.cookie("boxUserId");
		this.championId = getURLParam("championId");
		this.hero = getURLParam("hero");

		this.favorate = 0;
		this.suffix = "&serverName=" + this.serverName + "&playerName=" + this.playerName;
		if(this.hero) this.suffix += "&hero=" + this.hero;
		this.p = 1;//页码
		this.listData = null;//缓存list列表数据到本地
		this.$loading = $("#loading");
		this.$recordDetail = $("#recordDetail");
		this.$boxContentTemplate = $("#boxContentTemplate");
		this.$boxContent = $(".recent-record__list");
		this.$recordDetail = $("#recordDetail");
		this.$recordDetailTemplate = $("#recordDetailTemplate");
		this.$collect = $("#collect");
		this.$recordTarget = $("#recordTarget");
		this.$body = $("body");
		this.$wanScriptName = $("#wanScriptName");
		this.navStatus = 1; // 默认个人成就

		//饼图默认设置
	    this.highchartsOpts = {
	        chart: {
	            type: 'pie'
	        },
	        plotOptions: {
	            series: {
	                dataLabels: {
	                    enabled: false
	                }
	            }
	        },
	        tooltip: {
	            enabled:false
	        },
	        drilldown: {
	            series: null
	        }
	    };

		this.init();
	};

	Record.prototype = {
		constructor: Record,
		init: function() {
			var self = this;

			self.bindEvents();
			self._getListData();

			$('#modeTabs>li').each(function(item) {
		        var pageName = $(this).data('name');
		        $(this).find('a').attr('href', pageName + '.html?serverName=' + self.serverName + '&playerName=' + self.playerName + '&userId=' + self.userId + '&gameZone=' + self.gameZone);
		    });

	      // 非本人才显示返回按钮
	      if ( this.boxUserId != this.userId ) {
	        $('.common-page__goBack').css('visibility', 'visible');
	      }		    
		},

		// 初始化个人成就饼图
		initCharts: function(data) {
			var self = this;
			var defaultColors = ['#eeeeee', '#9ec8eb'];
		    // 第一张饼图
		    var data1 = parseInt($('.data-charts__1').html(), 10) || 0;
			$('#gankContainer').highcharts($.extend({}, self.highchartsOpts, {
		        colors: defaultColors,
		        series: [{
		            colorByPoint: true,
		            data: [{
		                y: 100 - data1
		            }, {
		                y: data1
		            }]
		        }]
		    }));
		    
			// 第二张饼图
			var data2 = parseInt($('.data-charts__2').html(), 10) || 0;
			$('#joinPartyContainer').highcharts($.extend({}, this.highchartsOpts, {
		        colors: defaultColors,
		        series: [{
		            colorByPoint: true,
		            data: [{
		                y: 100 - data2
		            }, {
		                y: data2
		            }]
		        }]
		    }));

			// // 第三张饼图
			var data3 = parseInt($('.data-charts__3').html(), 10) || 0;
			$('#dragonContainer').highcharts($.extend({}, this.highchartsOpts, {
		        colors: defaultColors,
		        series: [{
		            colorByPoint: true,
		            data: [{
		                y: 100 - data3
		            }, {
		                y: data3
		            }]
		        }]
		    }));
		},

		// 事件绑定
		bindEvents: function() {
			var self = this;

			//我的收藏/TA的收藏r
			this.$collect.on('click', function(e) {
				e.preventDefault();
				var filterData = [];
				for(var i=0,len=self.listData.length;i<len;i++) {
					var item = self.listData[i];
					if(item.collect) {
						filterData.push(item);
					}
				}

				self.listData = filterData;
				var renderArr = filterData.slice(0, 8);

				self.$recordDetail.html('');
				self._renderList(renderArr);
			});

			//分页上一页、下一页点击
			this.$body.delegate(".zj-page .zj-s", "click", function(e) {
				e.preventDefault();
				var page = $(this).attr("data-page");
				if(page == 0 || page == (self.totalPage + 1)) return;

				self.p = page;
				self._renderList(self.listData.slice((page - 1) * 7, page * 7));
			});

			//分页点击去到哪一页
			this.$body.delegate(".zj-page .go-page", "click", function(e) {
				e.preventDefault();
				var page = $(".zj-cur").val();
				if(page <= 0 || page >= (self.totalPage + 1)) return;

				self.p = page;
				self._renderList(self.listData.slice((page - 1) * 7, page * 7));
			});

			//enter
			this.$body.delegate(".zj-page .zj-cur", "keyup", function(e) {
				if(event.keyCode==13) {
					var page = $(this).val();
					if(page <= 0 || page >= (self.totalPage + 1)) return;

					self.p = page;
					self._renderList(self.listData.slice((page - 1) * 8, page * 8));
				}
			});

			//点击左边栏li item时拿到其matchId并获取其对应detail数据
			this.$body.delegate(".l-box .recent-list li", "click", function(e) {
				e.preventDefault();
				var id = $(this).attr("data-id"),
					name = $(this).attr("data-name"),
					enname = $(this).attr("data-enname");

				$(this).addClass("hover").siblings().removeClass("hover");

				self.matchId = id;
				self._getDetailDataDone(id, name, enname);
			});

			//收藏/取消收藏
			this.$body.delegate(".fav-btn", "click", function(e) {
				e.preventDefault();
				e.stopPropagation();

				var _this = this;
				var isAdd = $(this).hasClass("add-fav");
				var action = isAdd ? 'collect' : 'delete';
				var id = $(this).attr("data-id");
				var url = "http://api.lolbox.duowan.com/api/v2/player/" + self.gameZone + "/" + self.userId + "/game/" + action + "/?game_id=" + id;
				
				$.ajax({
		          url: url,
		          type: 'get',
		          dataType: 'jsonp',
		          success: function(result) {
		            if ( result ) {
		              
						if( isAdd ) {
							$( _this ).removeClass("add-fav").addClass("fav").attr("title", "点击删除此收藏");
						} else {
							if( confirm('确认删除此收藏吗？') ) {
								$( _this ).removeClass("fav").addClass("add-fav").attr("title", "点击收藏比赛");
							}
						}
		            }
		          }
		        });
			});

			// 详细战绩&个人成就导航
			this.$body.delegate(".record-nav li", "click", function(e) {
				e.preventDefault();
				e.stopPropagation();

				self.navStatus = $(this).index(); // 记录导航状态
				var tab = $(this).data('tab');
				$(this).addClass('active').siblings().removeClass('active');

				$('.tab-content').hide();
				$('#' + tab).show();

				// 导航点击统计	
				var curIndex = $(this).index();
				var StatId = [
					{'id': 'click/grzj', 'desc': '点击/个人战绩'},
					{'id': 'click/xxzj', 'desc': '点击/详细战绩'}
				];

				try{
					window.external.data_report( StatId[curIndex].id, StatId[curIndex].desc );
				}catch(e){}
			});

	      // 返回上一页
	      $('.common-page__goBack').on('click', function() {
	        window.history.back();
	        return false;
	      });

	      // 刷新按钮
	      $('.common-page__reflash').on('click', function() {
	        location.reload();
	      }); 

	      /*鼠标悬浮在用户头像的弹窗*/ 			
	      $(document).on('mouseenter', '.history-recordTab__userIcon', function() {
	      	self.userRecordDetail();
	      }).on('mouseleave', '.history-recordTab__userIcon', function() {
	      	setTimeout(function() {
	      		var isHover = $('.userRecordDetail').hasClass('hover');
		      	if ( !isHover ) {
		      		$('.userRecordDetail').hide();
		      	}
	      	}, 0.5*1000)

	      });

	      $(document).on('mouseenter', '.userRecordDetail', function() {
	      	$(this).addClass('hover');
	      }).on('mouseleave', '.userRecordDetail', function() {
	      	$(this).removeClass('hover').hide();
	      });

	      // 近期战绩下拉筛选列表 - 导航
	      $(document).on('click', '.recent-nav__input', function() {
	      	$(this).toggleClass('on');
	      	$('.recent-nav__list').toggle();
	      })

	      // 近期战绩下拉筛选列表 - 选项
	      $(document).on('click', '.recent-nav__list li', function(e) {
	      	e.preventDefault();

	      	var key = $(this).find('a').html();
	      	$('.recent-nav__input')
	      		.removeClass('on')
	      		.find('.key').html(key);	      	
	      	$('.recent-nav__list').hide();

	      	self._getListData(key);
	      })	      
		},

		// 获取左侧比赛列表
		_getListData: function(type) {
			var self = this;
			var game_type = {'匹配赛': 3, '排位赛': 4, '大乱斗': 6};
			var url = this.baseUrl + this.gameZone + '/'+this.userId+'/game_recent/';
			
			var args = {};
			self.championId && ( args.champion_id = self.championId );
			game_type[type] && ( args.game_type = game_type[type] );

			$.ajax({
				url: url,
				data: args,
				type: 'GET',
				dataType: 'jsonp',
				success: function(data, status, xhr) {
					if (xhr && xhr.status && xhr.status == 200) {
						var list = data.game_list;
						var renderArr = list.slice(0, 7);

						self.isSelf = data.is_myself;
						self.listData = list;
						self.totalPage = Math.ceil(list.length / 7);
						self._renderList(renderArr);

						//从数组第一个元素中获取到serverName的中文名
						var sn_cn = list[0] ? list[0].game_zone.alias : null;

						var crumbs = sn_cn ? decodeURIComponent(self.playerName) + "(" + sn_cn + ")" : decodeURIComponent(self.playerName);
						self.$recordTarget.attr("href", "playerDetail.html?serverName=" + self.serverName + "&playerName=" + self.playerName + "&userId=" + self.userId + "&gameZone=" + self.gameZone)
							.html(crumbs);
					}
				}
			});
		},

		// 获取玩家比赛详情
		_getDetailData: function(id) {
			var url = this.baseUrl + this.gameZone + "/"+this.userId+"/game/"+ id + '/';

			return $.ajax({
				url: url,
				type: 'GET',
				dataType: 'jsonp'
			});
		},

		_getDetailDataDone: function(id, name, enname) {
			var self = this;
			this.$loading.show();
			self.$recordDetail.hide();

			this._getDetailData(id).done(function(data) {				
				self._renderDetail(data, name, enname);				
				self.$loading.hide();
				self.$recordDetail.show();
			}).fail(function() {
				self.$loading.hide();
				self.$recordDetail.show();
			});			
		},

		/*渲染左侧的战绩列表*/
		_renderList: function(data) {
			var self = this;

			// 左侧列表渲染
			data.totalPage = self.totalPage;
			data.p = self.p;
			data.isSelf = self.isSelf;

			var template = _.template(self.$boxContentTemplate.html());
			self.$boxContent.html(template({
				data: data
			}));

			//	历史战绩对应详情初始化
			if(data && data.length > 0) {
				if ( self.historyId ) {
					getHistoryData(self.historyId);
				}else{
					getHistoryData(0);
				}
			}

			// 获取左侧第N个li历史战绩数据
			function getHistoryData(index) {
				var champion = data[index].champion,
					enname = champion.name,
					name = champion.display_name.concat(champion.title);

				self.matchId = data[index].game_id;
				self._getDetailDataDone(self.matchId, name, enname);
				$('.recent-list li').eq(index).addClass('hover');
			}
		},

		/*渲染历史战绩 - 个人成就*/
		_renderDetail: function(data, name, enname) {			
			var template, self = this;
			if(data.player_game_list) {

				// 模板渲染
				template = _.template(this.$recordDetailTemplate.html());
				this.$recordDetail.html(template({
					data: data
				}));

				// 显示显示默认或记录的导航位置
				$('.record-nav li').eq(self.navStatus).click();

			    // 获取推荐视频
			    self.getRecommendVideo(name, enname);
			    self.initCharts(data.player_game_list[0].player_champion);
			    self.positionRender(data.player_game_list[0]);		
			} else {
				template = "<div class='tip-no-data'><img src='img/clothes-commit-fail.png'><p>由于未知原因，此场比赛消失在遥远的二次元空间中。</p></div>";
				this.$recordDetail.html(template);
			}
		},

		// 获取推荐视频
		getRecommendVideo: function(name, enname, location) {
			$.ajax({
				url: 'http://v.huya.com/?r=api/GetVideoForBox&heroName=' + encodeURIComponent(name) + '&limit=3',
				dataType: 'jsonp',
				success: function(resp) {
					if(resp && resp.videos) {
						var videos = resp.videos,
							templateVideos = _.template($("#videosTemplate").html());

						videos.moreLink = 'http://lol.duowan.com/' + enname;
						
			            $("#videos").html(templateVideos({
			              data: videos
			            }));			            
					}
				}
			});
		},

		// 位置数据渲染
		positionRender: function(data) {
			// 位置计算
			var position_map = {'is_support': '辅助', 'is_adc': '输出', 'is_jungler': '打野'};
			var loseData = data.team_lose.player_champions;
			var allData = data.team_win.player_champions.concat(loseData); //输的和赢的数据合并
			var userId = data.player_champion.player.user_id;

			var key = getPositionKey(allData);
			$('.historyRecord-userInfo__position').html(position_map[key]);

			// 遍历战绩
			function getPositionKey(o) {
				for (var i = 0; i < o.length; i++) {
					var itemUserId = o[i].player.user_id;

					if ( userId == itemUserId ) {
						if ( o[i].is_jungler ) {
							return 'is_jungler';
							break;
						}
						if ( o[i].is_support ) {
							return 'is_support';
							break;
						}
						if ( o[i].is_adc ) {
							return 'is_adc';
							break;
						}												
					}					
				}
			}

			return position_map[key]; 
		},

		/*
		*  @ 历史战绩-个人战绩TAB详细战绩弹窗
		*  @ 注意！！！这里有坑，数据是来自详细战绩弹窗
		*/
		userRecordDetail: function() {
			var self = this;

			var userName   = decodeURIComponent(self.playerName).replace(/(^\s+)|(\s+$)/g,"");
			var recordList = $('.data-layer .layer');

			/*从历史战绩-个人战绩TAB #data-layer列表中拿到弹窗数据*/
			for (var i = 0; i < recordList.length; i++) {
				var listName = $(recordList[i]).find('.tip-user-name').text().replace(/(^\s+)|(\s+$)/g,"");
				if ( userName == listName.replace(/^\s+/,"") ) {
					var dom = $(recordList[i]).html();
					$('.userRecordDetail-con').html(dom);					
					getUserLevel();
					break;
				}
			}

			/*获取用户段位*/
			function getUserLevel() {
				$.ajax({
					url: 'http://api.lolbox.duowan.com/api/v2/player/'+ self.gameZone+'/'+ self.userId+'/',
					dataType: 'jsonp',
					success: function(o) {
				        var data = o && o.player_list && o.player_list[0];
				        var tierRank = data.tier_rank, tierName;

				        if (tierRank && tierRank['tier'] && tierRank['tier']['const'] > 0) {
				          tierName = tierRank['tier']['name_cn'] + ' ' + tierRank['rank']['name'];
				        } else {
				          tierName = '-';
				        }

				        var dom = '<div class="tip-level"></div><div class="tip-topright"><p><em class="zj-zdl zj-s"></em>' + data.box_score + '</p><p class="zj-blue">' + tierName + '</p></div>';
				        $('.userRecordDetail .tip-topright-wrap').html(dom);
				        $('.userRecordDetail').show();
					}
				});
			}
		}
	};

	// URL解析
	function getURLParam(name) {
		var value = location.search.match(new RegExp("[?&]" + name + "=([^&]*)(&?)", "i"));
		return value ? decodeURIComponent(value[1]) : value;
	}

	// 删除字符串空格
    function Trim(str,is_global){
		var result; 
		result = str.replace(/(^\s+)|(\s+$)/g,"");
		if(is_global.toLowerCase()=="g")
		result = result.replace(/\s/g,"");
		return result;
    }
	new Record();
});