var RankItem = require('./rankitem.js').RankItem;
var Label = require('./libs/label.js').Label;
var Sprite = require('./libs/sprite.js').Sprite;

var BottomScoreItem = require('./bottomscoreitem.js').BottomScoreItem;

const PAGE_SIZE = 9;
const ITEM_WIDTH =600;// 608;
const ITEM_HEIGHT = 100;//126;
const offsetY = 235;
const itemGap = 1;
const ownerY= 1150;
const pageTextY=1250;
var offsetX = 0;

var canvawidth = 0;
var canvaheight = 0;
var normal_scale = 1;

var swidth = 630;
var sheight = 800;

var friends_scores = [];
//总排行数据 可为群或者好友
var group_scores = [];
//周排行数据 可为群或者好友
var group_week_scores = [];
var current_scores = [];

var moveoffset = 0; //滑动偏移
var allHeight = 0; //整个排行榜高
var worldData;
var isworldRank = false;

const dataSorter = (gameDatas, filed = "stage") => {
  return gameDatas.sort((a, b) => {
    const kvDataA = a.KVDataList.find(kvData => kvData.key == filed);
    const kvDataB = b.KVDataList.find(kvData => kvData.key == filed);
    var stageA = JSON.parse(kvDataA.value).wxgame.stage;
    var stageB = JSON.parse(kvDataB.value).wxgame.stage;
    const gradeA = kvDataA ? parseInt(stageA || 0) : 0;
    const gradeB = kvDataB ? parseInt(stageB || 0) : 0;
    return gradeA > gradeB ? -1 : gradeA < gradeB ? 1 : 0;
  });
}

let myInfo;
let avatarUrl;
//获取个人信息
wx.getUserInfo({
  openIdList: ["selfOpenId"],
  success: function (res) {
    myInfo = res.data[0];
    avatarUrl = myInfo.avatarUrl;
    console.log(myInfo);
  }
})

var adpater = 0;

var h;//宽
var v;//高
class RankListRenderer {

  constructor() {
    this.totalPage = 0;
    this.currPage = 0;
    this.keyName = "";
    this.rankitemArr = [];
    this.init();
    this.sys_info = wx.getSystemInfoSync();
  }

  init() {
    this.canvas = wx.getSharedCanvas();
    this.ctx = this.canvas.getContext('2d');
    this.ctx.imageSmoothingEnabled = true;
    this.ctx.imageSmoothingQuality = "high";
    this.rankcanvas = wx.createCanvas();
    this.rankctx = this.rankcanvas.getContext('2d');
  }



  listen() {
    wx.onMessage(msg => {
      console.log(msg);
      switch (msg.action) {
        case "canvase_width_height":
          console.log(msg.data.width, msg.data.height);
          canvawidth = msg.data.width;
          canvaheight = msg.data.height;

          v = canvaheight / this.screenHeight;
          h = canvawidth / this.sys_info.screenWidth;
          
          offsetX = (canvawidth - ITEM_WIDTH) * 0.5 * normal_scale;
          this.rankcanvas.width = canvawidth;
          this.rankcanvas.height = canvaheight;
          break;
        case "clearctx":
          this.rankctx.clearRect(0, 0, canvawidth, canvaheight);
          break;
        case "get_friend_storage":
          this.getFriendStorage(msg.keyName);
          break;
        case "show_friend_rank":
          console.log("keyname", msg.keyName);
          this.keyName = msg.keyName;
          this.fetchFriendData(msg.keyName);
          isworldRank = false;
          this.currPage = 0;
          break;
        case "show_group_rank":
          console.log("show_group_rank", msg.data);
          if (!msg.data) return;
          this.keyName = msg.keyName;
          this.fetchGroupData(msg.keyName, msg.data);
          break;
        case "show_world_rank":
          console.log("show_group_rank", msg.data);
          if (!msg.data) return;
          this.keyName = msg.keyName;
          worldData = msg.data;
          this.totalPage = Math.ceil(worldData["list"].length / PAGE_SIZE);
          isworldRank = true;
          this.showWorldRanks(0);
          break;
        case "show_min_rank":
          this.keyName = msg.keyName;
          this.drawMinRank(msg.keyName, msg.data);
          break;
        case "show_up_page":
          if (!isworldRank && !current_scores.length) {
            return;
          }
          if (isworldRank && !worldData["list"].length) {
            return;
          } {
            let page = this.currPage;
            page -= 1;
            if (page < 0) page = 0;
            if (this.currPage > page) {
              this.currPage = page;
              if (isworldRank == false)
                this.showRanks(this.currPage);
              else this.showWorldRanks(this.currPage);
            }

          }
          break;
        case "show_next_page":
          if (!isworldRank) {
            if (!current_scores.length) return;

          } else {
            if (!worldData["list"].length) return;
          } {

            let page = this.currPage;
            page += 1;
            if (this.totalPage <= page) page = this.totalPage - 1;
            if (this.currPage < page) {
              this.currPage = page;
              if (isworldRank == false)
                this.showRanks(this.currPage);
              else this.showWorldRanks(this.currPage);
            }

          }

          break;
        default:
          console.log(`未知消息类型:msg.action=${msg.action}`);
          break;
      }
    });

  }


