const cartApi = require('../../api/cart') const productApi = require('../../api/product') const productLikeApi = require('../../api/product-like') const commentApi = require('../../api/comment') const shopApi = require('../../api/shop') const wishlistApi = require('../../api/wishlist') const actionGuard = require('../../utils/action-guard') const auth = require('../../utils/auth') const navigation = require('../../utils/navigation') const theme = require('../../utils/theme') const { getSignedUrl, resolveImageList } = require('../../utils/file') const { DEFAULT_PRODUCT_IMAGE } = require('../../utils/config') const { formatPrice, getProductTitle, splitCsv } = require('../../utils/format') const { runWithLoading } = require('../../utils/loading') function parseTimeRange(businessHours) { /** * `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 (!businessHours) { return null } const matched = String(businessHours).replace(/\s+/g, '').match(/(\d{1,2}:\d{2}).*?(\d{1,2}:\d{2})/) /** * `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 (!matched) { return null } return { start: matched[1], end: matched[2] } } function estimateEarliestBookable(businessHours) { const range = parseTimeRange(businessHours) /** * `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 (!range) { return businessHours || '以门店安排为准' } const next = new Date(Date.now() + 30 * 60 * 1000) const openTime = new Date(next) const closeTime = new Date(next) const startParts = range.start.split(':').map(Number) const endParts = range.end.split(':').map(Number) openTime.setHours(startParts[0], startParts[1], 0, 0) closeTime.setHours(endParts[0], endParts[1], 0, 0) /** * `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 (next <= openTime) { return `今天 ${range.start}` } /** * `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 (next >= closeTime) { return `明天 ${range.start}` } const month = String(next.getMonth() + 1).padStart(2, '0') const date = String(next.getDate()).padStart(2, '0') const hour = String(next.getHours()).padStart(2, '0') const minute = String(next.getMinutes()).padStart(2, '0') return `${month}-${date} ${hour}:${minute}` } /** * product-detail 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(theme.pageThemeData(getApp().globalData.shopTheme), { loading: true, loadError: '', productId: '', product: null, productImages: [], shopInfo: null, comments: [], commentText: '', replyTarget: null, isFavorite: false, isLiked: false, artistCountText: '门店安排', earliestBookableText: '以门店安排为准' }), /** * `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.setData({ productId: options && options.id ? options.id : '' }) this.loadProductDetail() }, async onPullDownRefresh() { await this.loadProductDetail() wx.stopPullDownRefresh() }, async loadProductDetail() { const productId = this.data.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 (!productId) { this.setData({ loading: false, loadError: '作品 ID 不存在' }) return } this.setData({ loading: true, loadError: '' }) try { const product = await productApi.getProductById(productId) const productImages = await resolveImageList(product.imageFileIds, DEFAULT_PRODUCT_IMAGE) const shopInfo = product.shopId ? await shopApi.getShopById(product.shopId) : null if (shopInfo) { const shopTheme = theme.resolveShopTheme(shopInfo) this.setData(theme.pageThemeData(shopTheme)) if (shopTheme.backgroundImageFileId) { try { const backgroundImageUrl = await getSignedUrl(shopTheme.backgroundImageFileId) if (backgroundImageUrl) { this.setData(theme.pageThemeData(shopTheme, backgroundImageUrl)) } } catch (error) {} } } const artistCount = typeof product.availableBookableArtistCount === 'number' ? product.availableBookableArtistCount : splitCsv(product.bookableArtists).length const formattedProduct = { ...product, displayTitle: getProductTitle(product), priceText: `¥${formatPrice(product.price)}`, descriptionText: product.description || '商家还没有补充作品说明。' } this.setData({ product: formattedProduct, productImages, shopInfo, artistCountText: artistCount > 0 ? `${artistCount} 位可预约` : (product.bookableArtistRestricted ? '暂时没有' : '门店安排'), earliestBookableText: estimateEarliestBookable(shopInfo && shopInfo.businessHours) }) await this.loadComments() if (auth.isLoggedIn()) { await this.loadInteractionStatus() } else { this.setData({ isFavorite: false, isLiked: false }) } } catch (error) { this.setData({ loadError: error.message || '作品详情加载失败' }) } finally { this.setData({ loading: false }) } }, async loadInteractionStatus() { const product = this.data.product /** * `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 || !product.id) { return } try { const [isFavorite, isLiked] = await Promise.all([ wishlistApi.checkWishlist(product.id), productLikeApi.checkLikeStatus(product.id) ]) this.setData({ isFavorite: Boolean(isFavorite), isLiked: Boolean(isLiked) }) } catch (error) {} }, async loadComments() { const product = this.data.product /** * `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 || !product.id) { this.setData({ comments: [] }) return } try { const comments = await commentApi.listByProduct(product.id) this.setData({ comments: Array.isArray(comments) ? comments : [] }) } catch (error) { this.setData({ comments: [] }) } }, /** * `handleBack` 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. */ handleBack() { navigation.goBack('/pages/products/index') }, /** * `handlePreviewImage` 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. */ handlePreviewImage(event) { const current = event.currentTarget.dataset.url /** * `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 (!current) { return } wx.previewImage({ current, urls: this.data.productImages }) }, /** * `handleOpenShop` 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. */ handleOpenShop() { const shopInfo = this.data.shopInfo /** * `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 (!shopInfo || !shopInfo.id) { return } navigation.navigate('/pages/shop-detail/index', { id: shopInfo.id, returnTo: navigation.getCurrentPageUrl() }) }, async handleToggleFavorite() { const product = this.data.product if (!product || !product.id || !navigation.ensureLogin('收藏作品')) { return } try { await actionGuard.run(this, `wishlist:toggle:${product.id}`, async () => { const nextFavorite = !this.data.isFavorite /** * `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.isFavorite) { await runWithLoading(() => wishlistApi.removeFromWishlist(product.id)) product.collectCount = Math.max(0, Number(product.collectCount || 0) - 1) } else { await runWithLoading(() => wishlistApi.addToWishlist(product.id)) product.collectCount = Number(product.collectCount || 0) + 1 } this.setData({ isFavorite: nextFavorite, product }) wx.showToast({ title: nextFavorite ? '已加入收藏' : '已取消收藏', icon: 'none' }) }, { message: '操作进行中,请勿重复点击' }) } catch (error) { if (actionGuard.isGuardError(error)) { return } wx.showToast({ title: error.message || '收藏操作失败', icon: 'none' }) } }, async handleToggleLike() { const product = this.data.product if (!product || !product.id || !navigation.ensureLogin('点赞作品')) { return } try { await actionGuard.run(this, `like:toggle:${product.id}`, async () => { const nextLiked = !this.data.isLiked /** * `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.isLiked) { await runWithLoading(() => productLikeApi.unlikeProduct(product.id)) product.likeCount = Math.max(0, Number(product.likeCount || 0) - 1) } else { await runWithLoading(() => productLikeApi.likeProduct(product.id)) product.likeCount = Number(product.likeCount || 0) + 1 } this.setData({ isLiked: nextLiked, product }) wx.showToast({ title: nextLiked ? '已点赞' : '已取消点赞', icon: 'none' }) }, { message: '操作进行中,请勿重复点击' }) } catch (error) { if (actionGuard.isGuardError(error)) { return } wx.showToast({ title: error.message || '点赞操作失败', icon: 'none' }) } }, async handleAddToCart() { const product = this.data.product if (!product || !product.id || !navigation.ensureLogin('加购')) { return } try { await actionGuard.run(this, `cart:add:${product.id}`, () => runWithLoading(() => cartApi.addToCart({ productId: product.id, quantity: 1 })), { message: '购物车处理中,请勿重复操作' }) await getApp().updateCartBadge() wx.showToast({ title: '已加入购物车', icon: 'none' }) } catch (error) { if (actionGuard.isGuardError(error)) { return } wx.showToast({ title: error.message || '加入购物车失败', icon: 'none' }) } }, async handleBuyNow() { const product = this.data.product if (!product || !product.id || !navigation.ensureLogin('预约下单')) { return } try { await actionGuard.run(this, `cart:buy-now:${product.id}`, () => runWithLoading(() => cartApi.addToCart({ productId: product.id, quantity: 1 })), { message: '操作进行中,请勿重复点击' }) await getApp().updateCartBadge() wx.switchTab({ url: '/pages/cart/index' }) } catch (error) { if (actionGuard.isGuardError(error)) { return } wx.showToast({ title: error.message || '操作失败', icon: 'none' }) } } , /** * `handleCommentInput` 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. */ handleCommentInput(event) { this.setData({ commentText: event.detail.value }) }, /** * `handleReply` 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. */ handleReply(event) { const comment = event.currentTarget.dataset.comment this.setData({ replyTarget: comment || null }) }, async handleSubmitComment() { const product = this.data.product const content = String(this.data.commentText || '').trim() if (!product || !product.id || !navigation.ensureLogin('发表评论')) { 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 (!content) { wx.showToast({ title: '请输入评论内容', icon: 'none' }) return } try { await commentApi.create({ productId: product.id, shopId: product.shopId, parentCommentId: this.data.replyTarget ? this.data.replyTarget.id : null, commentContent: content }) this.setData({ commentText: '', replyTarget: null }) await this.loadComments() wx.showToast({ title: '评论已发布', icon: 'none' }) } catch (error) { wx.showToast({ title: error.message || '评论发布失败', icon: 'none' }) } } })