yingsa/miniprogram/pages/index/index.js

125 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

const app = getApp()
const util = require('../../utils/util')
Page({
data: {
currentStore: null,
gender: '',
list: [],
loading: false,
page: 1,
pageSize: 20,
hasMore: true
},
onLoad() {
this.initData()
},
onShow() {
const newStore = app.globalData.currentStore
const oldStoreId = this.data.currentStore?.storeId
// 检查门店是否切换
if (newStore && newStore.storeId !== oldStoreId) {
this.setData({
currentStore: newStore,
page: 1,
hasMore: true,
list: []
})
this.fetchData()
} else if (app.globalData.storeChanged) {
// 全局标记门店已切换
app.globalData.storeChanged = false
this.setData({
currentStore: newStore,
page: 1,
hasMore: true,
list: []
})
this.fetchData()
}
},
onPullDownRefresh() {
this.setData({ page: 1, hasMore: true })
this.fetchData().then(() => {
wx.stopPullDownRefresh()
})
},
onReachBottom() {
if (this.data.hasMore && !this.data.loading) {
this.loadMore()
}
},
async initData() {
// 检查是否已登录(有 token
if (!app.globalData.token) {
// 未登录,跳转到用户页面进行登录
wx.switchTab({ url: '/pages/user/index' })
return
}
// 获取当前门店
try {
const store = await app.getCurrentStore()
this.setData({ currentStore: store })
this.fetchData()
} catch (e) {
console.error('获取门店失败:', e)
// 如果是认证失败,跳转到登录页
if (e.code === 401) {
wx.switchTab({ url: '/pages/user/index' })
}
}
},
async fetchData() {
if (!this.data.currentStore?.storeId) return
this.setData({ loading: true })
try {
const res = await app.request('/api/ladder/ranking', {
store_id: this.data.currentStore.storeId,
gender: this.data.gender,
page: this.data.page,
pageSize: this.data.pageSize
})
const list = res.data.list || []
this.setData({
list: this.data.page === 1 ? list : [...this.data.list, ...list],
hasMore: list.length >= this.data.pageSize
})
} catch (e) {
console.error('获取排名失败:', e)
} finally {
this.setData({ loading: false })
}
},
loadMore() {
this.setData({ page: this.data.page + 1 })
this.fetchData()
},
setGender(e) {
const gender = e.currentTarget.dataset.gender
this.setData({ gender, page: 1, hasMore: true })
this.fetchData()
},
selectStore() {
wx.navigateTo({ url: '/pages/store/index' })
},
viewPlayer(e) {
const id = e.currentTarget.dataset.id
wx.navigateTo({ url: `/pages/player/index?id=${id}` })
}
})