524 lines
14 KiB
JavaScript
524 lines
14 KiB
JavaScript
const cartApi = require('../../api/cart')
|
|
const couponApi = require('../../api/coupon')
|
|
const orderApi = require('../../api/order')
|
|
const auth = require('../../utils/auth')
|
|
const navigation = require('../../utils/navigation')
|
|
const { resolveLegacyImage } = require('../../utils/file')
|
|
const { NO_COUPON_KEY } = require('../../utils/config')
|
|
const { runWithLoading } = require('../../utils/loading')
|
|
const {
|
|
buildAppointmentValue,
|
|
formatDateTime,
|
|
formatPrice,
|
|
getMinDateText,
|
|
isPastAppointment,
|
|
parseAppointmentParts
|
|
} = require('../../utils/format')
|
|
|
|
function getCouponKey(coupon) {
|
|
return `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
|
|
}
|
|
|
|
function getCouponDisplay(coupon) {
|
|
if (Number(coupon.couponType) === 1) {
|
|
return `${coupon.couponName} ${coupon.discountValue} 折`
|
|
}
|
|
return `${coupon.couponName} 满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
|
|
}
|
|
|
|
function calculateCouponDiscount(coupon, amount) {
|
|
if (!coupon || amount <= 0) {
|
|
return 0
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
function buildCheckoutIssues(items) {
|
|
const issues = []
|
|
const selectedItems = items.filter(item => item.selected)
|
|
|
|
if (!selectedItems.length) {
|
|
issues.push('请先勾选要结算的作品')
|
|
return issues
|
|
}
|
|
|
|
const missingArtist = selectedItems.find(item => !item.artistId)
|
|
if (missingArtist) {
|
|
issues.push(`请先为“${missingArtist.productTitle}”选择美甲师`)
|
|
}
|
|
|
|
const missingTime = selectedItems.find(item => !item.appointmentValue)
|
|
if (missingTime) {
|
|
issues.push(`请先为“${missingTime.productTitle}”选择预约时间`)
|
|
}
|
|
|
|
const expiredTime = selectedItems.find(item => item.appointmentValue && isPastAppointment(item.appointmentValue))
|
|
if (expiredTime) {
|
|
issues.push(`“${expiredTime.productTitle}”的预约时间已过,请重新选择`)
|
|
}
|
|
|
|
const shopIds = Array.from(new Set(selectedItems.map(item => item.shopId).filter(Boolean)))
|
|
if (shopIds.length > 1) {
|
|
issues.push('跨门店作品请分开结算')
|
|
}
|
|
|
|
const artistIds = Array.from(new Set(selectedItems.map(item => item.artistId).filter(Boolean)))
|
|
if (artistIds.length > 1) {
|
|
issues.push('不同美甲师的项目请分开结算')
|
|
}
|
|
|
|
return issues
|
|
}
|
|
|
|
Page({
|
|
data: {
|
|
isLoggedIn: false,
|
|
loading: false,
|
|
minDate: getMinDateText(),
|
|
cartItems: [],
|
|
availableCoupons: [],
|
|
selectedCouponKey: NO_COUPON_KEY,
|
|
selectedCount: 0,
|
|
totalQuantity: 0,
|
|
subtotalAmount: 0,
|
|
subtotalText: '¥0.00',
|
|
discountAmountText: '¥0.00',
|
|
totalAmountText: '¥0.00',
|
|
checkoutIssues: [],
|
|
submittingOrder: false
|
|
},
|
|
|
|
onShow() {
|
|
this.loadCartItems()
|
|
},
|
|
|
|
async onPullDownRefresh() {
|
|
await this.loadCartItems()
|
|
wx.stopPullDownRefresh()
|
|
},
|
|
|
|
getSelectedItems() {
|
|
return this.data.cartItems.filter(item => item.selected)
|
|
},
|
|
|
|
getSelectedCoupon() {
|
|
return this.data.availableCoupons.find(item => item.key === this.data.selectedCouponKey) || null
|
|
},
|
|
|
|
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 subtotalAmount = selectedItems.reduce((sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0), 0)
|
|
const discountAmount = calculateCouponDiscount(selectedCoupon, subtotalAmount)
|
|
const totalAmount = Math.max(0, subtotalAmount - discountAmount)
|
|
const checkoutIssues = buildCheckoutIssues(this.data.cartItems)
|
|
|
|
this.setData({
|
|
selectedCount,
|
|
totalQuantity,
|
|
subtotalAmount,
|
|
subtotalText: `¥${formatPrice(subtotalAmount)}`,
|
|
discountAmountText: `¥${formatPrice(discountAmount)}`,
|
|
totalAmountText: `¥${formatPrice(totalAmount)}`,
|
|
checkoutIssues
|
|
})
|
|
},
|
|
|
|
async loadCartItems() {
|
|
const isLoggedIn = auth.isLoggedIn()
|
|
this.setData({
|
|
isLoggedIn,
|
|
loading: isLoggedIn
|
|
})
|
|
|
|
if (!isLoggedIn) {
|
|
this.setData({
|
|
cartItems: [],
|
|
availableCoupons: [],
|
|
selectedCouponKey: NO_COUPON_KEY,
|
|
loading: false
|
|
})
|
|
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
|
|
})) : []
|
|
const artist = availableArtists.find(current => String(current.id) === String(item.artistId || ''))
|
|
|
|
return {
|
|
...item,
|
|
productImageUrl,
|
|
priceText: `¥${formatPrice(item.price)}`,
|
|
selected: true,
|
|
artistId: item.artistId || '',
|
|
artistName: artist ? artist.name : '',
|
|
availableArtists,
|
|
appointmentDate: appointmentParts.date,
|
|
appointmentClock: appointmentParts.clock,
|
|
appointmentValue: buildAppointmentValue(appointmentParts.date, appointmentParts.clock)
|
|
}
|
|
}))
|
|
|
|
this.setData({
|
|
cartItems: formattedItems,
|
|
selectedCouponKey: NO_COUPON_KEY
|
|
})
|
|
await this.loadAvailableCoupons()
|
|
} catch (error) {
|
|
this.setData({
|
|
cartItems: []
|
|
})
|
|
wx.showToast({
|
|
title: error.message || '购物车加载失败',
|
|
icon: 'none'
|
|
})
|
|
} finally {
|
|
this.setData({
|
|
loading: false
|
|
})
|
|
this.refreshSummary()
|
|
}
|
|
},
|
|
|
|
async loadAvailableCoupons() {
|
|
const selectedItems = this.getSelectedItems()
|
|
if (!selectedItems.length) {
|
|
this.setData({
|
|
availableCoupons: [],
|
|
selectedCouponKey: NO_COUPON_KEY
|
|
})
|
|
this.refreshSummary()
|
|
return
|
|
}
|
|
|
|
const tags = new Set()
|
|
const subtotalAmount = selectedItems.reduce((sum, item) => sum + Number(item.price || 0) * Number(item.quantity || 0), 0)
|
|
selectedItems.forEach(item => {
|
|
String(item.tagNames || '')
|
|
.split(',')
|
|
.map(tag => tag.trim())
|
|
.filter(Boolean)
|
|
.forEach(tag => tags.add(tag))
|
|
})
|
|
|
|
try {
|
|
const coupons = await couponApi.getAvailableCoupons(
|
|
Array.from(tags).join(','),
|
|
subtotalAmount,
|
|
selectedItems[0].shopId
|
|
)
|
|
|
|
const list = Array.isArray(coupons) ? coupons.map(item => ({
|
|
...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
|
|
}
|
|
|
|
if (selectedCouponKey === NO_COUPON_KEY) {
|
|
const vipCoupons = list
|
|
.filter(item => item.sourceType === 'SYSTEM_VIP')
|
|
.sort((left, right) => calculateCouponDiscount(right, subtotalAmount) - calculateCouponDiscount(left, subtotalAmount))
|
|
if (vipCoupons.length) {
|
|
selectedCouponKey = vipCoupons[0].key
|
|
}
|
|
}
|
|
|
|
this.setData({
|
|
availableCoupons: list,
|
|
selectedCouponKey
|
|
})
|
|
} catch (error) {
|
|
this.setData({
|
|
availableCoupons: [],
|
|
selectedCouponKey: NO_COUPON_KEY
|
|
})
|
|
} finally {
|
|
this.refreshSummary()
|
|
}
|
|
},
|
|
|
|
handleOpenAuth() {
|
|
navigation.openAuth('/pages/cart/index')
|
|
},
|
|
|
|
handleBrowseProducts() {
|
|
navigation.switchTab('/pages/products/index')
|
|
},
|
|
|
|
async handleToggleSelect(event) {
|
|
const index = Number(event.currentTarget.dataset.index)
|
|
const cartItems = this.data.cartItems.slice()
|
|
const item = cartItems[index]
|
|
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 (!item) {
|
|
return
|
|
}
|
|
|
|
const nextQuantity = Number(item.quantity || 0) + delta
|
|
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 (!item) {
|
|
return
|
|
}
|
|
|
|
const confirmed = await new Promise(resolve => {
|
|
wx.showModal({
|
|
title: '移除作品',
|
|
content: '确认从购物车移除这件作品吗?',
|
|
success: res => resolve(Boolean(res.confirm))
|
|
})
|
|
})
|
|
|
|
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(event) {
|
|
const productId = event.currentTarget.dataset.productId
|
|
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 (!item) {
|
|
return
|
|
}
|
|
|
|
if (!item.availableArtists.length) {
|
|
wx.showToast({
|
|
title: '当前作品暂时没有可预约美甲师',
|
|
icon: 'none'
|
|
})
|
|
return
|
|
}
|
|
|
|
const tapIndex = await new Promise(resolve => {
|
|
wx.showActionSheet({
|
|
itemList: item.availableArtists.map(artist => artist.name),
|
|
success: res => resolve(res.tapIndex),
|
|
fail: () => resolve(-1)
|
|
})
|
|
})
|
|
|
|
if (tapIndex < 0 || tapIndex >= item.availableArtists.length) {
|
|
return
|
|
}
|
|
|
|
const artist = item.availableArtists[tapIndex]
|
|
item.artistId = artist.id
|
|
item.artistName = artist.name
|
|
this.setData({
|
|
cartItems
|
|
})
|
|
this.refreshSummary()
|
|
},
|
|
|
|
handleDateChange(event) {
|
|
const index = Number(event.currentTarget.dataset.index)
|
|
const cartItems = this.data.cartItems.slice()
|
|
const item = cartItems[index]
|
|
if (!item) {
|
|
return
|
|
}
|
|
|
|
item.appointmentDate = event.detail.value
|
|
item.appointmentValue = buildAppointmentValue(item.appointmentDate, item.appointmentClock)
|
|
this.setData({
|
|
cartItems
|
|
})
|
|
this.refreshSummary()
|
|
},
|
|
|
|
handleTimeChange(event) {
|
|
const index = Number(event.currentTarget.dataset.index)
|
|
const cartItems = this.data.cartItems.slice()
|
|
const item = cartItems[index]
|
|
if (!item) {
|
|
return
|
|
}
|
|
|
|
item.appointmentClock = event.detail.value
|
|
item.appointmentValue = buildAppointmentValue(item.appointmentDate, item.appointmentClock)
|
|
this.setData({
|
|
cartItems
|
|
})
|
|
this.refreshSummary()
|
|
},
|
|
|
|
handleCouponChange(event) {
|
|
this.setData({
|
|
selectedCouponKey: event.detail.value
|
|
})
|
|
this.refreshSummary()
|
|
},
|
|
|
|
async handleCheckout() {
|
|
if (this.data.submittingOrder) {
|
|
return
|
|
}
|
|
|
|
const selectedItems = this.getSelectedItems()
|
|
const checkoutIssues = buildCheckoutIssues(this.data.cartItems)
|
|
if (checkoutIssues.length) {
|
|
wx.showToast({
|
|
title: checkoutIssues[0],
|
|
icon: 'none'
|
|
})
|
|
return
|
|
}
|
|
|
|
this.setData({
|
|
submittingOrder: true
|
|
})
|
|
|
|
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
|
|
}))
|
|
}))
|
|
|
|
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 = '订单已创建,但跳转订单页失败,请手动前往订单页查看'
|
|
}
|
|
|
|
wx.showToast({
|
|
title: successToast,
|
|
icon: 'none'
|
|
})
|
|
} catch (error) {
|
|
wx.showToast({
|
|
title: error.message || '订单创建失败',
|
|
icon: 'none'
|
|
})
|
|
} finally {
|
|
this.setData({
|
|
submittingOrder: false
|
|
})
|
|
}
|
|
}
|
|
})
|