// pages/shop/catalog/list/list.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shopId: '',
    active: 1,
    swiperlist: [],
    typeMenu: [],
    goodsList: [],
    currentPage: 1,
    contentHeight: app.globalData.windowHeight,
    isLoadMore: false, //是否在加载中
    hasMore: true, //是否还有更多数据
    currentPage: 1,
    totalSize: 0,
    baseImg:  app.urls.baseImgUrl,
    isShowCart: false,
    shopCart: [],
    countTime: 2000, //延迟搜索 时间
    searchWaiting: false, //是否等待搜索倒计时中,
    searchKey: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      shopId: options.shopId,
      shopCart: app.globalData.shopCart
    })
    //获取全部商品
    this.getShopGoodsListByPage()
    this.selectComponent('#sCart').refreshCart()
  },
  getShopGoodsListByPage() {
    let _self = this
    wx.showLoading({
      title: '加载中...',
    })
    app.restAjax.get(
      app.restAjax.path(app.apis.getShopGoodsList, [app.baseUrls.tradeUrl, _self.data.shopId]), {
        page: _self.data.currentPage,
        keywords: _self.data.searchKey
      }, {
        headers: {
          token: app.globalData.token
        }
      }, (code, data) => {
        wx.hideLoading({})
        _self.setData({
          isLoadMore: false
        })
        if (code == 200) {
          if (data.rows.length > 0) {
            data.rows.forEach(it => {
              //构建图片
              var photos = it.goodsPhotos
              var pList = photos.split(',')
              it.showPhoto = _self.data.baseImg + pList[0]
              //判断购物车是否存在该商品
              if (app.globalData.shopCart.length > 0) {
                app.globalData.shopCart.forEach(i => {
                  if (i.goodsId == it.goodsId) {
                    it.buyNum = i.buyNum
                  } else {
                    it.buyNum = 0
                  }
                })
              } else {
                it.buyNum = 0
              }
            })
            _self.data.goodsList = _self.data.goodsList.concat(data.rows)
            _self.setData({
              goodsList: _self.data.goodsList
            })
          } else {
            _self.setData({
              hasMore: false
            })
          }
        }
      }, (code, error) => {
        wx.hideLoading({})
        if (error.msg) {
          app.dialog.msg(error.msg)
        } else {
          wx.showToast({
            title: '网络错误',
            icon: 'error'
          })
        }
      })
  },
  doLoadMore(e) {
    let _self = this
    if (_self.data.hasMore) {
      if (_self.data.isLoadMore) {
        return
      }
      _self.setData({
        isLoadMore: true,
        currentPage: ++_self.data.currentPage
      })
      _self.getShopGoodsListByPage(_self.data.shopId)
    } else {
      wx.showToast({
        title: '暂无更多数据',
        icon: 'none',
        duration: 500
      })
    }
  },
  //商品详情页面
  toGoodsDetail(e) {
    let _self = this
    wx.navigateTo({
      url: '../../product/goodsdetail?shopId=' + _self.data.shopId + '&goodsId=' + e.currentTarget.dataset.item.goodsId,
    })
  },
  //列表添加购物车
  addToCart(e) {
    let _self = this
    let goods = e.currentTarget.dataset.item
    _self.data.goodsList.forEach(it => {
      if (goods.goodsId == it.goodsId) {
        it.buyNum += 1
        if (it.buyNum > goods.goodsTotal) {
          it.buyNum = goods.goodsTotal
          wx.showToast({
            title: '超出库存',
            icon: 'error'
          })
        }
      }
    })
    this.selectComponent('#sCart').listAddToCart(goods)
    _self.setData({
      goodsList: _self.data.goodsList,
      shopCart: app.globalData.shopCart
    })
  },
  removeToCart(e) {
    let goods = e.currentTarget.dataset.item
    let _self = this
    _self.data.goodsList.forEach(it => {
      if (goods.goodsId == it.goodsId) {
        it.buyNum -= 1
      }
    })
    this.selectComponent('#sCart').listRemoveCart(goods)
    _self.setData({
      goodsList: _self.data.goodsList,
      shopCart: app.globalData.shopCart
    })
  },
  //显示购物车弹框
  doShowCart() {
    var _self = this
    if (this.data.shopCart.length > 0) {
      //判断当前购物车是否存在该商店的商品
      var isExist = false
      this.data.shopCart.forEach(it => {
        if (it.shopId == _self.data.shopId) {
          isExist = true
        }
      })
      if (isExist) {
        if (this.data.isShowCart) {
          this.setData({
            isShowCart: false
          })
        } else {
          this.setData({
            isShowCart: true
          })
        }
      } else {
        wx.showToast({
          title: '购物车空空如也',
          icon: 'error'
        })
      }
    } else {
      wx.showToast({
        title: '购物车空空如也',
        icon: 'error'
      })
    }
  },
  //隐藏购物车弹框
  onHideCart() {
    this.setData({
      isShowCart: false
    })
  },
  //删除购物车中的商品
  delGoods(e) {
    let _self = this
    var index = e.currentTarget.dataset.index
    var goods = e.currentTarget.dataset.goods
    app.globalData.shopCart.splice(index, 1)
    //删除购物车中数据
    _self.selectComponent('#sCart').refreshCart()
    //将列表中的数据购买数量重置
    _self.data.goodsList.forEach(it => {
      if (it.goodsId == goods.goodsId) {
        it.buyNum = 0
      }
    })
    _self.setData({
      goodsList: _self.data.goodsList,
      shopCart: app.globalData.shopCart
    })
    if (_self.data.shopCart.length <= 0) {
      _self.setData({
        isShowCart: false
      })
    }
  },
  //购物车弹框删除或添加商品
  onChange(e) {
    let buyNum = e.detail
    let goods = e.currentTarget.dataset.goods
    let _self = this
    //遍历列表
    _self.data.goodsList.forEach(it => {
      if (it.goodsId == goods.goodsId) {
        it.buyNum = buyNum
      }
    })
    //遍历购物车
    _self.data.shopCart.forEach(it => {
      if (it.goodsId == goods.goodsId) {
        it.buyNum = buyNum
      }
    })
    //刷新视图
    _self.setData({
      goodsList: _self.data.goodsList,
      shopCart: _self.data.shopCart
    })
    //刷新购物车
    _self.selectComponent('#sCart').refreshCart()
  },
  onHide() {
    this.setData({
      isShowCart: false
    })
  },
  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.setData({
        currentPage: 1,
        goodsList: []
      })
      this.getShopGoodsListByPage()
      clearInterval(setTimer) //清除计时器
    })
  },
})