// components/loadmore/index.js
const
  {
    globalData: {
      util: {
        regeneratorRuntime,
        request,
        showTip
      }
    }
  } = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    url: String,
    data: Object,
    page: {
      type: Number,
      value: 1
    },
    rows: {
      type: Number,
      value: 10
    },
    request: {
      type: String,
      value: "get"
    }
  },
  data: {
    completion: false,
    lock: false,
    state: false,
  },
  ready() {
    let reload = (param = null) => {
      this.setData({
        page: 1,
        completion: false,
        lock: false,
        param
      })
      this._observer && this._observer.disconnect()
      this._observer = wx.createIntersectionObserver(this).relativeToViewport()
      this._observer.observe('.loadmore', ({
        intersectionRatio
      }) => this.setData({
        state: intersectionRatio > 0
      }))
    }
    this.triggerEvent("reload", {
      reload
    })
    reload()
  },
  detached() {
    this._observer.disconnect();
  },
  observers: {
    state(o) {
      o && this.load()
    },
    completion(completion) {
      this.triggerEvent("loadCompletion", { completion })
    }
  },
  methods: {
    async load() {
      let {
        url,
        param,
        data,
        page,
        rows,
        completion,
        lock,
        state,
        request: req
      } = this.data
      if (lock || !state) return false
      lock = !lock;
      let {
        items = [],
        total = 0,
        _err
      } = await request[req](url, Object.assign({}, data, param, {
        page,
        rows
      }))
      if (_err) {
        _err.status && showTip(_err.errmsg || '加载列表失败')
        return this.setData({
          completion: true
        });
      }
      this.triggerEvent("getItems", {
        items
      })
      if (completion = rows * (page - 1) + items.length >= total) {
        this._observer.disconnect();
        return this.setData({
          completion
        })
      }
      this.setData({
        page: ++page
      })
      lock = !lock;
      setTimeout(() => this.load(), 1000)
    }
  }
})