// pages/mine/product/productmanage/searchproduct.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    CustomBar: app.globalData.CustomBar,
    goodsList: [],
    baseImageUrl: app.urls.baseImgUrl,
    shopId: '',
    countTime: 2000, //延迟搜索 时间
    searchWaiting: false, //是否等待搜索倒计时中,
    searchKey: ''
  },
  /**
   * 获取商品列表
   */
  getGoodsList(keywords) {
    wx.showLoading({
      title: '加载中...',
    })
    var _self = this
    app.http.get(app.urls.getShopGoodsList.format({
        shopId: _self.data.shopId
      }), {
        header: {
          token: app.globalData.token
        },
        data: {
          keywords: keywords
        }
      })
      .then(res => {
        wx.hideLoading({})
        _self.setData({
          isRefreshing: false
        })
        _self.setData({
          goodsList: res.data.rows
        })
      })
      .catch(err => {
        wx.hideLoading({})
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      shopId: options.shopId
    })
  },
  manageGoods(e) {
    wx.navigateTo({
      url: './productmanage?shopGoodsId=' + e.currentTarget.dataset.item.goodsId,
    })
  },
  searchGoods(e) {
    this.setData({
      countTime: 2000,
      searchKey: e.detail.value,
    })
    //是否处于搜索倒计时中
    if (!this.data.searchWaiting) {
      this.timer();
    }
  },
  /**
   *  延迟搜索  
   */
  timer() {
    var that = this;
    this.setData({
      searchWaiting: true
    })

    let promise = new Promise((resolve, reject) => {
      let setTimer = setInterval(
        () => {
          console.log('搜索倒计时: ' + that.data.countTime);
          this.setData({
            countTime: this.data.countTime - 1000
          })
          if (this.data.countTime <= 0) {
            console.log('开始搜索: ' + that.data.params);
            this.setData({
              countTime: 2000,
              searchWaiting: false,
            })
            resolve(setTimer)
          }
        }, 1000)
    })
    promise.then((setTimer) => {
      this.getGoodsList(this.data.searchKey)
      clearInterval(setTimer) //清除计时器
    })
  },
})