let util = require('../../utils/util')
let api = require('../../config/api')
let app = getApp()

Page({
  data: {
		fixed: false,
		userInfo: { nickname: '点击登录', avatar: '/static/images/avatar.png' },
		userMenus: [
			{ url: '/packageUser/collect/collect', name: '收藏', value: 0 },
      { url: '/packageUser/footprint/footprint', name: '浏览足迹', value: 0 }
		],

		categoryList: [
			{ pic: "https://www.qdeasydo.com/api/folder/500f9715-cf28-485e-8df3-11bd5127935c", id: 100101307 },
			{ pic: "https://www.qdeasydo.com/api/folder/6eb7bb4a-dbea-489f-a010-416bf6a8ddd2", id: 100101311 },
			{ pic: "https://www.qdeasydo.com/api/folder/e061f829-268c-437e-8734-9a34b5c4b2f6", id: 100101313 },
			{ pic: "https://www.qdeasydo.com/api/folder/2ac688c9-3218-4b1d-a3f3-83f0b420cb3e", id: 100101316 }
		]
  },

  onLoad: function() {
    this.setData({ navHeight: app.globalData.navHeight })
  },

  onShow: function() {
		let userInfo = { nickname: '点击登录', avatar: '/static/images/avatar.png' }
    if (wx.getStorageSync('token')) {
			userInfo = { ...this.data.userInfo, ...wx.getStorageSync('userInfo') }
			this.getUser()
		}
		this.setData({ userInfo })
	},

	// 获取用户的登录信息
  getUser() {
    util.showLoad('加载中')
    util.request(api.UserIndex).then(res => {
      util.hideLoad()
      if (res.errno === 0) {
				let { userMenus } = this.data
				let { collectCount, footPrintCount } = res.data
        userMenus[0].value = collectCount
        userMenus[1].value = footPrintCount
				this.setData({ userMenus })
      } else util.showErrorToast(res.errmsg)
    }).catch(() => {
      util.hideLoad()
      util.showErrorToast('网络连接失败')
    })
  },
	
	onPageScroll({ scrollTop }) {
		const fixed = scrollTop > app.globalData.navHeight ? true : false
		this.setData({ fixed })
	},

	redirect({ currentTarget }) {
		const { url } = currentTarget.dataset
		if (!wx.getStorageSync('token')) {
			wx.navigateTo({ url: '/packageLogin/login/login' })
			return
		}

		wx.navigateTo({ url })
	},

	toCategory({ currentTarget }) {
    const { id } = currentTarget.dataset
		app.globalData.menuId = id
    wx.switchTab({ url: '/pages/catalog/catalog' })
	}
})