const pages = require('../../mixin/pages')
const { getProductCategoryList } = require('../../api/common')
const { debounce } = require('../../utils/util')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    ...pages.data(),
    listUrl: '/api/user/home/shop/list',
    searchForm: {
      key_words: '',
      category_id: '',
      shop_type: ''
    },
    categoryList: [],
    navScrollLeft: -1,
    booLock: false,
    booPopop: true,
    arrShopType: app.globalData.arrShopType,
    shop_type: [],
    handleShoptype: null
  },
  ...pages.methods,

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    await this.fetchProductCategoryList()
    this.fetchOrderList()
    this.setData({
      handleShoptype: debounce(this.refreshOrderList, 2500)
    })
  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    if (this.data.freshing) {
      return
    }
    this.setData({
      freshing: true
    })
    this.bindCallBack()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.fetchOrderList()
  },
  bindCallBack() {
    this.refreshOrderList()
  },
  async fetchProductCategoryList() {
    try {
      const { status, data, msg } = await getProductCategoryList()
      if (status && Array.isArray(data) && data.length > 0) {
        const temp = data.map(item => {
          return {
            ...item,
            text: item.category_name
          }
        })

        temp.unshift({
          category_img_url: 'https://lanman-shining.oss-cn-hangzhou.aliyuncs.com/images/user/bashi635cd28a12481.png',
          category_name: '全部',
          id: 0
        })

        this.setData({
          categoryList: temp,
          'searchForm.category_id': temp[0].id
        })
      } else {
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    } catch (err) {}
  },
  handleNav(e) {
    const { item } = e.currentTarget.dataset

    if (this.data.searchForm.category_id !== item.id) {
      this.setData({
        'searchForm.category_id': item.id,
        navScrollLeft: 0
      }, () => {
        this.refreshOrderList()
      })
    }
  },
  hidePopop() {
    this.setData({
      booPopop: false
    })
  },
  onChange(event) {
    const temp = event.detail
    const value = temp[temp.length - 1]

    this.setData({
      shop_type: [],
      'searchForm.shop_type': value || ''
    }, () => {
      this.data.handleShoptype()
    })

    const timer = setTimeout(() => {
      clearTimeout(timer)
      this.setData({
        shop_type: value ? [value] : []
      })
    }, 200)
  }
})