626 lines
20 KiB
JavaScript
626 lines
20 KiB
JavaScript
/**
|
|
* Purpose: auth supports index.js by holding or executing the auth page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const auth = require('../../utils/auth')
|
|
/**
|
|
* Purpose: cache supports index.js by holding or executing the cache page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const cache = require('../../utils/cache')
|
|
/**
|
|
* Purpose: tagApi supports index.js by holding or executing the tag api page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const tagApi = require('../../api/tag')
|
|
/**
|
|
* Purpose: productApi supports index.js by holding or executing the product api page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const productApi = require('../../api/product')
|
|
/**
|
|
* Purpose: cartApi supports index.js by holding or executing the cart api page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const cartApi = require('../../api/cart')
|
|
/**
|
|
* Purpose: actionGuard supports index.js by holding or executing the action guard page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const actionGuard = require('../../utils/action-guard')
|
|
const { buildProductCards } = require('../../utils/product')
|
|
/**
|
|
* Purpose: navigation supports index.js by holding or executing the navigation page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const navigation = require('../../utils/navigation')
|
|
/**
|
|
* Purpose: theme supports index.js by holding or executing the theme page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const theme = require('../../utils/theme')
|
|
const { runWithLoading } = require('../../utils/loading')
|
|
const { CACHE_TTL } = require('../../utils/config')
|
|
const {
|
|
createKeyboardSafeData,
|
|
attachKeyboardSafe,
|
|
detachKeyboardSafe,
|
|
handleKeyboardFocus,
|
|
handleKeyboardBlur,
|
|
resetKeyboardSafe
|
|
} = require('../../utils/keyboard-safe')
|
|
|
|
/**
|
|
* Purpose: ALL_CATEGORY supports index.js by holding or executing the all category page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const ALL_CATEGORY = '\u5168\u90e8'
|
|
/**
|
|
* Purpose: FILTER_BUSY_MESSAGE supports index.js by holding or executing the filter busy message page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const FILTER_BUSY_MESSAGE = '\u7b5b\u9009\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
|
|
/**
|
|
* Purpose: CART_BUSY_MESSAGE supports index.js by holding or executing the cart busy message page or API role.
|
|
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
|
|
*/
|
|
const CART_BUSY_MESSAGE = '\u8d2d\u7269\u8f66\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c'
|
|
|
|
/**
|
|
* products page logic.
|
|
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
|
|
*/
|
|
Page({
|
|
data: Object.assign(createKeyboardSafeData({
|
|
cursorSpacing: 96
|
|
}), theme.pageThemeData(getApp().globalData.shopTheme), {
|
|
initialized: false,
|
|
loading: false,
|
|
loadingMore: false,
|
|
categories: [ALL_CATEGORY],
|
|
filterGroups: [],
|
|
selectedTagId: '',
|
|
selectedCategory: ALL_CATEGORY,
|
|
searchKeyword: '',
|
|
products: [],
|
|
filterSummaryText: '',
|
|
page: 1,
|
|
pageSize: 10,
|
|
total: 0,
|
|
hasMore: false
|
|
}),
|
|
|
|
/**
|
|
* `onLoad` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
onLoad(options) {
|
|
this.filterRequestId = 0
|
|
this.ensureKeyboardSafe()
|
|
this.bootstrapPage(options || {})
|
|
},
|
|
|
|
async onShow() {
|
|
this.ensureKeyboardSafe()
|
|
const app = getApp()
|
|
const pendingFilter = app && app.globalData ? app.globalData.pendingProductFilter : null
|
|
|
|
if (this.data.initialized && pendingFilter && (pendingFilter.keyword || pendingFilter.tag)) {
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (app && app.globalData) {
|
|
app.globalData.pendingProductFilter = null
|
|
}
|
|
await this.applyFilter(pendingFilter)
|
|
return
|
|
}
|
|
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (this.data.initialized) {
|
|
await this.syncProductCartState()
|
|
}
|
|
},
|
|
|
|
/**
|
|
* `onHide` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
onHide() {
|
|
resetKeyboardSafe(this)
|
|
detachKeyboardSafe(this)
|
|
},
|
|
|
|
/**
|
|
* `onUnload` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
onUnload() {
|
|
resetKeyboardSafe(this)
|
|
detachKeyboardSafe(this)
|
|
},
|
|
|
|
async onPullDownRefresh() {
|
|
await this.loadProducts(true)
|
|
wx.stopPullDownRefresh()
|
|
},
|
|
|
|
/**
|
|
* `onReachBottom` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
onReachBottom() {
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (!this.data.hasMore || this.data.loadingMore) {
|
|
return
|
|
}
|
|
this.loadProducts(false)
|
|
},
|
|
|
|
/**
|
|
* `ensureKeyboardSafe` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
ensureKeyboardSafe() {
|
|
attachKeyboardSafe(this, {
|
|
cursorSpacing: 96,
|
|
spacerExtraRpx: 16
|
|
})
|
|
},
|
|
|
|
async bootstrapPage(options) {
|
|
this.setData({
|
|
loading: true
|
|
})
|
|
|
|
try {
|
|
await this.loadTags()
|
|
await this.applyInitialFilter(options)
|
|
this.setData({
|
|
initialized: true
|
|
})
|
|
} catch (error) {
|
|
wx.showToast({
|
|
title: error.message || '\u4f5c\u54c1\u5217\u8868\u52a0\u8f7d\u5931\u8d25',
|
|
icon: 'none'
|
|
})
|
|
} finally {
|
|
this.setData({
|
|
loading: false
|
|
})
|
|
}
|
|
},
|
|
|
|
async loadTags() {
|
|
const groups = await cache.remember('tags:filter-options', CACHE_TTL.tags, () => tagApi.getFilterOptions())
|
|
const normalizedGroups = (Array.isArray(groups) ? groups : []).map(group => ({
|
|
...group,
|
|
tags: (Array.isArray(group.tags) ? group.tags : []).map(tag => ({
|
|
...tag,
|
|
idText: String(tag.id)
|
|
}))
|
|
}))
|
|
this.setData({
|
|
filterGroups: normalizedGroups
|
|
})
|
|
},
|
|
|
|
async applyInitialFilter(options) {
|
|
const app = getApp()
|
|
const pendingFilter = app && app.globalData ? app.globalData.pendingProductFilter : null
|
|
if (pendingFilter && (pendingFilter.keyword || pendingFilter.tag)) {
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (app && app.globalData) {
|
|
app.globalData.pendingProductFilter = null
|
|
}
|
|
await this.applyFilter(pendingFilter)
|
|
return
|
|
}
|
|
|
|
await this.applyFilter(options || {})
|
|
},
|
|
|
|
async applyFilter(filter) {
|
|
const keyword = String(filter.keyword || '').trim()
|
|
const tag = String(filter.tag || '').trim()
|
|
const tagId = String(filter.tagId || '').trim()
|
|
const matchedTag = this.resolveFilterTag(tagId, tag)
|
|
|
|
this.setData({
|
|
searchKeyword: keyword,
|
|
selectedTagId: matchedTag ? String(matchedTag.id) : '',
|
|
selectedCategory: matchedTag ? (matchedTag.displayName || matchedTag.tagName) : ALL_CATEGORY,
|
|
page: 1,
|
|
total: 0,
|
|
hasMore: false
|
|
})
|
|
|
|
await this.loadProducts(true)
|
|
},
|
|
|
|
async loadProducts(reset) {
|
|
const requestId = ++this.filterRequestId
|
|
const nextPage = reset ? 1 : this.data.page + 1
|
|
|
|
this.setData(reset ? { loading: true } : { loadingMore: true })
|
|
|
|
try {
|
|
const keyword = String(this.data.searchKeyword || '').trim()
|
|
const tag = this.data.selectedCategory === ALL_CATEGORY ? '' : this.data.selectedCategory
|
|
const tagIds = this.data.selectedTagId || ''
|
|
const result = await productApi.getProductPage({
|
|
page: nextPage,
|
|
size: this.data.pageSize,
|
|
keyword: keyword || undefined,
|
|
tag: tagIds ? undefined : (tag || undefined),
|
|
tagIds: tagIds || undefined
|
|
})
|
|
const cards = await buildProductCards(result && result.list ? result.list : [])
|
|
const displayCards = await this.attachCartState(cards)
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (requestId !== this.filterRequestId) {
|
|
return
|
|
}
|
|
|
|
const merged = reset ? displayCards : this.data.products.concat(displayCards)
|
|
const total = Number(result && result.total) || 0
|
|
this.setData({
|
|
products: merged,
|
|
page: nextPage,
|
|
total,
|
|
hasMore: merged.length < total,
|
|
filterSummaryText: this.buildFilterSummary(keyword, tag, total)
|
|
})
|
|
} catch (error) {
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (requestId !== this.filterRequestId) {
|
|
return
|
|
}
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (reset) {
|
|
this.setData({
|
|
products: [],
|
|
total: 0,
|
|
hasMore: false,
|
|
filterSummaryText: ''
|
|
})
|
|
}
|
|
wx.showToast({
|
|
title: error.message || '\u4f5c\u54c1\u5217\u8868\u52a0\u8f7d\u5931\u8d25',
|
|
icon: 'none'
|
|
})
|
|
} finally {
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (requestId === this.filterRequestId) {
|
|
this.setData({
|
|
loading: false,
|
|
loadingMore: false
|
|
})
|
|
}
|
|
}
|
|
},
|
|
|
|
/**
|
|
* `buildFilterSummary` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
buildFilterSummary(keyword, tag, total) {
|
|
const chips = []
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (tag) {
|
|
chips.push(tag)
|
|
}
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (keyword) {
|
|
chips.push(`\u641c\u7d22\uff1a${keyword}`)
|
|
}
|
|
chips.push(`\u5171 ${Number(total || 0)} \u4e2a`)
|
|
return chips.join(' \u00b7 ')
|
|
},
|
|
|
|
/**
|
|
* Purpose: flattenFilterTags returns all scene-filter tags for query matching.
|
|
* Usage: call before applying route or pending filters.
|
|
*/
|
|
flattenFilterTags() {
|
|
return (Array.isArray(this.data.filterGroups) ? this.data.filterGroups : [])
|
|
.reduce((list, group) => list.concat(Array.isArray(group.tags) ? group.tags : []), [])
|
|
},
|
|
|
|
/**
|
|
* Purpose: resolveFilterTag matches route filter text or id to a visible scene tag.
|
|
* Usage: call from applyFilter so old tag query links still select the right chip.
|
|
*/
|
|
resolveFilterTag(tagId, tagName) {
|
|
const tags = this.flattenFilterTags()
|
|
if (tagId) {
|
|
const byId = tags.find(item => String(item.id) === tagId)
|
|
if (byId) {
|
|
return byId
|
|
}
|
|
}
|
|
if (!tagName) {
|
|
return null
|
|
}
|
|
return tags.find(item => item.tagName === tagName || item.displayName === tagName) || null
|
|
},
|
|
|
|
/**
|
|
* `normalizeId` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
normalizeId(value) {
|
|
return value === undefined || value === null ? '' : String(value)
|
|
},
|
|
|
|
async fetchCartProductIdSet() {
|
|
if (!auth.isLoggedIn()) {
|
|
this.cartProductIdSet = new Set()
|
|
return this.cartProductIdSet
|
|
}
|
|
|
|
try {
|
|
const cartList = await cartApi.getCartList()
|
|
const idSet = new Set(
|
|
(Array.isArray(cartList) ? cartList : [])
|
|
.map(item => this.normalizeId(item && item.productId))
|
|
.filter(Boolean)
|
|
)
|
|
this.cartProductIdSet = idSet
|
|
return idSet
|
|
} catch (error) {
|
|
this.cartProductIdSet = new Set()
|
|
return this.cartProductIdSet
|
|
}
|
|
},
|
|
|
|
async attachCartState(cards) {
|
|
const idSet = await this.fetchCartProductIdSet()
|
|
return this.markCardsInCart(cards, idSet)
|
|
},
|
|
|
|
/**
|
|
* `markCardsInCart` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
markCardsInCart(cards, idSet) {
|
|
const productIdSet = idSet || new Set()
|
|
return (Array.isArray(cards) ? cards : []).map(item => ({
|
|
...item,
|
|
inCart: productIdSet.has(this.normalizeId(item && item.id))
|
|
}))
|
|
},
|
|
|
|
async syncProductCartState() {
|
|
const idSet = await this.fetchCartProductIdSet()
|
|
this.setData({
|
|
products: this.markCardsInCart(this.data.products, idSet)
|
|
})
|
|
},
|
|
|
|
/**
|
|
* `markProductInCart` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
markProductInCart(productId) {
|
|
const normalizedId = this.normalizeId(productId)
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (!normalizedId) {
|
|
return
|
|
}
|
|
|
|
this.cartProductIdSet = this.cartProductIdSet || new Set()
|
|
this.cartProductIdSet.add(normalizedId)
|
|
|
|
this.setData({
|
|
products: this.data.products.map(item => (
|
|
this.normalizeId(item && item.id) === normalizedId
|
|
? {
|
|
...item,
|
|
inCart: true
|
|
}
|
|
: item
|
|
))
|
|
})
|
|
},
|
|
|
|
/**
|
|
* `handleSearchInput` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
handleSearchInput(event) {
|
|
this.setData({
|
|
searchKeyword: event.detail.value
|
|
})
|
|
},
|
|
|
|
/**
|
|
* `handleSearchFocus` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
handleSearchFocus(event) {
|
|
handleKeyboardFocus(this, event)
|
|
},
|
|
|
|
/**
|
|
* `handleSearchBlur` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
handleSearchBlur() {
|
|
handleKeyboardBlur(this)
|
|
},
|
|
|
|
async handleSearchConfirm() {
|
|
resetKeyboardSafe(this)
|
|
try {
|
|
await actionGuard.run(this, 'products:search', async () => {
|
|
this.setData({
|
|
selectedCategory: ALL_CATEGORY,
|
|
selectedTagId: '',
|
|
page: 1
|
|
})
|
|
await runWithLoading(() => this.loadProducts(true))
|
|
}, {
|
|
message: FILTER_BUSY_MESSAGE
|
|
})
|
|
} catch (error) {
|
|
if (actionGuard.isGuardError(error)) {
|
|
return
|
|
}
|
|
wx.showToast({
|
|
title: error.message || '\u7b5b\u9009\u5931\u8d25',
|
|
icon: 'none'
|
|
})
|
|
}
|
|
},
|
|
|
|
async handleSelectCategory(event) {
|
|
const category = event.currentTarget.dataset.category
|
|
const tagId = event.currentTarget.dataset.tagId ? String(event.currentTarget.dataset.tagId) : ''
|
|
resetKeyboardSafe(this)
|
|
try {
|
|
await actionGuard.run(this, `products:category:${category}:${tagId}`, async () => {
|
|
this.setData({
|
|
selectedCategory: category,
|
|
selectedTagId: tagId,
|
|
searchKeyword: '',
|
|
page: 1
|
|
})
|
|
await runWithLoading(() => this.loadProducts(true))
|
|
}, {
|
|
message: FILTER_BUSY_MESSAGE
|
|
})
|
|
} catch (error) {
|
|
if (actionGuard.isGuardError(error)) {
|
|
return
|
|
}
|
|
wx.showToast({
|
|
title: error.message || '\u7b5b\u9009\u5931\u8d25',
|
|
icon: 'none'
|
|
})
|
|
}
|
|
},
|
|
|
|
async handleResetFilters() {
|
|
resetKeyboardSafe(this)
|
|
try {
|
|
await actionGuard.run(this, 'products:reset', async () => {
|
|
this.setData({
|
|
selectedCategory: ALL_CATEGORY,
|
|
selectedTagId: '',
|
|
searchKeyword: '',
|
|
page: 1
|
|
})
|
|
await runWithLoading(() => this.loadProducts(true))
|
|
}, {
|
|
message: FILTER_BUSY_MESSAGE
|
|
})
|
|
} catch (error) {
|
|
if (actionGuard.isGuardError(error)) {
|
|
return
|
|
}
|
|
wx.showToast({
|
|
title: error.message || '\u7b5b\u9009\u5931\u8d25',
|
|
icon: 'none'
|
|
})
|
|
}
|
|
},
|
|
|
|
/**
|
|
* `handleProductSelect` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
handleProductSelect(event) {
|
|
const product = event.detail || {}
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (!product.id) {
|
|
return
|
|
}
|
|
|
|
navigation.navigate('/pages/product-detail/index', {
|
|
id: product.id
|
|
})
|
|
},
|
|
|
|
async handleQuickAdd(event) {
|
|
const product = event.detail || {}
|
|
const productId = this.normalizeId(product.id)
|
|
/**
|
|
* `if` page method. Use this from WXML event bindings or lifecycle hooks.
|
|
* Call guide: read or update page data with `this.setData(...)` inside the method when state changes.
|
|
*/
|
|
if (!productId) {
|
|
return
|
|
}
|
|
|
|
if (!navigation.ensureLogin('\u52a0\u5165\u8d2d\u7269\u8f66')) {
|
|
return
|
|
}
|
|
|
|
if (this.cartProductIdSet && this.cartProductIdSet.has(productId)) {
|
|
wx.showToast({
|
|
title: '\u8d2d\u7269\u8f66\u5df2\u6709',
|
|
icon: 'none'
|
|
})
|
|
return
|
|
}
|
|
|
|
try {
|
|
await actionGuard.run(this, `cart:add:${productId}`, () => runWithLoading(() => cartApi.addToCart({
|
|
productId,
|
|
quantity: 1
|
|
})), {
|
|
message: CART_BUSY_MESSAGE
|
|
})
|
|
this.markProductInCart(productId)
|
|
await getApp().updateCartBadge()
|
|
wx.showToast({
|
|
title: '\u5df2\u52a0\u5165\u8d2d\u7269\u8f66',
|
|
icon: 'none'
|
|
})
|
|
} catch (error) {
|
|
if (actionGuard.isGuardError(error)) {
|
|
return
|
|
}
|
|
wx.showToast({
|
|
title: error.message || '\u52a0\u5165\u8d2d\u7269\u8f66\u5931\u8d25',
|
|
icon: 'none'
|
|
})
|
|
}
|
|
}
|
|
})
|