// miniprogram/pages/mediaList/index.js
let li = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    option1: [],
    value1: 0,
    h: 0,
    top: 0,
    page: 1,
    size: 15,
    group: ""
  },
  change(e) {
    this.setData({
      page: 1,
      top: 0,
      group: this.data.option1[e.detail].text
    }, () => {
      this.changePage(0, []);
    })
  },
  page() {
    this.changePage(this.data.page, this.data.list)
  },
  changePage(page, list) {
    wx.showLoading()
    let l = [];
    let index = 0
    for (let i = 0; i < li.length; i++) {
      const v = li[i];
      if (l.length >= 10 || index >= this.data.size) break
      if (!v || (v.captureWebsiteName !== this.data.group && this.data.group !== "全部")) continue;
      index++;
      l.push(v);
    }
    let p = { list: [...list, ...l] };
    if (l.length) p.page = page + 1;
    this.setData(p, () => {
      wx.hideLoading()
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let info = wx.getSystemInfoSync();
    const fs = wx.getFileSystemManager()
    wx.showLoading()
    wx.downloadFile({
      url:  app.base.url + '/l.json',
      success: r => {
        // 返回临时文件路径
        fs.readFile({
          filePath: r.tempFilePath,
          encoding: 'utf8',
          position: 0,
          success(res) {
            wx.hideLoading();
            li = res.data ? JSON.parse(res.data).list || [] : [];
            let group = [{ text: '全部', value: 0 }];
            let groupObj = {};
            let index = 1;
            li.map(v => {
              if (!groupObj[v.captureWebsiteName]) {
                group.push({
                  text: v.captureWebsiteName, value: index
                })
                groupObj[v.captureWebsiteName] = true;
                index++;
              }
            })
            let l = [];
            for (let i = 0; i < that.data.size; i++) {
              const v = li[i];
              l.push(v)
            }
            that.setData({
              option1: group,
              list: l,
              h: info.windowHeight - 50,
              group: group[0].text
            }, () => {
              wx.hideLoading()
            })
          },
          fail(res) {
            wx.hideLoading()
          }
        })

      },
      fail() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})