Files
JayuCloud/WeChatProgram/pages/product-detail/index.js
T

302 lines
7.7 KiB
JavaScript

const cartApi = require('../../api/cart')
const productApi = require('../../api/product')
const productLikeApi = require('../../api/product-like')
const shopApi = require('../../api/shop')
const wishlistApi = require('../../api/wishlist')
const auth = require('../../utils/auth')
const navigation = require('../../utils/navigation')
const { 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 (!businessHours) {
return null
}
const matched = String(businessHours).replace(/\s+/g, '').match(/(\d{1,2}:\d{2}).*?(\d{1,2}:\d{2})/)
if (!matched) {
return null
}
return {
start: matched[1],
end: matched[2]
}
}
function estimateEarliestBookable(businessHours) {
const range = parseTimeRange(businessHours)
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 (next <= openTime) {
return `今天 ${range.start}`
}
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}`
}
Page({
data: {
loading: true,
loadError: '',
productId: '',
product: null,
productImages: [],
shopInfo: null,
isFavorite: false,
isLiked: false,
artistCountText: '门店安排',
earliestBookableText: '以门店安排为准'
},
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 (!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
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)
})
if (auth.isLoggedIn()) {
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 (!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) {}
},
handleBack() {
navigation.goBack('/pages/products/index')
},
handlePreviewImage(event) {
const current = event.currentTarget.dataset.url
if (!current) {
return
}
wx.previewImage({
current,
urls: this.data.productImages
})
},
handleOpenShop() {
const shopInfo = this.data.shopInfo
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 {
const nextFavorite = !this.data.isFavorite
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'
})
} catch (error) {
wx.showToast({
title: error.message || '收藏操作失败',
icon: 'none'
})
}
},
async handleToggleLike() {
const product = this.data.product
if (!product || !product.id || !navigation.ensureLogin('点赞作品')) {
return
}
try {
const nextLiked = !this.data.isLiked
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'
})
} catch (error) {
wx.showToast({
title: error.message || '点赞操作失败',
icon: 'none'
})
}
},
async handleAddToCart() {
const product = this.data.product
if (!product || !product.id || !navigation.ensureLogin('加购')) {
return
}
try {
await runWithLoading(() => cartApi.addToCart({
productId: product.id,
quantity: 1
}))
await getApp().updateCartBadge()
wx.showToast({
title: '已加入购物车',
icon: 'none'
})
} catch (error) {
wx.showToast({
title: error.message || '加入购物车失败',
icon: 'none'
})
}
},
async handleBuyNow() {
const product = this.data.product
if (!product || !product.id || !navigation.ensureLogin('预约下单')) {
return
}
try {
await runWithLoading(() => cartApi.addToCart({
productId: product.id,
quantity: 1
}))
await getApp().updateCartBadge()
wx.switchTab({
url: '/pages/cart/index'
})
} catch (error) {
wx.showToast({
title: error.message || '操作失败',
icon: 'none'
})
}
}
})