const app = getApp()
import {
  getBannerList
} from '~/api/global'
import share from '~/mixins/share'
import {
  getSelfRead,
  getFavoritesList
} from '~/api/user'
import {
  getFollowWorks
} from '~/api/works'
import reachBottom from '~/mixins/reachBottom'
import {
  createStoreBindings
} from 'mobx-miniprogram-bindings'
import {
  store
} from '~/store/index'
Page({
  behaviors: [reachBottom, share],
  data: {
    navBarHeight: app.globalData.navBarHeight,
    bannerList: [],
    // 4关注作品,5我的作品,6收藏作品
    currentType: '4',
    isFixed: false
  },
  onShow() {
    if (typeof this.getTabBar === 'function') {
      this.getTabBar().setData({
        selected: 2
      })
    }
    this.getLocUserInfo()
    if (Object.keys(this.data.userInfo).length > 0) {
      this.requestAgain()
    } else {
      getApp().callBack = (res) => {
        this.getLocUserInfo()
        this.requestAgain()
      }
    }
    this.getBannerList()
  },
  loadMore() {
    if (this.data.currentType == '4') {
      this.getData(getFollowWorks, {})
    } else if (this.data.currentType == '5') {
      this.getData(getSelfRead, {})
    } else if (this.data.currentType == '6') {
      this.getData(getFavoritesList, {})
    }
  },
  async getBannerList() {
    let bannerList = await getBannerList({
      grade: this.data.userInfo.grade,
    })
    this.setData({
      bannerList,
    })
  },
  changeType({
    target
  }) {
    if (target.dataset.type) {
      let workListDom = this.selectComponent('#worksList')
      if (workListDom) {
        this.selectComponent('#worksList').resetAudio()
      }
      this.setData({
        currentType: target.dataset.type
      })
      this.requestAgain()
    }
  },
  /**
   * 监听页面滚动事件
   */
  onPageScroll(e) {
    if (e.scrollTop >= 110 && !this.data.isFixed) {
      this.setData({
        isFixed: true
      })
    } else if (e.scrollTop < 20 && this.data.isFixed) {
      this.setData({
        isFixed: false
      })
    }
  },
  requestAgain() {
    this.resetData()
  },
  async getLocUserInfo() {
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: {
        userInfo: 'userInfo'
      },
    })
    this.storeBindings.updateStoreBindings()
  },
  onUnload() {
    this.storeBindings.destroyStoreBindings()
  },
})