Files
JayuCloud/WeChatProgram/pages/home/index.js
T

299 lines
7.2 KiB
JavaScript

const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const cache = require('../../utils/cache')
const { buildProductCards } = require('../../utils/product')
const { resolveImageList } = require('../../utils/file')
const { DEFAULT_SHOP_IMAGE, CACHE_TTL } = require('../../utils/config')
const {
createKeyboardSafeData,
attachKeyboardSafe,
detachKeyboardSafe,
handleKeyboardFocus,
handleKeyboardBlur,
resetKeyboardSafe
} = require('../../utils/keyboard-safe')
const productApi = require('../../api/product')
const shopApi = require('../../api/shop')
const userApi = require('../../api/user')
Page({
data: Object.assign(createKeyboardSafeData({
cursorSpacing: 96
}), {
initialized: false,
loading: false,
loadingMore: false,
isLoggedIn: false,
userInfo: null,
navTitle: '游客模式',
greeting: '欢迎来到 Yumi Nail',
displayName: '先看看门店和作品',
searchKeyword: '',
bannerImages: [],
featuredItems: [],
popularItems: [],
popularPage: 1,
pageSize: 6,
hasMore: false,
popularTotal: 0
}),
onLoad() {
this.homeRequestId = 0
this.ensureKeyboardSafe()
this.loadHomeData()
},
onShow() {
this.ensureKeyboardSafe()
this.syncUserState()
if (this.data.initialized && this.data.isLoggedIn) {
this.loadUserProfile()
}
},
onHide() {
resetKeyboardSafe(this)
detachKeyboardSafe(this)
},
onUnload() {
resetKeyboardSafe(this)
detachKeyboardSafe(this)
},
async onPullDownRefresh() {
cache.removeByPrefix('home:')
await this.loadHomeData()
wx.stopPullDownRefresh()
},
onReachBottom() {
if (!this.data.hasMore || this.data.loadingMore) {
return
}
this.loadPopularProducts(false)
},
ensureKeyboardSafe() {
attachKeyboardSafe(this, {
cursorSpacing: 96,
spacerExtraRpx: 24
})
},
syncUserState() {
const app = getApp()
const userInfo = auth.getStoredUserInfo()
const isLoggedIn = auth.isLoggedIn()
const navTitle = userInfo && String(userInfo.shopName || '').trim()
? String(userInfo.shopName).trim()
: '游客模式'
if (app) {
app.globalData.userInfo = userInfo
app.globalData.isLoggedIn = isLoggedIn
}
this.setData({
isLoggedIn,
userInfo,
navTitle,
greeting: isLoggedIn ? '欢迎回来' : '游客模式',
displayName: isLoggedIn
? ((userInfo && userInfo.nickname) || 'Yumi 用户')
: '先逛逛喜欢的款式和门店'
})
},
async loadUserProfile() {
if (!auth.isLoggedIn()) {
this.syncUserState()
return
}
try {
const userInfo = await userApi.getUserInfo()
getApp().refreshUserInfo(userInfo)
this.syncUserState()
} catch (error) {}
},
async loadHomeData() {
const requestId = ++this.homeRequestId
this.setData({ loading: true })
this.syncUserState()
try {
await Promise.all([
this.loadUserProfile(),
this.loadBannerImages(requestId),
this.loadFeaturedProducts(requestId),
this.loadPopularProducts(true, requestId)
])
if (requestId === this.homeRequestId) {
this.setData({
initialized: true
})
}
} catch (error) {
wx.showToast({
title: error.message || '首页加载失败',
icon: 'none'
})
} finally {
if (requestId === this.homeRequestId) {
this.setData({ loading: false })
}
}
},
async loadBannerImages(requestId) {
const banners = await cache.remember('home:banners', CACHE_TTL.banner, async () => {
const shops = await shopApi.getPublicShops()
const list = Array.isArray(shops) ? shops : []
const resolved = await Promise.all(list.slice(0, 6).map(async (shop, index) => {
const imageIds = shop.coverImageFileId || shop.imageFileIds
const urls = await resolveImageList(imageIds, DEFAULT_SHOP_IMAGE)
return {
id: `${shop.id}-${index}`,
shopId: shop.id,
shopName: shop.shopName,
businessHours: shop.businessHours || '欢迎到店体验',
imageUrl: urls[0]
}
}))
return resolved.filter(item => item.imageUrl)
})
if (requestId === this.homeRequestId) {
this.setData({
bannerImages: Array.isArray(banners) ? banners : []
})
}
},
async loadFeaturedProducts(requestId) {
const items = await cache.remember('home:featured', CACHE_TTL.homeList, async () => {
const result = await productApi.getProductPage({
page: 1,
size: 6,
tag: '精选'
})
return buildProductCards(result && result.list ? result.list : [])
})
if (requestId === this.homeRequestId) {
this.setData({
featuredItems: Array.isArray(items) ? items : []
})
}
},
async loadPopularProducts(reset, requestId) {
const currentRequestId = requestId || this.homeRequestId
const nextPage = reset ? 1 : this.data.popularPage + 1
const loadingState = reset ? { loading: true } : { loadingMore: true }
this.setData(loadingState)
try {
const result = await productApi.getProductPage({
page: nextPage,
size: this.data.pageSize,
tag: '热门'
})
const cards = await buildProductCards(result && result.list ? result.list : [])
if (currentRequestId !== this.homeRequestId) {
return
}
const mergedItems = reset ? cards : this.data.popularItems.concat(cards)
const total = Number(result && result.total) || 0
this.setData({
popularItems: mergedItems,
popularPage: nextPage,
popularTotal: total,
hasMore: mergedItems.length < total
})
} catch (error) {
if (currentRequestId !== this.homeRequestId) {
return
}
wx.showToast({
title: error.message || '热门作品加载失败',
icon: 'none'
})
} finally {
if (currentRequestId === this.homeRequestId) {
this.setData({
loadingMore: false
})
}
}
},
handleSearchInput(event) {
this.setData({
searchKeyword: event.detail.value
})
},
handleSearchFocus(event) {
handleKeyboardFocus(this, event)
},
handleSearchBlur() {
handleKeyboardBlur(this)
},
handleSearchConfirm() {
resetKeyboardSafe(this)
navigation.openProducts({
keyword: this.data.searchKeyword.trim()
})
},
handleBannerTap(event) {
const shopId = event.currentTarget.dataset.shopId
if (!shopId) {
return
}
navigation.navigate('/pages/shop-detail/index', {
id: shopId,
returnTo: navigation.getCurrentPageUrl()
})
},
handleProfileTap() {
if (this.data.isLoggedIn) {
navigation.switchTab('/pages/profile/index')
return
}
navigation.openAuth()
},
handleProductSelect(event) {
const product = event.detail || {}
if (!product.id) {
return
}
navigation.navigate('/pages/product-detail/index', {
id: product.id
})
},
handleSeeAllFeatured() {
navigation.openProducts({
tag: '精选'
})
},
handleSeeAllPopular() {
navigation.openProducts({
tag: '热门'
})
}
})