  fetchFriendData(keyName) {
    wx.getFriendCloudStorage({
      keyList: [
        keyName,
      ],
      success: res => {
        console.log("wx.getFriendCloudStorage success", res);
        const dataLen = res.data.length;
        friends_scores = dataSorter(res.data, keyName);
        console.log("Sort success", friends_scores);
        current_scores = friends_scores;
        this.totalPage = Math.ceil(current_scores.length / PAGE_SIZE);
        console.log(" this.totalPage", this.totalPage);
        if (dataLen) {
          this.showRanks(0);

        }

      },

      fail: res => {
        console.log("wx.getFriendCloudStorage fail", res);
      },

    });
  }



  showRanks(page) {

    const startIndex = page * PAGE_SIZE;
    const stopIndex = startIndex + PAGE_SIZE;
    const datas = current_scores.slice(startIndex, stopIndex);
    let x = 0;
    if (this.sys_info.model.match("iPhone X")) {
      x = 110
    }
    this.ctx.clearRect(0, 0, canvawidth, canvaheight);
    for (let i = 0, len = datas.length; i < len; i++) {
      let data = datas[i];
      const nick = data.nickname.length <= 10 ? data.nickname : data.nickname.substr(0, 10) + "...";
      const kvData = data.KVDataList.find(kvData => kvData.key == this.keyName);
      const itemGapY = (ITEM_HEIGHT + itemGap) * i + offsetY;
      const avatarUrl = data.avatarUrl;
      
      const grade = kvData ? this.max_crossed_stage(kvData.value) : 0;
      let rankItem = this.rankitemArr[i];
      if (rankItem == null) {
        rankItem = new RankItem(offsetX, itemGapY, ITEM_WIDTH, ITEM_HEIGHT);
        this.rankitemArr.push(rankItem);
        rankItem.create();
      }

      rankItem.setData(i + startIndex + 1, avatarUrl, nick, grade, this.keyName);
      rankItem.drawToCanvas(this.ctx);
      console.log("offsetY", offsetY);
    }

    // let page_y = canvaheight - 360;
    // let pageLabel = new Label(canvawidth * 0.5-40 , pageTextY);
    // pageLabel.fontSize = "45px"
    // pageLabel.fillStyle = "#ffffff";
    // pageLabel.text = `${this.currPage + 1} / ${this.totalPage}`;
    // pageLabel.drawToCanvas(this.ctx);
    this.showBottomOwner();
  }

  max_crossed_stage(value)
  {
    return parseInt(JSON.parse(value).wxgame.stage);

  }

