Files
JayuCloud/Frontend/src/views/CartView.vue
T

880 lines
26 KiB
Vue
Raw Normal View History

<template>
2026-03-19 20:19:41 +08:00
<div class="page">
<header class="header">
2026-03-19 20:19:41 +08:00
<a-button type="text" @click="router.back()">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>购物车</h1>
<a-button type="text" @click="editing = !editing">
{{ editing ? '完成' : '批量删除' }}
</a-button>
</header>
2026-03-19 20:19:41 +08:00
<main class="content">
<a-empty v-if="!cartItems.length" description="购物车还是空的">
<a-button type="primary" @click="router.push('/products')">去逛作品</a-button>
</a-empty>
<a-alert
v-if="selectedCount && checkoutIssues.length && !editing"
class="issue-alert"
type="warning"
show-icon
:message="`还有 ${checkoutIssues.length} 项待完善`"
:description="checkoutIssues.map(issue => issue.message).join(';')"
>
<template #action>
<a-button size="small" @click="focusFirstIssue">定位问题</a-button>
</template>
</a-alert>
<a-card
v-for="item in cartItems"
:key="item.id"
:ref="element => setItemRef(item.id, element)"
class="item-card"
:class="{ 'issue-card': item.selected && hasItemIssue(item) }"
>
2026-03-19 20:19:41 +08:00
<div class="item-row">
<a-checkbox v-model:checked="item.selected" @change="loadAvailableCoupons" />
<div class="thumb" @click="openProduct(item)">
<img v-if="item.productImage" :src="item.productImage" :alt="item.productTitle" />
<span v-else>{{ item.productTitle[0] }}</span>
</div>
2026-03-19 20:19:41 +08:00
<div class="item-main">
<div class="title" @click="openProduct(item)">{{ item.productTitle }}</div>
<div class="price">¥{{ Number(item.price || 0).toFixed(2) }}</div>
2026-03-19 20:19:41 +08:00
<div class="selector" :class="{ issue: item.selected && !item.artistId }" @click="openBookingModal(item)">
2026-03-19 20:19:41 +08:00
<span class="label">美甲师</span>
<span class="value">{{ item.artist?.name || '请选择美甲师' }}</span>
<RightOutlined />
2026-03-19 14:10:59 +08:00
</div>
2026-03-19 20:19:41 +08:00
<div
class="selector"
:class="{ issue: item.selected && (!item.appointmentTime || isPastAppointment(item.appointmentTime)) }"
@click="openBookingModal(item)"
>
2026-03-19 20:19:41 +08:00
<span class="label">预约时间</span>
<span class="value">
{{ item.appointmentTime ? formatAppointmentDisplay(item.appointmentTime) : (item.artistId ? '请选择预约时间' : '先选择美甲师') }}
</span>
<RightOutlined />
</div>
<div v-if="item.approximateDuration" class="duration">预计时长:{{ item.approximateDuration }}</div>
<div class="actions">
<div class="qty">
<a-button size="small" :disabled="item.quantity <= 1" @click="changeQuantity(item, -1)">-</a-button>
<span>{{ item.quantity }}</span>
<a-button size="small" :disabled="item.quantity >= 99" @click="changeQuantity(item, 1)">+</a-button>
2026-02-25 10:37:16 +08:00
</div>
<a-popconfirm title="确认删除这件作品吗?" ok-text="确认" cancel-text="取消" @confirm="removeItem(item)">
<a-button type="text" danger size="small">
<DeleteOutlined />
</a-button>
</a-popconfirm>
</div>
</div>
</div>
</a-card>
<a-card v-if="selectedCount && !editing" class="coupon-card" @click="openCouponModal">
2026-03-19 20:19:41 +08:00
<div class="coupon-row">
<span>优惠方式</span>
<span>{{ selectedCoupon ? formatCouponDisplay(selectedCoupon) : '不使用优惠' }}</span>
</div>
<div v-if="selectedCoupon" class="coupon-extra">
<span>{{ selectedCoupon.sourceType === 'SYSTEM_VIP' ? '当前为 VIP 自动折扣,不会消耗用户券。' : '当前为用户券,只有下单成功才会消耗。' }}</span>
<strong>-¥{{ discountAmount.toFixed(2) }}</strong>
</div>
</a-card>
<a-card v-if="cartItems.length && !editing" class="summary-card">
<div class="summary-row"><span>选中项目</span><span>{{ selectedCount }} 项</span></div>
2026-03-19 20:19:41 +08:00
<div class="summary-row"><span>作品数量</span><span>{{ totalQuantity }} 件</span></div>
<div class="summary-row"><span>小计</span><span>¥{{ subtotal.toFixed(2) }}</span></div>
<div v-if="selectedCoupon" class="summary-row"><span>优惠</span><span>-¥{{ discountAmount.toFixed(2) }}</span></div>
<div class="summary-row total"><span>合计</span><span>¥{{ totalAmount.toFixed(2) }}</span></div>
2026-03-19 20:19:41 +08:00
</a-card>
</main>
2026-03-19 20:19:41 +08:00
<footer v-if="cartItems.length" class="footer">
<a-button
v-if="editing"
danger
size="large"
block
@click="removeSelectedItems"
>
删除已选中的 {{ selectedCount }} 项
</a-button>
<a-button
v-else
type="primary"
size="large"
block
@click="checkout"
>
结算 {{ selectedCount }} 项,预计金额 ¥{{ totalAmount.toFixed(2) }}
</a-button>
2026-03-19 20:19:41 +08:00
</footer>
<a-modal v-model:open="showCouponModal" title="选择优惠方式" @ok="applyCouponSelection" @cancel="showCouponModal = false">
<a-radio-group v-model:value="couponSelectionKey" class="coupon-options">
<a-radio :value="NO_COUPON_KEY">不使用优惠</a-radio>
<a-radio v-for="coupon in availableCoupons" :key="getCouponKey(coupon)" :value="getCouponKey(coupon)">
{{ formatCouponDisplay(coupon) }}
2026-03-19 20:19:41 +08:00
</a-radio>
</a-radio-group>
<div class="coupon-tip">
系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
</div>
</a-modal>
2026-02-28 14:32:28 +08:00
2026-03-19 20:19:41 +08:00
<a-modal v-model:open="showBookingModal" :title="bookingTitle" @ok="confirmBooking" @cancel="closeBookingModal">
<div class="modal-section">
<div class="section-title">美甲师</div>
<div v-if="availableArtists.length" class="artist-list">
<button
v-for="artist in availableArtists"
:key="artist.id"
type="button"
class="artist-option"
2026-03-27 14:55:41 +08:00
:class="{ active: sameId(draftArtistId, artist.id) }"
2026-03-19 20:19:41 +08:00
@click="draftArtistId = artist.id"
>
<img v-if="artist.avatar" :src="artist.avatar" :alt="artist.name" />
<span>{{ artist.name }}</span>
</button>
2026-02-28 14:32:28 +08:00
</div>
<a-empty v-else description="暂无可预约美甲师" />
2026-03-19 20:19:41 +08:00
</div>
<div class="modal-section">
<div class="section-title">预约时间</div>
2026-03-21 13:16:39 +08:00
<a-date-picker
v-model:value="draftAppointmentTime"
class="time-picker"
style="width: 100%"
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
input-read-only
:disabled-date="disablePastAppointmentDate"
:disabled-time="disablePastAppointmentTime"
:show-time="{ minuteStep: 30, secondStep: 60, hideDisabledOptions: true }"
placeholder="请选择预约时间"
/>
2026-03-19 20:19:41 +08:00
<div class="helper">{{ bookingHelperText }}</div>
2026-02-28 14:32:28 +08:00
</div>
</a-modal>
</div>
</template>
<script setup lang="ts">
2026-03-19 20:19:41 +08:00
import { computed, inject, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
2026-03-19 20:19:41 +08:00
import { DeleteOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
2026-03-19 20:19:41 +08:00
import { cartApi } from '../api/cart'
import { couponApi, type UserCoupon } from '../api/coupon'
import { fileApi } from '../api/index'
import { orderApi } from '../api/order'
import { shopApi } from '../api/shop'
2026-03-27 14:55:41 +08:00
import type { IdType } from '@/utils/id'
import { sameId, toOptionalIdString } from '@/utils/id'
2026-02-28 17:09:45 +08:00
2026-03-19 20:19:41 +08:00
const router = useRouter()
2026-02-28 17:09:45 +08:00
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
const NO_COUPON_KEY = 'NONE'
2026-03-19 20:19:41 +08:00
interface ArtistOption {
2026-03-27 14:55:41 +08:00
id: IdType
2026-03-19 20:19:41 +08:00
name: string
avatar?: string
}
interface CartItem {
2026-03-27 14:55:41 +08:00
id: IdType
productId: IdType
shopId?: IdType
productTitle: string
productImage: string
2026-03-04 11:17:38 +08:00
originalProductImage?: string
price: number
quantity: number
totalPrice: number
2026-02-28 15:45:16 +08:00
tags: string
2026-03-19 20:19:41 +08:00
tagNames?: string
approximateDuration?: string
bookableArtists?: string
availableBookableArtistCount?: number
bookableArtistRestricted?: boolean
availableArtists?: ArtistOption[]
2026-03-19 20:19:41 +08:00
appointmentTime?: string
selected: boolean
2026-03-27 14:55:41 +08:00
artistId?: IdType
2026-03-19 20:19:41 +08:00
artist?: ArtistOption
}
interface CheckoutIssue {
key: string
message: string
2026-03-27 14:55:41 +08:00
itemId?: IdType
}
const cartItems = ref<CartItem[]>([])
const imageIdCache = ref<Record<string, string>>({})
2026-03-27 14:55:41 +08:00
const itemRefs = ref<Record<string, HTMLElement>>({})
const availableCoupons = ref<UserCoupon[]>([])
const selectedCoupon = ref<UserCoupon | null>(null)
const couponSelectionKey = ref(NO_COUPON_KEY)
const couponSelectionTouched = ref(false)
const showCouponModal = ref(false)
2026-03-19 20:19:41 +08:00
const showBookingModal = ref(false)
const currentItem = ref<CartItem | null>(null)
const availableArtists = ref<ArtistOption[]>([])
2026-03-27 14:55:41 +08:00
const draftArtistId = ref<IdType>()
2026-03-19 20:19:41 +08:00
const draftAppointmentTime = ref('')
const currentShopHours = ref('')
const editing = ref(false)
const selectedItems = computed(() => cartItems.value.filter(item => item.selected))
const selectedCount = computed(() => selectedItems.value.length)
const totalQuantity = computed(() => selectedItems.value.reduce((sum, item) => sum + item.quantity, 0))
const subtotal = computed(() => selectedItems.value.reduce((sum, item) => sum + Number(item.price || 0) * item.quantity, 0))
const discountAmount = computed(() => calculateCouponDiscount(selectedCoupon.value, subtotal.value))
2026-03-19 20:19:41 +08:00
const totalAmount = computed(() => Math.max(0, subtotal.value - discountAmount.value))
const bookingTitle = computed(() => currentItem.value ? `为 ${currentItem.value.productTitle} 选择预约信息` : '选择预约信息')
2026-03-19 20:19:41 +08:00
const bookingHelperText = computed(() => {
const texts: string[] = []
if (currentShopHours.value) texts.push(`门店营业时间:${currentShopHours.value}`)
if (currentItem.value?.approximateDuration) texts.push(`预计时长:${currentItem.value.approximateDuration}`)
2026-03-21 13:16:39 +08:00
return texts.join(' · ') || '请选择至少晚于当前 5 分钟的预约时间'
})
2026-03-21 13:16:39 +08:00
const getMinAppointmentDate = () => {
const date = new Date()
date.setSeconds(0, 0)
date.setMinutes(date.getMinutes() + 5)
return date
}
const getDayBoundary = (date: Date) => {
const boundary = new Date(date)
boundary.setHours(0, 0, 0, 0)
return boundary.getTime()
}
const getCouponKey = (coupon: UserCoupon) => `${coupon.sourceType || 'USER_COUPON'}:${coupon.id}`
2026-03-27 14:55:41 +08:00
const setItemRef = (itemId: IdType, element: unknown) => {
const refKey = toOptionalIdString(itemId)
if (!refKey) {
return
}
if (element && (element as any).$el) {
2026-03-27 14:55:41 +08:00
itemRefs.value[refKey] = (element as any).$el as HTMLElement
return
}
if (element instanceof HTMLElement) {
2026-03-27 14:55:41 +08:00
itemRefs.value[refKey] = element
return
}
2026-03-27 14:55:41 +08:00
delete itemRefs.value[refKey]
}
const formatCouponDisplay = (coupon: UserCoupon) => {
const badge = coupon.sourceType === 'SYSTEM_VIP' ? '[VIP 自动券]' : '[用户券]'
const benefit = coupon.couponType === 1
? `${coupon.discountValue} 折`
: `满 ${coupon.minAmount} 减 ${coupon.reduceAmount}`
return `${badge} ${coupon.couponName} ${benefit}`
}
const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
if (!coupon || amount <= 0) {
return 0
}
if (coupon.couponType === 1) {
const discountValue = Number(coupon.discountValue || 0)
return discountValue ? amount - amount * discountValue / 10 : 0
}
if (coupon.couponType === 2) {
return Number(coupon.reduceAmount || 0)
}
return 0
}
const findBestSystemVipCoupon = (coupons: UserCoupon[]) => {
return coupons
.filter(coupon => coupon.sourceType === 'SYSTEM_VIP')
.sort((left, right) => calculateCouponDiscount(right, subtotal.value) - calculateCouponDiscount(left, subtotal.value))[0] || null
}
const formatAppointmentDisplay = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '未选择预约时间'
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() < getMinAppointmentDate().getTime()
const hasItemIssue = (item: CartItem) => !item.artistId || !item.appointmentTime || isPastAppointment(item.appointmentTime)
2026-03-27 15:04:58 +08:00
// 购物车结算口径要求单店铺、单美甲师、完整预约信息,避免后端拆单和排班出现歧义。
const checkoutIssues = computed<CheckoutIssue[]>(() => {
const items = selectedItems.value
const issues: CheckoutIssue[] = []
const firstMissingArtist = items.find(item => !item.artistId)
if (firstMissingArtist) {
issues.push({ key: 'artist', message: `请先为“${firstMissingArtist.productTitle}”选择美甲师`, itemId: firstMissingArtist.id })
}
const firstMissingTime = items.find(item => !item.appointmentTime)
if (firstMissingTime) {
issues.push({ key: 'time', message: `请先为“${firstMissingTime.productTitle}”选择预约时间`, itemId: firstMissingTime.id })
}
const firstExpiredTime = items.find(item => isPastAppointment(item.appointmentTime))
if (firstExpiredTime) {
issues.push({ key: 'expired', message: `“${firstExpiredTime.productTitle}”的预约时间已过期,请重新选择`, itemId: firstExpiredTime.id })
}
2026-03-27 14:55:41 +08:00
const selectedShopIds = new Set(
items
.map(item => toOptionalIdString(item.shopId))
.filter((shopId): shopId is string => Boolean(shopId))
)
if (selectedShopIds.size > 1) {
issues.push({ key: 'shop', message: '跨店铺项目请分开结算', itemId: items[0]?.id })
}
2026-03-27 14:55:41 +08:00
const selectedArtistIds = new Set(
items
.map(item => toOptionalIdString(item.artistId))
.filter((artistId): artistId is string => Boolean(artistId))
)
if (selectedArtistIds.size > 1) {
issues.push({ key: 'artist-mix', message: '不同美甲师的项目请分开结算', itemId: items[0]?.id })
}
return issues
})
const scrollToIssue = (issue?: CheckoutIssue) => {
2026-03-27 14:55:41 +08:00
const itemId = toOptionalIdString(issue?.itemId)
if (!itemId) {
return
}
2026-03-27 14:55:41 +08:00
const target = itemRefs.value[itemId]
if (target) {
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
}
}
const focusFirstIssue = () => {
scrollToIssue(checkoutIssues.value[0])
}
2026-03-19 20:19:41 +08:00
const loadCartItems = async () => {
const response = await cartApi.getCartList() as unknown as any[]
cartItems.value = (response || []).map(item => ({
2026-03-19 20:19:41 +08:00
...item,
selected: true,
originalProductImage: item.productImage,
productImage: '',
appointmentTime: item.appointmentTime
}))
couponSelectionTouched.value = false
couponSelectionKey.value = NO_COUPON_KEY
selectedCoupon.value = null
editing.value = false
2026-03-19 20:19:41 +08:00
await Promise.all([loadProductImages(), loadAvailableCoupons()])
}
2026-03-19 20:19:41 +08:00
const loadProductImages = async () => {
for (const item of cartItems.value) {
if (!item.originalProductImage) continue
const match = item.originalProductImage.replace(/<[^>]*>/g, '').match(/\/api\/file\/get\/(\d+)/)
if (!match?.[1]) continue
const imageId = match[1]
try {
if (!imageIdCache.value[imageId]) {
2026-03-27 14:55:41 +08:00
imageIdCache.value[imageId] = await fileApi.getSignedUrl(imageId) as any
}
2026-03-19 20:19:41 +08:00
item.productImage = imageIdCache.value[imageId] || ''
} catch {
item.productImage = ''
}
2026-02-25 10:37:16 +08:00
}
}
2026-03-19 20:19:41 +08:00
const loadAvailableCoupons = async () => {
if (editing.value) {
return
}
const currentSelectedKey = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : couponSelectionKey.value
const selectedShopId = selectedItems.value[0]?.shopId
if (!selectedItems.value.length || subtotal.value <= 0) {
2026-03-19 20:19:41 +08:00
availableCoupons.value = []
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
return
}
try {
2026-03-27 15:04:58 +08:00
// 这里只做“最佳 VIP 自动券”兜底预选,普通用户券必须显式点选后才会消耗。
const tags = new Set<string>()
selectedItems.value.forEach(item => {
item.tagNames?.split(',').map(tag => tag.trim()).forEach(tag => {
if (tag) {
tags.add(tag)
}
})
})
const data = await couponApi.getAvailableCoupons(Array.from(tags).join(','), subtotal.value, selectedShopId) as unknown as UserCoupon[]
availableCoupons.value = Array.isArray(data) ? data : []
const matchedCoupon = availableCoupons.value.find(coupon => getCouponKey(coupon) === currentSelectedKey) || null
if (matchedCoupon) {
selectedCoupon.value = matchedCoupon
couponSelectionKey.value = getCouponKey(matchedCoupon)
return
}
if (couponSelectionTouched.value && currentSelectedKey === NO_COUPON_KEY) {
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
return
}
couponSelectionTouched.value = false
const defaultVipCoupon = findBestSystemVipCoupon(availableCoupons.value)
if (defaultVipCoupon) {
selectedCoupon.value = defaultVipCoupon
couponSelectionKey.value = getCouponKey(defaultVipCoupon)
} else {
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
}
} catch (error) {
console.error('获取可用优惠失败:', error)
availableCoupons.value = []
selectedCoupon.value = null
couponSelectionKey.value = NO_COUPON_KEY
2026-02-25 10:37:16 +08:00
}
}
2026-03-19 20:19:41 +08:00
const changeQuantity = async (item: CartItem, delta: number) => {
const next = item.quantity + delta
if (next < 1 || next > 99) return
item.quantity = next
try {
await cartApi.updateCartQuantity({ productId: item.productId, quantity: next })
await Promise.all([loadAvailableCoupons(), updateCartCount()])
} catch {
item.quantity -= delta
message.error('更新数量失败')
}
}
const removeItem = async (item: CartItem) => {
try {
await cartApi.removeFromCart(item.productId)
2026-03-27 14:55:41 +08:00
cartItems.value = cartItems.value.filter(current => !sameId(current.id, item.id))
2026-03-19 20:19:41 +08:00
await Promise.all([loadAvailableCoupons(), updateCartCount()])
message.success('作品已删除')
} catch {
2026-03-05 16:08:27 +08:00
message.error('删除作品失败')
}
}
const removeSelectedItems = async () => {
if (!selectedItems.value.length) {
message.warning('请先勾选要删除的作品')
return
}
try {
await Promise.all(selectedItems.value.map(item => cartApi.removeFromCart(item.productId)))
await Promise.all([loadCartItems(), updateCartCount()])
message.success('已删除选中的作品')
} catch (error) {
console.error('批量删除失败:', error)
message.error('批量删除失败,请稍后重试')
}
}
const openProduct = (item: CartItem) => {
router.push('/product/' + item.productId)
}
2026-03-19 20:19:41 +08:00
const openBookingModal = async (item: CartItem) => {
currentItem.value = item
draftArtistId.value = item.artistId
2026-03-21 13:16:39 +08:00
draftAppointmentTime.value = item.appointmentTime || ''
2026-03-19 20:19:41 +08:00
showBookingModal.value = true
await Promise.all([loadArtists(item), loadShopHours(item.shopId)])
2026-03-02 10:13:20 +08:00
}
2026-03-19 20:19:41 +08:00
const loadArtists = async (item: CartItem) => {
2026-03-27 15:04:58 +08:00
// 购物车里保存的是后端已经按作品可约范围裁剪过的美甲师列表,这里只做前端展示和 ID 保真。
availableArtists.value = Array.isArray(item.availableArtists)
? item.availableArtists
.filter(artist => artist && artist.id !== undefined && artist.id !== null)
.map(artist => ({
2026-03-27 14:55:41 +08:00
id: artist.id,
name: artist.name,
avatar: artist.avatar
}))
: []
2026-03-27 14:55:41 +08:00
if (draftArtistId.value && !availableArtists.value.some(artist => sameId(artist.id, draftArtistId.value))) {
draftArtistId.value = undefined
}
}
2026-03-27 14:55:41 +08:00
const loadShopHours = async (shopId?: IdType) => {
2026-03-19 20:19:41 +08:00
currentShopHours.value = ''
if (!shopId) return
try {
const shop = await shopApi.getShopById(shopId) as any
currentShopHours.value = shop?.businessHours || ''
} catch {
currentShopHours.value = ''
}
}
2026-03-21 13:16:39 +08:00
const disablePastAppointmentDate = (current: any) => {
if (!current) return false
2026-03-21 13:16:39 +08:00
return current.valueOf() < getDayBoundary(new Date())
}
2026-03-21 13:16:39 +08:00
const disablePastAppointmentTime = (current: any) => {
if (!current || typeof current.format !== 'function') {
return {}
}
const minDate = getMinAppointmentDate()
const minDateText = [
minDate.getFullYear(),
String(minDate.getMonth() + 1).padStart(2, '0'),
String(minDate.getDate()).padStart(2, '0')
].join('-')
if (current.format('YYYY-MM-DD') !== minDateText) {
return {}
}
const minHour = minDate.getHours()
const minMinute = minDate.getMinutes()
return {
disabledHours: () => Array.from({ length: minHour }, (_, index) => index),
disabledMinutes: (selectedHour: number) => selectedHour === minHour
? Array.from({ length: minMinute }, (_, index) => index)
: [],
disabledSeconds: () => []
}
}
2026-03-19 20:19:41 +08:00
const closeBookingModal = () => {
showBookingModal.value = false
currentItem.value = null
draftArtistId.value = undefined
draftAppointmentTime.value = ''
availableArtists.value = []
currentShopHours.value = ''
}
const confirmBooking = () => {
if (!currentItem.value) return closeBookingModal()
if (!draftArtistId.value) return message.warning('请先选择美甲师')
if (!draftAppointmentTime.value) return message.warning('请选择预约时间')
2026-03-21 13:16:39 +08:00
if (isPastAppointment(draftAppointmentTime.value)) return message.warning('预约时间至少需要晚于当前 5 分钟')
2026-03-19 20:19:41 +08:00
currentItem.value.artistId = draftArtistId.value
2026-03-27 14:55:41 +08:00
currentItem.value.artist = availableArtists.value.find(artist => sameId(artist.id, draftArtistId.value))
2026-03-21 13:16:39 +08:00
currentItem.value.appointmentTime = draftAppointmentTime.value
2026-03-19 20:19:41 +08:00
closeBookingModal()
}
const openCouponModal = () => {
couponSelectionKey.value = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : NO_COUPON_KEY
showCouponModal.value = true
}
2026-03-19 20:19:41 +08:00
const applyCouponSelection = () => {
couponSelectionTouched.value = true
if (couponSelectionKey.value === NO_COUPON_KEY) {
selectedCoupon.value = null
} else {
selectedCoupon.value = availableCoupons.value.find(coupon => getCouponKey(coupon) === couponSelectionKey.value) || null
}
2026-02-28 17:09:45 +08:00
showCouponModal.value = false
}
2026-03-19 20:19:41 +08:00
const checkout = async () => {
const items = selectedItems.value
if (!items.length) {
return message.warning('请先选择要结算的作品')
}
const firstIssue = checkoutIssues.value[0]
if (firstIssue) {
message.warning(firstIssue.message)
scrollToIssue(firstIssue)
return
}
try {
2026-03-02 10:13:20 +08:00
await orderApi.createOrder({
2026-03-19 20:19:41 +08:00
couponId: selectedCoupon.value?.id,
couponSourceType: selectedCoupon.value?.sourceType || (couponSelectionTouched.value && !selectedCoupon.value ? NO_COUPON_KEY : undefined),
2026-03-19 20:19:41 +08:00
items: items.map(item => ({
2026-03-19 14:10:59 +08:00
productId: item.productId,
quantity: item.quantity,
2026-03-19 20:19:41 +08:00
artistId: item.artistId,
appointmentTime: item.appointmentTime
2026-03-19 14:10:59 +08:00
}))
})
2026-03-19 20:19:41 +08:00
await Promise.all([loadCartItems(), updateCartCount()])
message.success('订单创建成功')
2026-03-19 20:19:41 +08:00
router.push('/orders')
} catch (error: any) {
console.error('创建订单失败:', error)
message.error(error?.message || '创建订单失败')
}
}
watch(
() => cartItems.value.map(item => `${item.id}-${item.selected}-${item.quantity}`).join('|'),
() => {
void loadAvailableCoupons()
}
)
2026-03-19 14:10:59 +08:00
2026-03-19 20:19:41 +08:00
onMounted(async () => {
try {
await loadCartItems()
} catch {
message.error('获取购物车数据失败')
2026-03-19 14:10:59 +08:00
}
})
</script>
<style scoped>
.page {
min-height: 100vh;
padding-top: 60px;
background: #f5f5f5;
}
2026-03-24 09:50:55 +08:00
.header,
.footer {
position: fixed;
left: 0;
right: 0;
background: #fff;
z-index: 10;
}
.header {
top: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 15px;
border-bottom: 1px solid #f0f0f0;
}
.header h1 {
margin: 0;
font-size: 18px;
font-weight: 700;
}
.content {
max-width: 980px;
margin: 0 auto;
padding: 16px 16px 140px;
}
.issue-alert {
margin-bottom: 16px;
border-radius: 16px;
}
.item-card,
.coupon-card,
.summary-card {
margin-bottom: 12px;
border-radius: 16px;
}
.issue-card {
border-color: #faad14;
box-shadow: 0 8px 24px rgba(250, 173, 20, 0.12);
}
.item-row {
display: flex;
gap: 12px;
align-items: flex-start;
}
.thumb {
width: 84px;
height: 84px;
border-radius: 12px;
overflow: hidden;
background: #eef3ff;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
.thumb img {
width: 100%;
height: 100%;
object-fit: cover;
}
.item-main {
flex: 1;
}
.title {
font-size: 15px;
font-weight: 700;
cursor: pointer;
}
.price {
margin: 6px 0 10px;
color: #ff4d4f;
font-weight: 700;
}
.selector {
display: flex;
align-items: center;
gap: 8px;
padding: 10px 12px;
margin-bottom: 10px;
border: 1px solid transparent;
border-radius: 10px;
background: #f8f9ff;
cursor: pointer;
}
.selector.issue {
border-color: #faad14;
background: #fff7e6;
}
.selector .label {
min-width: 56px;
color: #666;
font-size: 13px;
}
.selector .value {
flex: 1;
color: #1677ff;
font-size: 13px;
}
.duration,
.coupon-tip,
.helper {
color: #666;
font-size: 12px;
}
.actions,
.qty,
.coupon-row,
.summary-row,
.coupon-extra {
display: flex;
align-items: center;
justify-content: space-between;
}
.qty {
gap: 8px;
}
.coupon-extra {
margin-top: 10px;
color: #666;
gap: 12px;
}
.summary-row {
margin-bottom: 10px;
}
.summary-row.total {
margin-bottom: 0;
font-weight: 700;
}
.footer {
bottom: 60px;
padding: 15px;
border-top: 1px solid #f0f0f0;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
}
.coupon-options {
display: flex;
flex-direction: column;
gap: 8px;
}
.modal-section + .modal-section {
margin-top: 16px;
}
.section-title {
margin-bottom: 8px;
font-weight: 700;
}
.artist-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.artist-option {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 12px;
border: 1px solid #d9d9d9;
border-radius: 999px;
background: #fff;
cursor: pointer;
}
.artist-option.active {
border-color: #1677ff;
color: #1677ff;
background: #f0f9ff;
}
.artist-option img {
width: 24px;
height: 24px;
border-radius: 50%;
object-fit: cover;
}
@media (max-width: 767px) {
.content {
padding: 15px 15px 140px;
2026-03-24 09:50:55 +08:00
}
}
2026-03-19 20:19:41 +08:00
</style>