/*
  @玩家详细信息 改 - zengfukun@foxmail.com
*/

(function(window) {
  var Personal = function(type) {
    this.gameZone = getURLParam("gameZone");
    this.userId = getURLParam("userId");
    this.urlServerName = getURLParam("serverName");
    this.urlPlayerName = getURLParam("playerName");
    this.serverName = encodeURIComponent(this.urlServerName);
    this.playerName = encodeURIComponent(this.urlPlayerName);

    this.boxUserId = $.cookie("boxUserId");
    this.boxPlayerName = encodeURIComponent($.cookie("boxPlayerName"));
    this.boxPlayerName = encodeURIComponent($.cookie("boxPlayerName"));

    this.type = type;//页面类型
    this.Services = "http://api.lolbox.duowan.com/api/v2/player/";
    this.baseUrl = "http://api.lolbox.duowan.com/api/v2/player/"+ this.gameZone +"/" + this.userId + '/';

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

    this.init();
  };

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

      //获取除开KDA那行的其他数据
      self._getData().done(function(result, status, xhr) {

        // 数据重组
        var isMyself = result.is_myself;
        var followed = result.followed;
        var data = result.player_list[0];
        self.userInfo  = data; // 缓存数据
        data.isSelf = isMyself;
        data.followed = followed;

        // 视图渲染
        self._render(data);
        self.renderByPageType();
        self._moreGameResult();
      });

      $('#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 ( self.boxUserId != self.userId ) {
        $('.common-page__goBack').css('visibility', 'visible');
      }
    },

    // 页面渲染路由
    renderByPageType: function() {
      switch(this.type) {
        case 'tab1': this.renderTab1();break;
        case 'tab2': this.renderTab2();break;
        case 'tab3': this.renderTab3();break;
        case 'tab4': this.renderTab4();break;
      }
    },

    // 战绩总览页面渲染入口
    renderTab1: function() {
      var self = this;

      //近20场比赛
      $('#compositeRateContainer').highcharts($.extend({}, this.highchartsOpts,  {
        colors: ['#eeeeee', '#9ec8eb'],
        series: [{
            colorByPoint: true,
            data: [{
                y: 100 - self.userInfo.stat_perf.kda.average_win_rate
            }, {
                y: self.userInfo.stat_perf.kda.average_win_rate
            }]
        }]
      }));

      var userPosition = parseInt($('.data-userPosition').attr("data-percent"), 10) || 0;
      userPosition = userPosition >= 100 ? 100 : userPosition;
      //最强位置
      $('#jungleAreaContainer').highcharts($.extend({}, this.highchartsOpts, {
        colors: ['#eeeeee','#a1d8b9'],
        series: [{
            colorByPoint: true,
            data: [{
                y: 100 - userPosition
            }, {
                y: userPosition
            }]
        }]
      }));

      // 最近比赛跳转
      $(document).on('click', '#history li', function() {
        var historyId = $(this).index();
        location.href = "historyRecord.html?serverName=" + self.serverName + "&playerName=" + self.playerName + "&userId=" + self.userId + "&gameZone=" + self.gameZone + '&historyId=' + historyId;
      })
    },

    // 历史战绩页面渲染入口
    renderTab2: function() {},

    // 擅长领域页面渲染入口
    renderTab3: function() {

      var self = this;

      var defaultColors = ['#eeeeee', '#9ec8eb'];
      var navLists = ['打野','输出','辅助'];

      // TAB切换
      $('.content-nav li').on('click', function(e) {
        e.preventDefault();
        var id = $(this).data('id');
        renderByNav(id);
        $(this).addClass('active').siblings().removeClass('active');
      });

      //初始化第一个TAB
      renderByNav(0); 

      // 内容渲染
      function renderByNav(index) {
        var type = decodeURI(navLists[index]);

        //获取视频数据
        getVideosData(type, 4).done(function(resp) {
          if(resp && resp.videos) {

            // 更多推荐视频路由
            var videos = resp.videos, moreLink;

            switch(index) {
              case 0: moreLink = 'http://v.huya.com/lol/jiaoxue/daye.html';break;
              case 1: moreLink = 'http://v.huya.com/t/shuchushipin.html';break;
              case 2: moreLink = 'http://v.huya.com/t/fuzhushipin.html';break;
            };

            videos.moreLink = moreLink;

            // 推荐视频渲染
            var templateVideos = _.template($("#detailVideosTemp").html());
            $("#detailVideos").html(templateVideos({
              data: videos
            }));                       
          }
        });

        // 获取区间数据
        self.getUserRank().done(function(o) {
          if ( o.results[0] ) {
            self.ZoneData = o.results;
            renderMainModule(index); // 依赖区间数据
          }                     
        })        
      }

      // 擅长领域中间部分数据重组和渲染
      function renderMainModule(index) {
        // 用户段位
        var duanwei = parseInt($('.userDuanwei').attr('data-duanwei'), 10);

        // 算法表
        var title = [
            '个人参团数/团队团战数',     //参团率 
            '小龙击杀数量/小龙复活次数', //大小龙率
            '支援成功次数/支援次数',     //GANK率
            '个人存活时间/游戏持续时间', //存活率
            '个人输出量/团队总体输出量', //输出率
            '个人插（排）眼数/团队总（插）眼数',         //插/反眼率
        ];

        // 数据构造
        var positionEname = ['jungler','adc','support'];
        var Position = self.userInfo.stat_perf.position_perf;

        var Database = {

          // 饼图名字关系表
          t_chart__name: [
            {'name1': '参团率', 'name2': '小龙率', 'name3': 'GANK率', 'title1': title[0], 'title2': title[1], 'title3': title[2]},
            {'name1': '存活率', 'name2': '参团率', 'name3': '输出率', 'title1': title[3], 'title2': title[0], 'title3': title[4]},
            {'name1': '存活率', 'name2': '参团率', 'name3': '视野率', 'title1': title[3], 'title2': title[0], 'title3': title[5]}
          ],

          // 概率关系表
          t_chart_rate: [
            {'rate1': Position.rate_assists_jungler, 'rate2': Position.rate_dragon_killed_jungler || 0, 'rate3': Position.rate_gank_jungler},
            {'rate1': Position.rate_keep_alive_adc, 'rate2': Position.rate_assists_adc, 'rate3': Position.rate_damage_adc},
            {'rate1': Position.rate_keep_alive_support, 'rate2': Position.rate_assists_support, 'rate3': Position.rate_vision_support}
          ],

          // 区间概率
          zone: [
            {'zone1': self.ZoneData[duanwei]['rate_assists_jungler'], 'zone2': self.ZoneData[duanwei]['rate_dragon_killed_jungler'], 'zone3': self.ZoneData[duanwei]['rate_gank_jungler']},
            {'zone1': self.ZoneData[duanwei]['rate_keep_alive_adc'], 'zone2': self.ZoneData[duanwei]['rate_assists_adc'], 'zone3': self.ZoneData[duanwei]['rate_damage_adc']},
            {'zone1': self.ZoneData[duanwei]['rate_keep_alive_support'], 'zone2': self.ZoneData[duanwei]['rate_assists_support'], 'zone3': self.ZoneData[duanwei]['rate_vision_support']}
          ],

          // 列表标题关系表
          t_list__name: ['打野', '输出', '辅助'],

          // 底部场均信号沟通等数据
          t_bottom: [
            {signal: Position.signals_sent_jungler, eye: Position.rate_vision_jungler || 0, kill: Position.neutral_minions_killed_jungler, tower: Position.turrets_killed_jungler}, //打野
            {signal: Position.signals_sent_adc, eye: Position.rate_vision_adc || 0, kill: Position.neutral_minions_killed_adc, tower: Position.turrets_killed_adc}, //输出
            {signal: Position.signals_sent_support, eye: Position.rate_vision_support || 0, kill: Position.neutral_minions_killed_support, tower: Position.turrets_killed_support} //辅助
          ]
        }

        // 渲染
        var templateMain = _.template($("#detailMainTemp").html());
        $("#detailMain").html(templateMain({
          data: {
            // 三个概率图
            chart1: {
              name: Database.t_chart__name[index]['name1'],
              rate: Database.t_chart_rate[index]['rate1'],
              title: Database.t_chart__name[index]['title1']
            },
            chart2: {
              name: Database.t_chart__name[index]['name2'],
              rate: Database.t_chart_rate[index]['rate2'],
              title: Database.t_chart__name[index]['title2']
            },
            chart3: {
              name: Database.t_chart__name[index]['name3'],
              rate: Database.t_chart_rate[index]['rate3'],
              title: Database.t_chart__name[index]['title3']
            },

            // 常在打野、输出、辅助列表
            list: {
              title: Database.t_list__name[index],
              data: self.userInfo.stat_perf.position_champ[positionEname[index]]
            },

            // 底部场均信号沟通等数据
            bottom: Database.t_bottom[index],
            zone: Database.zone[index],
            All: Position
          }
        }));

        // 渲染饼图
        renderEcharts({
          rate1: Database.t_chart_rate[index]['rate1'],
          rate2: Database.t_chart_rate[index]['rate2'],
          rate3: Database.t_chart_rate[index]['rate3']
        }); 
      }

      // 渲染饼图
      function renderEcharts(rateData) {
        $('#gankContainer').highcharts($.extend({}, self.highchartsOpts, {
          colors: defaultColors,
          series: [{
              colorByPoint: true,
              data: [{
                  y: 100 - rateData.rate1
              }, {
                  y: rateData.rate1
              }]
          }]
        }));
        $('#joinPartyContainer').highcharts($.extend({}, self.highchartsOpts, {
          colors: ['#eeeeee', '#f7cebe'],
          series: [{
              colorByPoint: true,
              data: [{
                  y: 100 - rateData.rate2
              }, {
                  y: rateData.rate2
              }]
          }]
        }));
        $('#dragonContainer').highcharts($.extend({}, self.highchartsOpts, {
          colors: defaultColors,
          series: [{
              colorByPoint: true,
              data: [{
                  y: 100 - rateData.rate3
              }, {
                  y: rateData.rate3
              }]
          }]
        })); 
      }

      // 获取推荐视频
      function getVideosData(type, limit) {
        var url = 'http://v.huya.com/?r=api/GetVideoForBox&location=' + type + '&limit=' + limit;

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

    // 个人成就页面渲染入口
    renderTab4: function() {
      var self = this;

      // 个人成就拆分逻辑加载
      $.getScript( achievementJS, function() {
        App.highchartsOpts = self.highchartsOpts;
        App.defaultColors = ['#eeeeee', '#9ec8eb'];
      });
    },

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

      $("body").delegate(".handles .copy", "click", function(e) {
        event.preventDefault();

        if (window.clipboardData && window.clipboardData.setData !== undefined) {
            var achievement = $(this).parent().find(".copy-text").text();
            window.clipboardData.setData('Text', achievement);
            alert('复制成功');
        }
      });

      $("body").delegate(".combat-explain,.handles a", 'click', function(e) {
        var stat = $(this).attr("stat-sign") || '',
          yaDxinesc = $(this).attr("stat-desc") || '',
          yaCode = "click/"+stat;
        try {
          window.external.data_report(yaCode, yaDxinesc);
        } catch(err) {}
      });

      $("body").delegate('.blacklist', 'click', function(e) {
        e.preventDefault();
        if($(this).hasClass('hide-list')) {
          $(this).removeClass('hide-list').html('隐藏拉黑');
          $('.blacklist-content2').show();
        } else{
          $(this).addClass('hide-list').html('拉黑');
          $('.blacklist-content2').hide();
        }
      });

      $("body").on('mouseenter', '.table-history__lastseason .toggle-s4-s5', function(e) {
        $('.s4-s5').show();
        $('.table-arrow').addClass('up');
      }).on('mouseleave', '.table-history', function() {
        $('.s4-s5').hide();
        $('.table-arrow').removeClass('up');
      });;

      $("#screenshot").on("click", function(e) {
        $('.share').removeClass('hover');
          setTimeout(function () {
              window.location.href = 'lolboxphoto://'+data.game_zone.server_name+'_'+data.pn+'_玩家详情';
          }, 200);
      });

      /* 关注鼠标悬浮显示 */
      $(document).on('mouseenter', '.name-info .name', function(event) {
        $('.attention').css('display', 'block');
      }).on('mouseleave', '.name-info .name', function(event) {
        setTimeout(function() {
          var isHover = $('.attention').hasClass('hover');
          
          if ( !isHover ) {
            $('.attention').hide();
          }
        },1.5*1000);
      })

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

      //关注、取消关注
      $("body").delegate(".attention", "click", function(e) {
        e.preventDefault();

        if(!self.boxUserId) {
          alert('非法操作，请至少登陆一次游戏！');
          return;
        }

        var type = $(this).attr("data-action"), that = this;
        var action = type == 'addFocus' ? 'follow' : 'unfollow';
        var url = "http://api.lolbox.duowan.com/api/v2/player/"+this.gameZone+"/" + self.boxUserId + '/'+action+'/?user_id='+this.userId;

        $.ajax({
          url: url,
          type: 'get',
          dataType: 'jsonp',
          success: function(result) {
            if (result) {
              if(type == "addFocus") {
                  $(that).addClass("already").attr("data-action", "removeFocus")
                  .find("span").html("已关注");
              } else {
                $(that).removeClass("already").attr("data-action", "addFocus")
                  .find("span").html("关注");
              }
            }
          }
        });
      });

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

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

    // 获取个人详细信息
    _getData: function() {
      var url = this.baseUrl;

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

    _getKDAData: function() {
      var url = this.baseUrl + "?_do=personal/positionhonorkda&serverName=" + this.serverName + "&playerName=" + this.playerName;

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

    // 数据渲染入口
    _render: function(data) {
      var self = this;   
      self.userInfo = data; // 数据备份
      self.playerId = data.user_id;

      // 个人信息数据渲染
      self._renderPersonalInfo(data);

      //战绩总览数据渲染
      if( self.type == 'tab1' ) {
        var template = _.template($("#echarts-tpl").html());
        $(".fighting-history__view").html(template({
          data: data
        }));    

        try{
          self._renderHistory(data);
          self._renderKDA(data);          
        }catch(e){}

        // 广告接入
        $('.record-ad__wrap').html($('.ad-module a'));
      }

      // 内容显示
      $(".box-bd").show();
    },

    // 个人信息通用模块渲染
    _renderPersonalInfo: function(data) {
      var href = "historyRecord.html?serverName=" + this.serverName + "&playerName=" + this.playerName + "&userId=" + this.userId + "&gameZone=" + this.gameZone;
      var attentionUrl = "http://lolbox.duowan.com/webApi.php?serverName=" + this.serverName + "&playerName=" + this.playerName + "&targetServerName=" + this.boxServerName + "&targetPlayerName=" + this.boxPlayerName + "&action=";

      //储存个人信息
      data.global = {};
      //二维码url
      data.global.qrcodeUrl = "http://lolbox.duowan.com/qrcode.php?openmode=barcode&amp;serverName=" + this.serverName + "&amp;playerName=" + this.playerName;

      //头像url，点击去到战绩页面
      data.global.href = href;
      //关注/取消关注接口baseUrl
      data.global.aUrl = attentionUrl;

      $("#currentNav").html(data.pn+"("+data.game_zone.alias+")").attr("href", location.href);

      // 头部个人信息模板渲染
      var template = _.template($("#personalInfoTemp").html());
      $("#personalInfo").html(template({
        data: data
      }));

      // 称号图片地址
      if ( data.honor_title ) {
        var placeholder = $('.userMedal').attr('src');
        var src = placeholder.replace('placeholder', ['a_level_', data.honor_title].join(''));
        $('.userMedal').attr('src', src);
      }      
    },

    _renderKDA: function(data) {
      this._renderDaYe(data);
      this._renderKDADetail(data);
    },

    _renderDaYe: function(data) {
      var colorsArr = ['#fbb28f','#cea9d7','#fa9f9f','#80c989','#9dc7eb'], setColors = [], setData = [], i=0;
      var statPosition = data.stat_position;//英雄位置统计

      if(statPosition) {
        for(var key in statPosition) {
          var value = statPosition[key];

          if(key != 'total_game' && value != 0) {
            var keyTxt = '';

            switch(key) {
              case 'adc': keyTxt = 'ADC';break;
              case 'jungler': keyTxt = '打野';break;
              case 'mid': keyTxt = '中单';break;
              case 'support': keyTxt = '辅助';break;
              case 'top': keyTxt = '上单';break;
            };

            setData.push({
              value: value,
              label: keyTxt
            });

            setColors.push(colorsArr[i++]);
          }
        }
      }

      $("body").delegate("#daYe, .kda-li, .kill-li", "mouseenter", function(e) {
        e.preventDefault();

        if($(this).hasClass("da-ye")) {
          $(".daye-hover").show();
        } else if($(this).hasClass("kda-li")) {
          $(".kda-hover").show();
        } else {
          $(".kill-hover").show();
        }
        
      });

      $("body").delegate("#daYe, .kda-li, .kill-li", "mouseleave", function(e) {
        e.preventDefault();

        if($(this).hasClass("da-ye")) {
          $(".daye-hover").hide();
        } else if($(this).hasClass("kda-li")) {
          $(".kda-hover").hide();
        } else {
          $(".kill-hover").hide();
        }
      });

      //近7天英雄使用次数
      $("#heroTime").html(statPosition.total_game);
    },

    _renderKDADetail: function(data) {
      var template = _.template($("#kdaTemp").html());
      $("#kda").html(template({
        data: data
      }));
    },

    _renderHistory: function(data) {
      var nextFirstWinTime = data.timestamp_until_next_first_win_bonus;
      var currentTime = new Date().getTime();

      $(".f-time").html('首胜可用');
      $("#firstMsg").addClass('active-status');

      if ( currentTime < nextFirstWinTime*1000 ) {
        $("#firstMsg").removeClass('active-status');   

        countDown(nextFirstWinTime, '.f-time');
      }        
      
      $("#firstMsg").on('mouseenter', function(e) {
        $('.first-win-hover').show();
      }).on('mouseleave', function(e) {
        $('.first-win-hover').hide();
      });
      
      // 倒计时方法
      function countDown(times, target) {
        var times = Math.ceil(parseInt(times)*1000);

        var timerId = setInterval(function() {
          if ( times <= 0 ) {
            $(target).html('首胜可用');
            $("#firstMsg").addClass('active-status');
            return;
          }

          var h = parseInt(times % 86400 / 3600),
              m = parseInt(times % 86400 % 3600 / 60),
              s = parseInt(times % 86400 % 3600 % 60 % 60);
              s = s < 10 ? '0' + s : s;

          $(target).html([h,':',m,':',s].join(''));
          times--;
        }, 1*1000);
      }

      //最近战绩
      var template = _.template($("#historyTemp").html());
      var data = data.game_recent_list;

      setTimeout(function() {
        $("#history").html(template({
          data: data
        })).niceScroll({
          cursorcolor: "#D9D9D9",
          cursorwidth: "8",
          cursoropacitymin: 1,
          cursorborder: 'none'
        });
      });
    },

    _moreGameResult: function() {
      var href = "historyRecord.html?serverName=" + this.urlServerName + "&playerName=" + this.urlPlayerName+'&userId='+this.userId+'&gameZone='+this.gameZone;
      $("#moreGameResult").attr("href", href);
    },

    // 获取【擅长领域】TAB区间数据
    getUserRank: function() {
      var self = this;

      return $.ajax({
        url: self.Services + self.gameZone + '/perf_ave/',
        dataType: 'jsonp'
      });      
    }
  };

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

  function getCookie(cookieName) {
      var cookieString = document.cookie;
      var start = cookieString.indexOf(cookieName + '=');
      // 加上等号的原因是避免在某些 Cookie 的值里有
      // 与 cookieName 一样的字符串。
      if (start == -1) // 找不到
          return null;
      start += cookieName.length + 1;
      var end = cookieString.indexOf(';', start);
      if (end == -1)
          return cookieString.substring(start);
      return   cookieString.substring(start, end);
  }

  function beenBlockedTimes(action) {
    var boxPlayerName = decodeURI(getCookie('boxPlayerName'));
    var boxServerName = decodeURI(getCookie('boxServerName'));
    $.ajax({
        url: "http://lolbox.duowan.com/webApi.php",
        data: {serverName: boxServerName, playerName: boxPlayerName, action: action},
        cache: false,
        success: function (msg) {
            if (msg == 1) {
                location.reload();
            } else if (msg == -1) {
                alert('非法操作，请至少登陆一次游戏！');
            }
        },
        error: function () {
        }
    });
  }

  window.Personal = Personal;
})(window);
