// pages/create-order/index.js
import http from '../../utils/http'
import util from '../../utils/util'
import api from '../../utils/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabs: ['未读', '已读'],
    tabIndex: 0,
    list: [[], []],
    is_read: [2, 1],
    touchBottom: [false, false],
    pages: [1, 1],
    stat: [0, 0]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
  },

  navigate(e) {
    getApp().navigate(e)
  },

  switchTab: function (e) {
    var index = e.currentTarget.dataset.index
    this.setData({
      tabIndex: index
    })
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
    this.search()
  },

  search() {
    this.setData({
      list: [
        [],
        []
      ],
      pages: [1, 1],
      touchBottom: [false, false]
    })
    this.getList()
  },

  getList: function () {
    var that = this
    var index = this.data.tabIndex
    var is_read = this.data.is_read[index]
    var page = this.data.pages[index]
    http({
      url: 'notifications/get',
      data: {
        is_read: is_read,
        page: page
      },
      success: function (res) {
        if (res.code == 0) {
          var list = that.data.list
          var touchBottom = that.data.touchBottom
          list[index] = list[index].concat(res.data);
          if (res.data.length <= 0) {
            touchBottom[index] = true;
          }
          that.setData({
            touchBottom,
            list
          })
        }
      }
    })
  },

  doAction: function(e) {
    var type = e.currentTarget.dataset.type
    var that = this
    http({
      url: 'notifications/change',
      data: {
        type: type
      },
      success: function (res) {
        if (res.code == 0) {
          that.search()
          that.getStat()
        }
      }
    })
  },

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

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getStat()
    this.search();
  },

  getStat() {
    api.getByName(this, 'notifications/getStat', 'stat');
  },

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

  },

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

  },

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

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var index = this.data.tabIndex
    if(!this.data.isSearch && !this.data.touchBottom[index]) {
      var pages = this.data.pages
      pages[index] = pages[index] + 1;
      this.setData({
        pages
      })
      this.getList()
    }
    if(this.data.touchBottom[index]) {
      util.error('没有更多数据了')
    }
  },

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

  }
})