var util = require('../../utils/util.js');
var api = require('../../config/api.js');

Page({
  data: {
    navList: [],
    categoryList: [],
    currentCategory: {},
    categorys: [],
    scrollLeft: 0,
    scrollTop: 0,
    goodsCount: 0,
    scrollHeight: 0,
    top: 0,
    navtop: 0
  },
  onLoad: function (options) {
    this.setData({
      imgServer: util.imgServer,
    })
    getApp().checkNetStatu();
    this.getCatalog();
  },
  onPullDownRefresh() {
    this.getCatalog();
    getApp().onPullDownRefresh()
  },
  gotoSearch() {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  getCatalog: function () {
    //CatalogList
    let that = this;
    wx.showLoading({
      title: '加载中...',
    });
    util.request(api.CatalogList).then(async function (res) {
      let navList = res.data.categoryList
      let ccs = []

      await Promise.all(navList.map((nav, i) => {
        return util.request(api.CatalogCurrent, { id: nav.id })
          .then(function (res) {
            ccs[i] = res.data.currentCategory
          })
      }))
      
      that.setData({
        navList,
        currentCategory: ccs[0],
        categorys: ccs
      });

      wx.nextTick(() => {
        that.getCatesTop()
        wx.createSelectorQuery().select('#cate-layout').boundingClientRect().exec((rect) => {
          that.catgHeight = rect[0].height
        })
      })
      wx.hideLoading();
    });

    // util.request(api.GoodsCount).then(function (res) {
    //   that.setData({
    //     goodsCount: res.data.goodsCount
    //   });
    // });

  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
    
    getApp().updateCardCount()
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  async getCatesTop(eid) {
    const index = eid ? this.data.categorys.findIndex(({id}) => id === eid) : this.data.categorys.length

    if (this.heights) {
      return [...this.heights].splice(0, index)
    }

    const firstCategorys = [...this.data.categorys].splice(0, index)
    const heights = []

    await Promise.all(
      firstCategorys.map(({id}) => 
        new Promise(r => 
          wx.createSelectorQuery().select('#index-nav-' + id).boundingClientRect().exec((rect) => {
            heights.push(rect[0].height)
            r()
          })
        )
      )
    )
    this.heights = heights
    return heights
  },
  async scroll(ev) {
    let heights = await this.getCatesTop()
    let mtop = 0
    let tages = heights.map((hei) => {
      let sstart = ev.detail.scrollTop
      let eend = sstart + this.catgHeight
      let start = mtop
      let end = mtop + hei
      let s = start > sstart ? start : sstart
      let e = end > eend ? eend : end

      mtop += hei
      if (s > e) {
        return 0
      } else {
        return (e - s) / hei
      }
    })

    let index = tages.indexOf([...tages].sort((b, a) => a - b)[0])

    this.setData({
      currentCategory: this.data.categorys[index],
      navtop: index * 100 + 'rpx'
    })
  },
  switchCate: async function (event) {
    const eid = event.currentTarget.dataset.id
    const top = (await this.getCatesTop(eid)).reduce((t, c) => t + c, 0)

    this.setData({
      currentCategory: this.data.categorys.find(({id}) => id === eid),
      top: top
    })
  }
})