const auth = require('../../utils/auth') const cache = require('../../utils/cache') const tagApi = require('../../api/tag') const productApi = require('../../api/product') const cartApi = require('../../api/cart') const actionGuard = require('../../utils/action-guard') const { buildProductCards } = require('../../utils/product') const navigation = require('../../utils/navigation') 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') const ALL_CATEGORY = '\u5168\u90e8' const FILTER_BUSY_MESSAGE = '\u7b5b\u9009\u5904\u7406\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u64cd\u4f5c' 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], 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 tags = await cache.remember('tags:all', CACHE_TTL.tags, () => tagApi.getAllTags()) const names = Array.isArray(tags) ? tags.map(item => item.tagName).filter(Boolean) : [] this.setData({ categories: [ALL_CATEGORY].concat(names) }) }, 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() this.setData({ searchKeyword: keyword, selectedCategory: tag && this.data.categories.includes(tag) ? tag : 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 result = await productApi.getProductPage({ page: nextPage, size: this.data.pageSize, keyword: keyword || undefined, tag: tag || 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 ') }, /** * `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, 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 resetKeyboardSafe(this) try { await actionGuard.run(this, `products:category:${category}`, async () => { this.setData({ selectedCategory: category, 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, 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' }) } } })