const app = getApp()
import {
  getHotrecommendList,
  getAuthorityList,
  getCategoryList
} from "~/api/works"
import reachBottom from '~/mixins/reachBottom'
import share from '~/mixins/share'
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '~/store/index'
Page({
  behaviors: [reachBottom, share],
  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: app.globalData.navBarHeight,
    background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
    currentType: '1',
    // 控制一级分类是否固定
    isFixed: false,
    categoryList: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow() {
    if (typeof this.getTabBar === 'function') {
      this.getTabBar().setData({
        selected: 1
      })
    }
    getApp().callBack = (res) => {
      this.getLocUserInfo()
      this.resetData()
      this.getCategoryList()
    }
    let uid = wx.getStorageSync('uid')
    /*  if (uid) {
       this.getLocUserInfo()
       this.resetData()
     } else {
       getApp().callBack = (res) => {
         this.getLocUserInfo()
         this.resetData()
       }
     } */
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  },
  async getLocUserInfo() {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: {
        userInfo: 'userInfo'
      },
    })
    this.storeBindings.updateStoreBindings()
  },
  loadMore() {
    if (this.data.currentType == '1') {
      this.getData(getHotrecommendList, {
        grade: this.data.userInfo.grade
      })
    } else if (this.data.currentType == '2') {
      this.getData(getAuthorityList, {
        grade: this.data.userInfo.grade
      })
    }
  },
  jumpChildClassify({
    currentTarget
  }) {
    let firstInfo = currentTarget.dataset.item
    let params = firstInfo.childList.length > 0 ? `list=${encodeURIComponent(JSON.stringify(firstInfo.childList))}` : `id=${firstInfo.id}`
    wx.navigateTo({
      url: `/pages/childClassify/index?type=class&title=${firstInfo.title}&${params}`,
    })
  },
  jumpSearch() {
    wx.navigateTo({
      url: '/pages/childClassify/index?type=search',
    })
  },
  /**
   * 监听页面滚动事件
   */
  onPageScroll(e) {
    if (e.scrollTop >= 103 && !this.data.isFixed) {
      this.setData({
        isFixed: true
      })
    } else if (e.scrollTop < 103 && this.data.isFixed) {
      this.setData({
        isFixed: false
      })
    }
  },
  onReachBottom() {
    this.loadMore()
  },
  async getCategoryList() {
    let grade = this.data.userInfo.grade
    let categoryList = await getCategoryList({
      grade
    })
    console.log(categoryList);
    this.setData({
      categoryList
    })
  },
  selectType({
    target
  }) {
    if (target.dataset.type) {
      this.setData({
        currentType: target.dataset.type
      })
      this.resetData()
      this.selectComponent('#worksList').resetAudio()
    }
  },
})