880 lines
26 KiB
Vue
880 lines
26 KiB
Vue
<template>
|
||
<div class="page">
|
||
<header class="header">
|
||
<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>
|
||
|
||
<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) }"
|
||
>
|
||
<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>
|
||
<div class="item-main">
|
||
<div class="title" @click="openProduct(item)">{{ item.productTitle }}</div>
|
||
<div class="price">¥{{ Number(item.price || 0).toFixed(2) }}</div>
|
||
|
||
<div class="selector" :class="{ issue: item.selected && !item.artistId }" @click="openBookingModal(item)">
|
||
<span class="label">美甲师</span>
|
||
<span class="value">{{ item.artist?.name || '请选择美甲师' }}</span>
|
||
<RightOutlined />
|
||
</div>
|
||
|
||
<div
|
||
class="selector"
|
||
:class="{ issue: item.selected && (!item.appointmentTime || isPastAppointment(item.appointmentTime)) }"
|
||
@click="openBookingModal(item)"
|
||
>
|
||
<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>
|
||
</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">
|
||
<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>
|
||
<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>
|
||
</a-card>
|
||
</main>
|
||
|
||
<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>
|
||
</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) }}
|
||
</a-radio>
|
||
</a-radio-group>
|
||
<div class="coupon-tip">
|
||
系统只会默认预选最佳 VIP 自动券,普通用户券需要你手动选择后才会在下单时使用。
|
||
</div>
|
||
</a-modal>
|
||
|
||
<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"
|
||
:class="{ active: sameId(draftArtistId, artist.id) }"
|
||
@click="draftArtistId = artist.id"
|
||
>
|
||
<img v-if="artist.avatar" :src="artist.avatar" :alt="artist.name" />
|
||
<span>{{ artist.name }}</span>
|
||
</button>
|
||
</div>
|
||
<a-empty v-else description="暂无可预约美甲师" />
|
||
</div>
|
||
|
||
<div class="modal-section">
|
||
<div class="section-title">预约时间</div>
|
||
<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="请选择预约时间"
|
||
/>
|
||
<div class="helper">{{ bookingHelperText }}</div>
|
||
</div>
|
||
</a-modal>
|
||
</div>
|
||
</template>
|
||
|
||
<script setup lang="ts">
|
||
import { computed, inject, onMounted, ref, watch } from 'vue'
|
||
import { useRouter } from 'vue-router'
|
||
import { DeleteOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue'
|
||
import { message } from 'ant-design-vue'
|
||
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'
|
||
import type { IdType } from '@/utils/id'
|
||
import { sameId, toOptionalIdString } from '@/utils/id'
|
||
|
||
const router = useRouter()
|
||
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
|
||
|
||
const NO_COUPON_KEY = 'NONE'
|
||
|
||
interface ArtistOption {
|
||
id: IdType
|
||
name: string
|
||
avatar?: string
|
||
}
|
||
|
||
interface CartItem {
|
||
id: IdType
|
||
productId: IdType
|
||
shopId?: IdType
|
||
productTitle: string
|
||
productImage: string
|
||
originalProductImage?: string
|
||
price: number
|
||
quantity: number
|
||
totalPrice: number
|
||
tags: string
|
||
tagNames?: string
|
||
approximateDuration?: string
|
||
bookableArtists?: string
|
||
availableBookableArtistCount?: number
|
||
bookableArtistRestricted?: boolean
|
||
availableArtists?: ArtistOption[]
|
||
appointmentTime?: string
|
||
selected: boolean
|
||
artistId?: IdType
|
||
artist?: ArtistOption
|
||
}
|
||
|
||
interface CheckoutIssue {
|
||
key: string
|
||
message: string
|
||
itemId?: IdType
|
||
}
|
||
|
||
const cartItems = ref<CartItem[]>([])
|
||
const imageIdCache = ref<Record<string, string>>({})
|
||
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)
|
||
const showBookingModal = ref(false)
|
||
const currentItem = ref<CartItem | null>(null)
|
||
const availableArtists = ref<ArtistOption[]>([])
|
||
const draftArtistId = ref<IdType>()
|
||
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))
|
||
const totalAmount = computed(() => Math.max(0, subtotal.value - discountAmount.value))
|
||
const bookingTitle = computed(() => currentItem.value ? `为 ${currentItem.value.productTitle} 选择预约信息` : '选择预约信息')
|
||
const bookingHelperText = computed(() => {
|
||
const texts: string[] = []
|
||
if (currentShopHours.value) texts.push(`门店营业时间:${currentShopHours.value}`)
|
||
if (currentItem.value?.approximateDuration) texts.push(`预计时长:${currentItem.value.approximateDuration}`)
|
||
return texts.join(' · ') || '请选择至少晚于当前 5 分钟的预约时间'
|
||
})
|
||
|
||
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}`
|
||
|
||
const setItemRef = (itemId: IdType, element: unknown) => {
|
||
const refKey = toOptionalIdString(itemId)
|
||
if (!refKey) {
|
||
return
|
||
}
|
||
if (element && (element as any).$el) {
|
||
itemRefs.value[refKey] = (element as any).$el as HTMLElement
|
||
return
|
||
}
|
||
if (element instanceof HTMLElement) {
|
||
itemRefs.value[refKey] = element
|
||
return
|
||
}
|
||
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)
|
||
|
||
// 购物车结算口径要求单店铺、单美甲师、完整预约信息,避免后端拆单和排班出现歧义。
|
||
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 })
|
||
}
|
||
|
||
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 })
|
||
}
|
||
|
||
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) => {
|
||
const itemId = toOptionalIdString(issue?.itemId)
|
||
if (!itemId) {
|
||
return
|
||
}
|
||
const target = itemRefs.value[itemId]
|
||
if (target) {
|
||
target.scrollIntoView({ behavior: 'smooth', block: 'center' })
|
||
}
|
||
}
|
||
|
||
const focusFirstIssue = () => {
|
||
scrollToIssue(checkoutIssues.value[0])
|
||
}
|
||
|
||
const loadCartItems = async () => {
|
||
const response = await cartApi.getCartList() as unknown as any[]
|
||
cartItems.value = (response || []).map(item => ({
|
||
...item,
|
||
selected: true,
|
||
originalProductImage: item.productImage,
|
||
productImage: '',
|
||
appointmentTime: item.appointmentTime
|
||
}))
|
||
couponSelectionTouched.value = false
|
||
couponSelectionKey.value = NO_COUPON_KEY
|
||
selectedCoupon.value = null
|
||
editing.value = false
|
||
await Promise.all([loadProductImages(), loadAvailableCoupons()])
|
||
}
|
||
|
||
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]) {
|
||
imageIdCache.value[imageId] = await fileApi.getSignedUrl(imageId) as any
|
||
}
|
||
item.productImage = imageIdCache.value[imageId] || ''
|
||
} catch {
|
||
item.productImage = ''
|
||
}
|
||
}
|
||
}
|
||
|
||
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) {
|
||
availableCoupons.value = []
|
||
selectedCoupon.value = null
|
||
couponSelectionKey.value = NO_COUPON_KEY
|
||
return
|
||
}
|
||
|
||
try {
|
||
// 这里只做“最佳 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
|
||
}
|
||
}
|
||
|
||
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)
|
||
cartItems.value = cartItems.value.filter(current => !sameId(current.id, item.id))
|
||
await Promise.all([loadAvailableCoupons(), updateCartCount()])
|
||
message.success('作品已删除')
|
||
} catch {
|
||
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)
|
||
}
|
||
|
||
const openBookingModal = async (item: CartItem) => {
|
||
currentItem.value = item
|
||
draftArtistId.value = item.artistId
|
||
draftAppointmentTime.value = item.appointmentTime || ''
|
||
showBookingModal.value = true
|
||
await Promise.all([loadArtists(item), loadShopHours(item.shopId)])
|
||
}
|
||
|
||
const loadArtists = async (item: CartItem) => {
|
||
// 购物车里保存的是后端已经按作品可约范围裁剪过的美甲师列表,这里只做前端展示和 ID 保真。
|
||
availableArtists.value = Array.isArray(item.availableArtists)
|
||
? item.availableArtists
|
||
.filter(artist => artist && artist.id !== undefined && artist.id !== null)
|
||
.map(artist => ({
|
||
id: artist.id,
|
||
name: artist.name,
|
||
avatar: artist.avatar
|
||
}))
|
||
: []
|
||
|
||
if (draftArtistId.value && !availableArtists.value.some(artist => sameId(artist.id, draftArtistId.value))) {
|
||
draftArtistId.value = undefined
|
||
}
|
||
}
|
||
|
||
const loadShopHours = async (shopId?: IdType) => {
|
||
currentShopHours.value = ''
|
||
if (!shopId) return
|
||
try {
|
||
const shop = await shopApi.getShopById(shopId) as any
|
||
currentShopHours.value = shop?.businessHours || ''
|
||
} catch {
|
||
currentShopHours.value = ''
|
||
}
|
||
}
|
||
|
||
const disablePastAppointmentDate = (current: any) => {
|
||
if (!current) return false
|
||
return current.valueOf() < getDayBoundary(new Date())
|
||
}
|
||
|
||
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: () => []
|
||
}
|
||
}
|
||
|
||
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('请选择预约时间')
|
||
if (isPastAppointment(draftAppointmentTime.value)) return message.warning('预约时间至少需要晚于当前 5 分钟')
|
||
currentItem.value.artistId = draftArtistId.value
|
||
currentItem.value.artist = availableArtists.value.find(artist => sameId(artist.id, draftArtistId.value))
|
||
currentItem.value.appointmentTime = draftAppointmentTime.value
|
||
closeBookingModal()
|
||
}
|
||
|
||
const openCouponModal = () => {
|
||
couponSelectionKey.value = selectedCoupon.value ? getCouponKey(selectedCoupon.value) : NO_COUPON_KEY
|
||
showCouponModal.value = true
|
||
}
|
||
|
||
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
|
||
}
|
||
showCouponModal.value = false
|
||
}
|
||
|
||
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 {
|
||
await orderApi.createOrder({
|
||
couponId: selectedCoupon.value?.id,
|
||
couponSourceType: selectedCoupon.value?.sourceType || (couponSelectionTouched.value && !selectedCoupon.value ? NO_COUPON_KEY : undefined),
|
||
items: items.map(item => ({
|
||
productId: item.productId,
|
||
quantity: item.quantity,
|
||
artistId: item.artistId,
|
||
appointmentTime: item.appointmentTime
|
||
}))
|
||
})
|
||
await Promise.all([loadCartItems(), updateCartCount()])
|
||
message.success('订单创建成功')
|
||
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()
|
||
}
|
||
)
|
||
|
||
onMounted(async () => {
|
||
try {
|
||
await loadCartItems()
|
||
} catch {
|
||
message.error('获取购物车数据失败')
|
||
}
|
||
})
|
||
</script>
|
||
|
||
<style scoped>
|
||
.page {
|
||
min-height: 100vh;
|
||
padding-top: 60px;
|
||
background: #f5f5f5;
|
||
}
|
||
|
||
.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;
|
||
}
|
||
}
|
||
</style>
|