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

826 lines
28 KiB
JavaScript
Raw Normal View History

2026-05-23 18:45:41 +08:00
/**
* 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.
*/
2026-04-01 15:18:35 +08:00
const cartApi = require('../../api/cart')
2026-05-23 18:45:41 +08:00
/**
* Purpose: orderApi supports index.js by holding or executing the order 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.
*/
2026-04-01 15:18:35 +08:00
const orderApi = require('../../api/order')
2026-05-23 18:45:41 +08:00
/**
* 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.
*/
2026-04-01 15:18:35 +08:00
const auth = require('../../utils/auth')
2026-05-23 18:45:41 +08:00
/**
* 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.
*/
2026-04-01 15:18:35 +08:00
const navigation = require('../../utils/navigation')
2026-05-23 18:45:41 +08:00
/**
* 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')
2026-04-01 15:18:35 +08:00
const { resolveLegacyImage } = require('../../utils/file')
const { NO_COUPON_KEY } = require('../../utils/config')
const { runWithLoading } = require('../../utils/loading')
const { clearBuyNowContext, isBuyNowCartItem, readBuyNowContext } = require('../../utils/buy-now')
const { buildRecoveryState, clearRecoveryState } = require('../../utils/recovery')
2026-04-01 15:18:35 +08:00
const {
buildAppointmentValue,
formatDateTime,
formatPrice,
getMinDateText,
isPastAppointment,
parseAppointmentParts
} = require('../../utils/format')
2026-05-23 18:45:41 +08:00
/**
* Purpose: getCouponKey supports index.js by holding or executing the get coupon key page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
2026-04-01 15:18:35 +08:00
function getCouponKey(coupon) {
return `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: getCouponDisplay supports index.js by holding or executing the get coupon display page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
2026-04-01 15:18:35 +08:00
function getCouponDisplay(coupon) {
if (coupon && coupon.displayText) {
return coupon.displayText
}
2026-04-01 15:18:35 +08:00
if (Number(coupon.couponType) === 1) {
return `${coupon.couponName} ${coupon.discountValue} 折`
}
return `${coupon.couponName} 满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: calculateCouponDiscount supports index.js by holding or executing the calculate coupon discount page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
2026-04-01 15:18:35 +08:00
function calculateCouponDiscount(coupon, amount) {
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!coupon || amount <= 0) {
return 0
}
if (coupon.discountAmount !== undefined && coupon.discountAmount !== null) {
return Number(coupon.discountAmount || 0)
}
2026-04-01 15:18:35 +08:00
if (Number(coupon.couponType) === 1) {
const discountValue = Number(coupon.discountValue || 0)
return discountValue ? amount - amount * discountValue / 10 : 0
}
if (Number(coupon.couponType) === 2) {
return Number(coupon.reduceAmount || 0)
}
return 0
}
2026-05-23 18:45:41 +08:00
/**
* Purpose: buildCheckoutIssues supports index.js by holding or executing the build checkout issues page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
2026-04-01 15:18:35 +08:00
function buildCheckoutIssues(items) {
const issues = []
const selectedItems = items.filter(item => item.selected)
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!selectedItems.length) {
issues.push('请先勾选要结算的作品')
return issues
}
const missingArtist = selectedItems.find(item => !item.artistId)
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (missingArtist) {
issues.push(`请先为“${missingArtist.productTitle}”选择美甲师`)
}
const missingTime = selectedItems.find(item => !item.appointmentValue)
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (missingTime) {
issues.push(`请先为“${missingTime.productTitle}”选择预约时间`)
}
const expiredTime = selectedItems.find(item => item.appointmentValue && isPastAppointment(item.appointmentValue))
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (expiredTime) {
issues.push(`“${expiredTime.productTitle}”的预约时间已过,请重新选择`)
}
const shopIds = Array.from(new Set(selectedItems.map(item => item.shopId).filter(Boolean)))
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (shopIds.length > 1) {
issues.push('跨门店作品请分开结算')
}
const artistIds = Array.from(new Set(selectedItems.map(item => item.artistId).filter(Boolean)))
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (artistIds.length > 1) {
issues.push('不同美甲师的项目请分开结算')
}
return issues
}
/**
* cart page logic.
* Call guide: page data drives the WXML template, and each method is called by user events or lifecycle callbacks.
*/
2026-04-01 15:18:35 +08:00
Page({
data: Object.assign(theme.pageThemeData(getApp().globalData.shopTheme), {
2026-04-01 15:18:35 +08:00
isLoggedIn: false,
loading: false,
minDate: getMinDateText(),
cartItems: [],
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
2026-04-01 15:18:35 +08:00
selectedCouponKey: NO_COUPON_KEY,
2026-05-23 18:45:41 +08:00
/**
* Purpose: couponSelectionTouched records whether the user explicitly chose a coupon option.
* Usage: keep normal user coupons manual-only while still allowing VIP auto coupons as default.
*/
couponSelectionTouched: false,
2026-04-01 15:18:35 +08:00
selectedCount: 0,
isBuyNowMode: false,
heroKicker: '结算准备',
heroTitle: '已选 0 个预约项目',
heroDesc: '确认美甲师和时间后再下单。',
2026-04-01 15:18:35 +08:00
totalQuantity: 0,
subtotalAmount: 0,
subtotalText: '¥0.00',
discountAmountText: '¥0.00',
totalAmountText: '¥0.00',
2026-04-03 11:44:32 +08:00
checkoutIssues: [],
submittingOrder: false,
recoveryState: clearRecoveryState()
}),
2026-04-01 15:18:35 +08:00
/**
* `onShow` 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.
*/
2026-04-01 15:18:35 +08:00
onShow() {
this.loadCartItems()
},
async onPullDownRefresh() {
await this.loadCartItems()
wx.stopPullDownRefresh()
},
/**
* `getSelectedItems` 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.
*/
2026-04-01 15:18:35 +08:00
getSelectedItems() {
return this.data.cartItems.filter(item => item.selected)
},
/**
* `getSelectedCoupon` 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.
*/
2026-04-01 15:18:35 +08:00
getSelectedCoupon() {
return this.data.availableCoupons.find(item => item.key === this.data.selectedCouponKey) || null
},
/**
* `refreshSummary` 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.
*/
2026-04-01 15:18:35 +08:00
refreshSummary() {
const selectedItems = this.getSelectedItems()
const selectedCoupon = this.getSelectedCoupon()
const selectedCount = selectedItems.length
const totalQuantity = selectedItems.reduce((sum, item) => sum + Number(item.quantity || 0), 0)
const localSubtotalAmount = selectedItems.reduce((sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0), 0)
const preview = this.data.checkoutPreview || {}
const subtotalAmount = preview.subtotalAmount !== undefined ? Number(preview.subtotalAmount || 0) : localSubtotalAmount
const discountAmount = preview.savedAmount !== undefined ? Number(preview.savedAmount || 0) : calculateCouponDiscount(selectedCoupon, subtotalAmount)
const totalAmount = preview.payableAmount !== undefined ? Number(preview.payableAmount || 0) : Math.max(0, subtotalAmount - discountAmount)
2026-04-01 15:18:35 +08:00
const checkoutIssues = buildCheckoutIssues(this.data.cartItems)
const isBuyNowMode = Boolean(this.data.isBuyNowMode)
2026-04-01 15:18:35 +08:00
this.setData({
selectedCount,
heroKicker: isBuyNowMode ? '确认订单' : '结算准备',
heroTitle: isBuyNowMode ? '确认本次预约' : `已选 ${selectedCount} 个预约项目`,
heroDesc: isBuyNowMode ? '本次只会提交刚刚选择的作品,不会混入购物车其他项目。' : '确认美甲师和时间后再下单。',
2026-04-01 15:18:35 +08:00
totalQuantity,
subtotalAmount,
subtotalText: `¥${formatPrice(subtotalAmount)}`,
discountAmountText: `¥${formatPrice(discountAmount)}`,
totalAmountText: `¥${formatPrice(totalAmount)}`,
checkoutIssues
})
},
async loadCartItems() {
const isLoggedIn = auth.isLoggedIn()
const buyNowContext = isLoggedIn ? readBuyNowContext() : null
const buyNowProductId = buyNowContext && buyNowContext.productId ? String(buyNowContext.productId) : ''
2026-04-01 15:18:35 +08:00
this.setData({
isLoggedIn,
isBuyNowMode: Boolean(buyNowProductId),
loading: isLoggedIn,
recoveryState: clearRecoveryState()
2026-04-01 15:18:35 +08:00
})
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!isLoggedIn) {
this.setData({
cartItems: [],
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
2026-04-01 15:18:35 +08:00
selectedCouponKey: NO_COUPON_KEY,
2026-05-23 18:45:41 +08:00
couponSelectionTouched: false,
loading: false,
recoveryState: clearRecoveryState()
2026-04-01 15:18:35 +08:00
})
this.refreshSummary()
return
}
try {
const cartItems = await cartApi.getCartList()
const list = Array.isArray(cartItems) ? cartItems : []
const formattedItems = await Promise.all(list.map(async item => {
const appointmentParts = parseAppointmentParts(item.appointmentTime)
const productImageUrl = await resolveLegacyImage(item.productImage)
const availableArtists = Array.isArray(item.availableArtists) ? item.availableArtists.map(artist => ({
id: artist.id,
name: artist.name,
avatar: artist.avatar,
userType: artist.userType,
roleLabel: artist.roleLabel,
participateProduction: artist.participateProduction
2026-04-01 15:18:35 +08:00
})) : []
const artist = availableArtists.find(current => String(current.id) === String(item.artistId || ''))
return {
...item,
productImageUrl,
priceText: `¥${formatPrice(item.price)}`,
selected: buyNowProductId ? isBuyNowCartItem(item, buyNowProductId) : true,
2026-04-01 15:18:35 +08:00
artistId: item.artistId || '',
artistName: artist ? artist.name : '',
availableArtists,
appointmentDate: appointmentParts.date,
appointmentClock: appointmentParts.clock,
appointmentValue: buildAppointmentValue(appointmentParts.date, appointmentParts.clock)
}
}))
this.setData({
cartItems: formattedItems,
2026-05-23 18:45:41 +08:00
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false,
recoveryState: clearRecoveryState()
2026-04-01 15:18:35 +08:00
})
if (buyNowProductId) {
clearBuyNowContext()
}
2026-04-01 15:18:35 +08:00
await this.loadAvailableCoupons()
} catch (error) {
this.setData({
cartItems: [],
recoveryState: buildRecoveryState({
title: '购物车加载失败',
message: error,
fallbackMessage: '购物车暂时没有加载出来,请重试或先去逛作品。',
actions: [
{ key: 'retryCartLoad', text: '重试' },
{ key: 'products', text: '去逛作品' },
{ key: 'contact', text: '联系客服' }
]
})
2026-04-01 15:18:35 +08:00
})
} finally {
this.setData({
loading: false
})
this.refreshSummary()
}
},
async loadAvailableCoupons() {
const selectedItems = this.getSelectedItems()
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!selectedItems.length) {
this.setData({
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
2026-05-23 18:45:41 +08:00
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false
2026-04-01 15:18:35 +08:00
})
this.refreshSummary()
return
}
try {
const selectedCoupon = this.getSelectedCoupon()
const preview = await orderApi.checkoutPreview({
couponId: selectedCoupon ? selectedCoupon.id : undefined,
couponSourceType: selectedCoupon ? selectedCoupon.sourceType : (this.data.couponSelectionTouched && this.data.selectedCouponKey === NO_COUPON_KEY ? NO_COUPON_KEY : undefined),
items: selectedItems.map(item => ({
productId: item.productId,
quantity: item.quantity,
artistId: item.artistId,
appointmentTime: item.appointmentValue
}))
})
2026-04-01 15:18:35 +08:00
const list = Array.isArray(preview && preview.availableCoupons) ? preview.availableCoupons.map(item => ({
...item,
key: getCouponKey(item),
displayText: getCouponDisplay(item)
})) : []
const unavailableCoupons = Array.isArray(preview && preview.unavailableCoupons) ? preview.unavailableCoupons.map(item => ({
2026-04-01 15:18:35 +08:00
...item,
key: getCouponKey(item),
displayText: getCouponDisplay(item)
})) : []
let selectedCouponKey = this.data.selectedCouponKey
if (selectedCouponKey !== NO_COUPON_KEY && !list.find(item => item.key === selectedCouponKey)) {
selectedCouponKey = NO_COUPON_KEY
}
const previewSubtotalAmount = Number((preview && preview.subtotalAmount) || this.data.subtotalAmount || 0)
2026-04-01 15:18:35 +08:00
/**
* `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.
*/
2026-05-23 18:45:41 +08:00
if (selectedCouponKey === NO_COUPON_KEY && !this.data.couponSelectionTouched) {
const bestCoupons = list
.sort((left, right) => calculateCouponDiscount(right, previewSubtotalAmount) - calculateCouponDiscount(left, previewSubtotalAmount))
/**
* `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 (bestCoupons.length) {
selectedCouponKey = bestCoupons[0].key
2026-04-01 15:18:35 +08:00
}
}
this.setData({
availableCoupons: list,
unavailableCoupons,
checkoutPreview: preview || null,
vipTip: preview && preview.vipTip ? preview.vipTip : '',
2026-04-01 15:18:35 +08:00
selectedCouponKey
})
} catch (error) {
this.setData({
availableCoupons: [],
unavailableCoupons: [],
checkoutPreview: null,
vipTip: '',
2026-05-23 18:45:41 +08:00
selectedCouponKey: NO_COUPON_KEY,
couponSelectionTouched: false
2026-04-01 15:18:35 +08:00
})
} finally {
this.refreshSummary()
}
},
/**
* `handleOpenAuth` 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.
*/
2026-04-01 15:18:35 +08:00
handleOpenAuth() {
navigation.openAuth('/pages/cart/index')
},
/**
* `handleBrowseProducts` 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.
*/
2026-04-01 15:18:35 +08:00
handleBrowseProducts() {
navigation.switchTab('/pages/products/index')
},
handleRecoveryAction(event) {
const key = event.currentTarget.dataset.key
if (key === 'retryCartLoad') {
this.setData({ recoveryState: clearRecoveryState() })
this.loadCartItems()
return
}
if (key === 'retryCheckout') {
this.setData({ recoveryState: clearRecoveryState() })
this.handleCheckout()
return
}
if (key === 'contact') {
this.handleContactSupport()
return
}
if (key === 'cart') {
this.setData({ recoveryState: clearRecoveryState() })
return
}
const actions = this.data.recoveryState.actions || []
const action = actions.find(item => item.key === key)
if (action && action.route) {
this.openRecoveryRoute(action.route)
}
},
openRecoveryRoute(route) {
const pureRoute = String(route || '').split('?')[0]
if (!pureRoute) {
return
}
if (navigation.isTabPage(pureRoute)) {
navigation.switchTab(pureRoute)
return
}
navigation.navigate(route)
},
handleContactSupport() {
wx.showModal({
title: '联系客服',
content: '请截图保留失败提示;如果担心重复下单,请先查看订单。也可以前往“我的”页联系门店或平台客服。',
confirmText: '去我的',
cancelText: '留在本页',
success: res => {
if (res.confirm) {
navigation.switchTab('/pages/profile/index')
}
}
})
},
2026-04-01 15:18:35 +08:00
async handleToggleSelect(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!item) {
return
}
item.selected = !item.selected
this.setData({
cartItems
})
if (cartItems.some(current => current.selected)) {
await runWithLoading(() => this.loadAvailableCoupons())
return
}
await this.loadAvailableCoupons()
},
async handleChangeQuantity(event) {
const index = Number(event.currentTarget.dataset.index)
const delta = Number(event.currentTarget.dataset.delta)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!item) {
return
}
const nextQuantity = Number(item.quantity || 0) + delta
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (nextQuantity < 1 || nextQuantity > 99) {
return
}
item.quantity = nextQuantity
this.setData({
cartItems
})
this.refreshSummary()
try {
await runWithLoading(async () => {
await cartApi.updateCartQuantity({
productId: item.productId,
quantity: nextQuantity
})
await this.loadAvailableCoupons()
})
await getApp().updateCartBadge()
} catch (error) {
item.quantity -= delta
this.setData({
cartItems
})
this.refreshSummary()
wx.showToast({
title: error.message || '数量更新失败',
icon: 'none'
})
}
},
async handleRemoveItem(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!item) {
return
}
const confirmed = await new Promise(resolve => {
wx.showModal({
title: '移除作品',
content: '确认从购物车移除这件作品吗?',
success: res => resolve(Boolean(res.confirm))
})
})
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!confirmed) {
return
}
try {
await runWithLoading(() => cartApi.removeFromCart(item.productId))
wx.showToast({
title: '已移出购物车',
icon: 'none'
})
await getApp().updateCartBadge()
this.loadCartItems()
} catch (error) {
wx.showToast({
title: error.message || '移除失败',
icon: 'none'
})
}
},
/**
* `handleOpenProduct` 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.
*/
2026-04-01 15:18:35 +08:00
handleOpenProduct(event) {
const productId = event.currentTarget.dataset.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.
*/
2026-04-01 15:18:35 +08:00
if (!productId) {
return
}
navigation.navigate('/pages/product-detail/index', {
id: productId
})
},
async handleChooseArtist(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!item) {
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.
*/
2026-04-01 15:18:35 +08:00
if (!item.availableArtists.length) {
wx.showToast({
title: '当前作品暂时没有可预约美甲师',
icon: 'none'
})
return
}
const tapIndex = await new Promise(resolve => {
wx.showActionSheet({
itemList: item.availableArtists.map(artist => artist.roleLabel ? `${artist.name}(${artist.roleLabel})` : artist.name),
2026-04-01 15:18:35 +08:00
success: res => resolve(res.tapIndex),
fail: () => resolve(-1)
})
})
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (tapIndex < 0 || tapIndex >= item.availableArtists.length) {
return
}
const artist = item.availableArtists[tapIndex]
item.artistId = artist.id
item.artistName = artist.roleLabel ? `${artist.name}(${artist.roleLabel})` : artist.name
2026-04-01 15:18:35 +08:00
this.setData({
cartItems
})
this.refreshSummary()
},
/**
* `handleDateChange` 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.
*/
2026-04-01 15:18:35 +08:00
handleDateChange(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!item) {
return
}
item.appointmentDate = event.detail.value
item.appointmentValue = buildAppointmentValue(item.appointmentDate, item.appointmentClock)
this.setData({
cartItems
})
this.refreshSummary()
},
/**
* `handleTimeChange` 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.
*/
2026-04-01 15:18:35 +08:00
handleTimeChange(event) {
const index = Number(event.currentTarget.dataset.index)
const cartItems = this.data.cartItems.slice()
const item = cartItems[index]
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (!item) {
return
}
item.appointmentClock = event.detail.value
item.appointmentValue = buildAppointmentValue(item.appointmentDate, item.appointmentClock)
this.setData({
cartItems
})
this.refreshSummary()
},
/**
* `handleCouponChange` 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.
*/
2026-04-01 15:18:35 +08:00
handleCouponChange(event) {
this.setData({
2026-05-23 18:45:41 +08:00
selectedCouponKey: event.detail.value,
couponSelectionTouched: true
2026-04-01 15:18:35 +08:00
})
this.loadAvailableCoupons()
2026-04-01 15:18:35 +08:00
},
async handleCheckout() {
/**
* `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.
*/
2026-04-03 11:44:32 +08:00
if (this.data.submittingOrder) {
return
}
2026-04-01 15:18:35 +08:00
const selectedItems = this.getSelectedItems()
const checkoutIssues = buildCheckoutIssues(this.data.cartItems)
/**
* `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.
*/
2026-04-01 15:18:35 +08:00
if (checkoutIssues.length) {
wx.showToast({
title: checkoutIssues[0],
icon: 'none'
})
return
}
2026-04-03 11:44:32 +08:00
this.setData({
submittingOrder: true
})
2026-04-01 15:18:35 +08:00
try {
const selectedCoupon = this.getSelectedCoupon()
await runWithLoading(() => orderApi.createOrder({
couponId: selectedCoupon ? selectedCoupon.id : undefined,
couponSourceType: selectedCoupon ? selectedCoupon.sourceType : (this.data.selectedCouponKey === NO_COUPON_KEY ? NO_COUPON_KEY : undefined),
items: selectedItems.map(item => ({
productId: item.productId,
quantity: item.quantity,
artistId: item.artistId,
appointmentTime: item.appointmentValue
}))
}))
2026-04-03 11:44:32 +08:00
let successToast = '订单创建成功'
try {
await getApp().updateCartBadge()
await this.loadCartItems()
} catch (followupError) {
console.error('订单创建后刷新页面失败:', followupError)
successToast = '订单已创建,但页面刷新失败,请前往订单页查看'
}
try {
await navigation.navigate('/pages/orders/index')
} catch (navigationError) {
console.error('订单创建后跳转订单页失败:', navigationError)
successToast = '订单已创建,但跳转订单页失败,请手动前往订单页查看'
}
2026-04-01 15:18:35 +08:00
wx.showToast({
2026-04-03 11:44:32 +08:00
title: successToast,
2026-04-01 15:18:35 +08:00
icon: 'none'
})
} catch (error) {
this.setData({
recoveryState: buildRecoveryState({
title: '下单失败',
message: error,
fallbackMessage: '订单创建失败,请重试;如果担心重复下单,请先查看订单。',
actions: [
{ key: 'retryCheckout', text: '重试下单' },
{ key: 'orders', text: '查看订单' },
{ key: 'contact', text: '联系客服' },
{ key: 'cart', text: '返回购物车' }
]
})
2026-04-01 15:18:35 +08:00
})
2026-04-03 11:44:32 +08:00
} finally {
this.setData({
submittingOrder: false
})
2026-04-01 15:18:35 +08:00
}
}
})