const util = require('../../../utils/util.js');
const app = getApp();
Page({
  data: {
    index: 0,
    records:[],
    info:{},
    isLoadMore: true,
    pageIndex: 1,
    pageSize: 20,
  },
  onLoad: function (options) {
    this.setData({ index: parseInt(options.index) || 0 });
    this.getInfo();
    this.getCoinList(true);
  },
  getInfo(){
    var self = this;
    util.ajax({
      func: "coin/countinfo",
      load: false
    }, function (res) {
      if (res.code == 0) {
        self.setData({ info: res.data });
      }
    });
  },
  getCoinList(load){
    var self = this;
    util.ajax({
      func: self.data.index == 0 ? "coin/records" :"coin/invite_list",
      data: { "pageIndex": self.data.pageIndex, "pageSize": self.data.pageSize },
      load: load
    }, function (res) {
      if(res.code == 0){
        let isLoadMore = true;
        let newData = res.data.records;
        let oldData = !load ? newData : [...self.data.records, ...newData];
        if (newData.length < self.data.pageSize && oldData.length > self.data.pageSize) {
          isLoadMore = false;
        }
        for (let i = 0; i < oldData.length - 1; i++) {
          oldData[i].avatar = oldData[i].avatar ? oldData[i].avatar : '/images/default_logo.jpg';
          if (self.data.index == 0) {
            oldData[i].priceStats = (oldData[i].price.toString().indexOf("-") == -1 ? 0 : 1);
          }
        }
        self.setData({ records: oldData, isLoadMore: isLoadMore });
      }else
        util.showTips(res.reason);
    });
  },
  binderror(e){
    var records = this.data.records, index = e.currentTarget.dataset.index;
    records[index].avatar = '/images/default_logo.jpg';
    this.setData({ records });
  },
  tabs(e){
    if (e.currentTarget.dataset.index!=this.data.index) {
      this.setData({ index: e.currentTarget.dataset.index, isLoadMore: true, pageIndex: 1});
      this.getCoinList(false);
    }
  },
  onPullDownRefresh: function () {
    var self = this;
    wx.showNavigationBarLoading();
    setTimeout(function () {
      self.setData({ pageIndex: 1 });
      self.getCoinList(false);
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, 1000);
  },
  onReachBottom: function () {
    var self = this;
    if (self.data.isLoadMore == false) return false;

    setTimeout(function () {
      self.setData({ pageIndex: self.data.pageIndex + 1 });
      self.getCoinList(true);
    }, 1000);
  },
  onShareAppMessage() {
    return {
      title: '个人钱包',
      path: '/pages/account/coin/index'
    }
  }
})