// packageH/member/upgrade_code/upgrade_code/upgrade_code.js
const App = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    codeList: [],
    codeLoading: false, //* 升级码列表是否加载中
    codeFinished: false, //* 升级码列表是否加载完成
    codeLoadPage: 1, //* 升级码列表页数
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCodes();
    wx.setNavigationBarTitle({
      title: "升级码",
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData(
      {
        codeList: [],
        codeLoading: false,
        codeFinished: false,
        codeLoadPage: 1,
      },
      () => {
        this.getCodes();
      }
    );
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getCodes();
  },
  onShareAppMessage() {},
  onShareTimeline() {},

  getCodes() {
    if (this.data.codeLoading === true || this.data.codeFinished === true) {
      return;
    }
    this.setData({
      codeLoading: true,
    });
    let url = App.getNetAddresss(
      "plugin.upgrade-code.Frontend.controllers.list.index"
    );
    App._getNetWork({
      url,
      data: {
        page: this.data.codeLoadPage,
      },
      success: ({ data: { data: response, result, msg } }) => {
        if (!result) {
          wx.showToast({
            title: msg,
            icon: "none",
            duration: 1500,
            complete() {
              wx.redirectTo({
                url: "/packageG/member_v2/member_v2",
              });
            },
          });
          return;
        }
        const { data, current_page, last_page, per_page } = response;
        const setData = {
          codeLoading: false,
          codeLoadPage: this.data.codeLoadPage + 1,
        };

        if (current_page == last_page || per_page < data.length) {
          setData["codeFinished"] = true;
        }
        for (const codeItem of data) {
          if (codeItem["member_level"] && codeItem["dividend_level"]) {
            codeItem["_level_text"] =
              codeItem["member_level"]["level_name"] +
              " + " +
              codeItem["dividend_level"]["level_name"];
          } else if (codeItem["member_level"]) {
            codeItem["_level_text"] = codeItem["member_level"]["level_name"];
          } else if (codeItem["dividend_level"]) {
            codeItem["_level_text"] = codeItem["dividend_level"]["level_name"];
          }
        }
        let localData = this.data.codeList;
        localData = localData.concat(data);
        setData["codeList"] = localData;
        this.setData(setData);
        wx.stopPullDownRefresh();
      },
    });
  },
});
