$(function() {
  //获取url里面参数
  var urlServerName = getURLParam("serverName");
  var urlPlayerName = getURLParam("playerName");
  var gameZone = getURLParam("gameZone");
  var userId = getURLParam("userId");
  var serverNameParam = encodeURIComponent(urlServerName);
  var playerNameParam = encodeURIComponent(urlPlayerName);

  var Personal = function() {
    this.baseUrl = "http://api.lolbox.duowan.com/api/v2/player/"+gameZone+"/" + userId + '/';
    this.serverName = serverNameParam;
    this.playerName = playerNameParam;
    this.boxUserId = $.cookie("boxUserId");
    this.boxPlayerName = encodeURIComponent($.cookie("boxPlayerName"));
    this.boxPlayerName = encodeURIComponent($.cookie("boxPlayerName"));

    //由于常用英雄浮窗的数据由hover调接口，改为直接从主接口中获取，所以做一下缓存.
    this.commonHeroHoverData = [];
  };

  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 () {
        }
    });
  }

  Personal.prototype = {
    constructor: Personal,
    init: function() {
      var that = this;
      this._moreGameResult();
      this._moreCommonHero();
      //获取除开KDA那行的其他数据
      this._getData().done(function(result, status, xhr) {
        var isMyself = result.is_myself;
        var followed = result.followed;
        var data = result.player_list[0];
        data.isSelf = isMyself;
        data.followed = followed;

        that._render(data);
      }).fail(function() {});

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

        event.preventDefault();
      });

      $("body").delegate( '.black-eye', 'mouseenter', function(e) {
          e.preventDefault();
          $(".black-label").show();
      });
      $("body").delegate( '.black-eye', 'mouseleave', function(e) {
          e.preventDefault();
          $(".black-label").hide();
      });
      $("body").delegate( '.black-eye', 'click', function(e) {
          e.preventDefault();
          // $(".blacklist-content1").hide();
          // $(".blacklist-content2").show();
          beenBlockedTimes('showBeenBlockedTimes');
      });
      $("body").delegate( '.blacklist-content2>a', 'click', function(e) {
          e.preventDefault();
          // $(".blacklist-content1").show();
          // $(".blacklist-content2").hide();
          beenBlockedTimes('hiddenBeenBlockedTimes');
      });
      $("body").delegate('.nav-top-bottom', 'click', function(e) {
        $(this).toggleClass('active');
        $('.hide-default').toggle();
      });
    },
    _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 status = data.status;
      var that = this;
      this.playerId = data.user_id;

      // if(status) {
      //   var tip;
      //   if(status == 10402) {
      //     tip = "盒子未保存过该用户的战斗日志";
      //   } else if(status == 10407) {
      //     tip = "请重新打一场匹配恢复战绩";
      //   } else if(status == 10401){
      //     tip = "参数不全";
      //   }

      //   $(".no-data-tip").show().find("p").html(tip);
      //   $(".box-bd").hide();
      //   return;
      // }

      $(".box-bd").show();
      //获取KDA行数据--放在box-bd show 之后，保证Morris正常渲染.
      // this._getKDAData().done(function(data) {
      //   that._renderKDA(data);
      // }).fail(function() {});

      this._renderPersonalInfo(data);
      this._renderHistory(data);
      this._renderHero(data);
      this._renderGameCount(data);

      this._renderKDA(data);
    },
    _renderPersonalInfo: function(data) {
      var self = this;
      var href = "recordlist.html?serverName=" + this.serverName + "&playerName=" + this.playerName + "&userId=" + userId + "&gameZone=" + gameZone;
      var attentionUrl = "http://lolbox.duowan.com/webApi.php?serverName=" + this.serverName + "&playerName=" + this.playerName + "&targetServerName=" + this.boxServerName + "&targetPlayerName=" + this.boxPlayerName + "&action=";
      // var attentionUrl = "http://lolbox.duowan.com/webApi.php?serverName=" + this.serverName + "&playerName=" + this.playerName + "&targetServerName=%E7%94%B5%E4%BF%A1%E4%B8%80&targetPlayerName=%E6%96%8C%E7%A6%BE%E4%B8%96%E7%BA%AA&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
      }));

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

      //关注、取消关注
      $("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/"+gameZone+"/" + self.boxUserId + '/'+action+'/?user_id='+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("关注");
              }
            }
          }
        });
      });
      
      //分享
      jiathis_config = {
          title: "#无盒子 不开撸# 我是" + data.pn +"，我在使用LOL盒子。来看看我的战斗力有多少吧！",
          appkey: {
              "tsina": "3629014272",
              "tqq": "801220649",
              "qzone": "100302822"
          },
          summary: " ",
          ralateuid: {
              "tsina": "2909042820"
          }
      };
      if (playerMostUsedHero)
          jiathis_config.pic = 'http://lolbox.duowan.com/images/champions/' + playerMostUsedHero + '_120x120.png';
      if (SnsShare) SnsShare.init();
        
    },
    _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++]);
          }
        }

        if(setData.length > 0) {
          //初始化打野
          Morris.Donut({
            element: 'daYe',
            data: setData,
            colors: setColors,
            gridTextSize: 30
          });
        }
      }

      $("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 continueUsed = data.continuousWinOrLose;
      var nextFirstWinTime = data.timestamp_until_next_first_win_bonus;

      //如果 是未来某个一个时刻的 Unix 时间戳，展示灰色图标，格式化为倒计时，tips显示 “首胜：x小时x分”；
      //如果 是过去某个时刻时间戳，表示首胜可用，展示金色图标，tips显示 “首胜可用”；
      //如果是 null ，表示“数据缺失”，不展示图标和tips。
      if (nextFirstWinTime) {
        var firstWinSeconds = nextFirstWinTime * 1000;
        var now = new Date().getTime();
        var tipMsg = '', $target = $("#firstMsg");
        if(firstWinSeconds > now) {
          var gap = firstWinSeconds - now;
          //计算出相差天数  
          var days=Math.floor(gap/(24*3600*1000))  
             
          //计算出小时数  
          var leave1=gap % (24*3600*1000)    //计算天数后剩余的毫秒数  
          var hours = Math.floor(leave1 / (3600*1000))  
          //计算相差分钟数  
          var leave2 = leave1 % (3600*1000)        //计算小时数后剩余的毫秒数  
          var minutes = Math.floor(leave2 / (60*1000))  
          tipMsg = hours + "小时" + minutes + "分钟";
        } else {
          tipMsg = '首胜可用';
          $target.addClass('active-status');
        }

        $(".f-time").html(tipMsg);

        $target.on('mouseenter', function(e) {
          e.preventDefault();
          $('.first-win-hover').show();
        }).on('mouseleave', function(e) {
          e.preventDefault();
          $('.first-win-hover').hide();
        });
      }

      //连胜、连败
      // if(continueUsed.statCode != -1) {
      //   var template1 = _.template($("#flagTemp").html());
      //   $("#flag").html(template1({
      //     data: continueUsed
      //   }));
      // }
      
      //最近战绩
      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'
        });
      });
      
    },
    _renderHero: function(data) {
      if(data) {
        commonHeroHoverData = data.champion_performance_list;

        var self = this;
        //英雄浮窗数据获取url
        var baseUrl = "http://lolbox.duowan.com/new/api/index.php?_do=personal/mostusedchampion&serverName=" + this.serverName + "&playerName=" + this.playerName;
        data.heroWindowUrl = baseUrl;

        var template = _.template($("#commonHeroTemp").html());
        $("#commonHeroContent").html(template({
          data: data
        }));

        var enterTimeout, leaveTimeout, canBeClosed;
        //常用英雄浮窗
        $("body").delegate('#commonHero>li', 'mouseenter', function(e) {
          e.preventDefault();

          if($(this).hasClass('default')) return;
          
          var tag= $(e.target)[0].tagName;
          var $el = /LI/g.test(tag) ? $(e.target) : $(e.target).parents('li');

          var pos_left = $el.offset().left + $el.outerWidth() + 6;
          var pos_top = $el.offset().top + ($el.outerHeight() / 2) - 80;
          var name = $el.attr('data-name');
          var index = $el.attr('data-index');

          //从commonHeroHoverData缓存中获取对应的英雄数据
          var tdata = commonHeroHoverData[index];

          clearTimeout(enterTimeout);
          clearTimeout(leaveTimeout);
          canBeClosed = true;
          if($(".hover-content")) $(".hover-content").remove();
          var $hContent = $("<div class='hover-content personal-hover'></div>");

          if(tdata.length == 0) {
            tdata.noData = true;
            tdata.tipMsg = "因长时间没有游戏，数据无法采集";
            $hContent.addClass("blank-content");         
          }

          //截图url
          var shotUrl = "http://lolbox.duowan.com/playerDetail/championsStatShareShot.php?serverName=" + self.serverName + "&playerName=" + self.playerName + "&ch=" + name + "&openmode=default";

          tdata.shotUrl = shotUrl;

          var template = _.template($("#heroHoverTemp").html());
          $hContent.html(template({
            data: tdata
          })).css({
            left: pos_left,
            top: pos_top
          });

          enterTimeout = setTimeout(function(){
            $('body').append($hContent);
            if (SnsShare) SnsShare.init();
          }, 100);
        });

        $("body").delegate('#commonHero>li', 'mouseleave', function(e) {
          e.preventDefault();
          clearTimeout(enterTimeout);
          clearTimeout(leaveTimeout);

          leaveTimeout = setTimeout(function(){
            if(canBeClosed) $(".hover-content").remove();
          }, 100);

          $(".hover-content").on('mouseenter', function(e) {
            canBeClosed = false;
          }).on('mouseleave',function(e) {
              clearTimeout(leaveTimeout);
              leaveTimeout = setTimeout(function(){
                $(".hover-content").remove();
              }, 100);
          });
        });
      } 
    }, 
    _renderHeroHover: function(name) {
      //英雄浮窗数据获取url
      var baseUrl = "http://lolbox.duowan.com/new/api/index.php?_do=personal/mostusedchampion&serverName=" + this.serverName + "&playerName=" + this.playerName;
      var url = baseUrl + "&zhName=" + name + "&playerId=" + this.playerId;

      return $.ajax({
        url: url,
        type: 'GET',
        dataType: 'jsonp'
      });
    },
    _renderGameCount: function(data) {
      // 经典模式
      var template = _.template($("#gameCountTemp").html());
      $("#gameCount").html(template({
        data: data
      }));

      //2015赛季
      var template1 = _.template($("#gameCount2015Temp").html());
      $("#gameCount2015").html(template1({
        data: data
      }));
    },
    _moreGameResult: function() {
      var href = "recordlist.html?serverName=" + urlServerName + "&playerName=" + urlPlayerName+'&userId='+userId+'&gameZone='+gameZone;
      $("#moreGameResult").attr("href", href);
    },
    _moreCommonHero: function() {
      var href = "championsStat.html?serverName=" + this.serverName + "&playerName=" + this.playerName;
      $("#moreCommonHero").attr("href", href);
    }
  };

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

  var personal = new Personal();
  personal.init();
});