  showBottomOwner() {
    let grade = 0;
    let mydata;
    let ranking=0;
    for (let i = current_scores.length - 1; i >= 0; i--) {

      let data = current_scores[i];
      if (data.avatarUrl == avatarUrl) {
        mydata = data;
        ranking=i+1;
        break;
      }
    }
    let kvData = mydata.KVDataList.find(kvData => kvData.key == this.keyName);
    grade = kvData ? this.max_crossed_stage(kvData.value) : 0;
    if (this.ownerItem == null) {
      //this.ownerItem = new BottomScoreItem(offsetX, 1040 + adpater, ITEM_WIDTH, ITEM_HEIGHT);
      this.ownerItem = new BottomScoreItem(offsetX, ownerY, ITEM_WIDTH, ITEM_HEIGHT);
      this.ownerItem.create();
    }
    console.log(mydata.nickname);
    console.log(grade);
    //this.ownerItem.setData( mydata.nickname, avatarUrl, grade);
    this.ownerItem.setData(ranking, mydata.nickname, avatarUrl, grade);
    this.ownerItem.drawToCanvas(this.ctx);
  }

  showWorldRanks(page) {
    const startIndex = page * PAGE_SIZE;
    const stopIndex = startIndex + PAGE_SIZE;
    const datas = worldData["list"].slice(startIndex, stopIndex);
    console.log("datas", datas);
    let x = 0;
    if (this.sys_info.model.match("iPhone X")) {
      x = 110
    }
    this.ctx.clearRect(0, 0, canvawidth, canvaheight);
    for (let i = 0, len = datas.length; i < len; i++) {
      let data = datas[i];
      let nick = data.nickname.length <= 10 ? data.nickname : data.nickname.substr(0, 10) + "...";
      nick = nick == "" ? "游客" : nick
      const itemGapY = (ITEM_HEIGHT + 6) * i + offsetY;
      const avatarUrl = data.avatar;
      const grade = data.score;
      let rankItem = this.rankitemArr[i];
      if (rankItem == null) {
        rankItem = new RankItem(i,offsetX, itemGapY, ITEM_WIDTH, ITEM_HEIGHT);
        this.rankitemArr.push(rankItem);
        rankItem.create();
      }
      rankItem.position(offsetX, itemGapY);
      rankItem.setData(i + startIndex + 1, avatarUrl, nick, grade, this.keyName);
      rankItem.drawToCanvas(this.ctx);
      console.log("offsetY", offsetY);
    }

    let page_y = canvaheight - 360;
    let pageLabel = new Label(canvawidth * 0.5 - 60, page_y);
    pageLabel.fontSize = "35px"
    pageLabel.fillStyle = "#ffffff";
    pageLabel.text = `${this.currPage + 1} / ${this.totalPage}`;
    pageLabel.drawToCanvas(this.ctx);
    this.showBottomOwner();
  }

  fetchGroupData(keyName, shareTicket) {
    //取出群同玩成员数据
    wx.getGroupCloudStorage({
      shareTicket,
      keyList: [
        keyName,
      ],
      success: res => {
        console.log("wx.getGroupCloudStorage success", res);
        const dataLen = res.data.length;
        group_scores = dataSorter(res.data, keyName);
        current_scores = group_scores;
        this.totalPage = Math.ceil(current_scores.length / PAGE_SIZE);
        console.log(" this.totalPage", this.totalPage);
        if (dataLen) {
          this.showRanks(0);
        }

      },
      fail: res => {
        console.log("wx.getGroupCloudStorage fail", res);
      },
    });
  }

  drawMinRank(keyName, shareTicket) {
    wx.getFriendCloudStorage({
      keyList: [
        keyName,
      ],
      success: res => {
        console.log("wx.getFriendCloudStorage success", res);
        const dataLen = res.data.length;
        friends_scores = dataSorter(res.data, keyName);
        current_scores = friends_scores;
        this.totalPage = Math.ceil(current_scores.length / PAGE_SIZE);
        console.log(" this.totalPage", this.totalPage);
        if (dataLen) this.showMinRanks();

      },

      fail: res => {
        console.log("wx.getFriendCloudStorage fail", res);
      },

    });
  }


  getFriendStorage(keyName) {
    wx.getFriendCloudStorage({
      keyList: [
        keyName,
      ],
      success: res => {
        console.log("wx.getFriendCloudStorage success", res);
        const dataLen = res.data.length;
        friends_scores = dataSorter(res.data, keyName);
        current_scores = friends_scores;
        console.log(" this.totalPage", this.totalPage);
      },

      fail: res => {
        console.log("wx.getFriendCloudStorage fail", res);
      },

    });
  }
}


let ranklist = new RankListRenderer();
ranklist.listen();