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

551 lines
21 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>
2026-03-19 20:19:41 +08:00
<a-button type="text">编辑</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>
2026-03-19 20:19:41 +08:00
<a-card v-for="item in cartItems" :key="item.id" class="item-card">
<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">¥{{ item.price.toFixed(2) }}</div>
<div class="selector" @click="openBookingModal(item)">
<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" @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>
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" 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>
2026-03-19 20:19:41 +08:00
<div v-if="selectedCoupon" class="coupon-discount">优惠金额 -¥{{ discountAmount.toFixed(2) }}</div>
</a-card>
2026-03-19 20:19:41 +08:00
<a-card v-if="cartItems.length" class="summary-card">
<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>
2026-03-19 20:19:41 +08:00
<footer v-if="cartItems.length" class="footer">
<a-button type="primary" size="large" block @click="checkout">
结算 {{ selectedCount }} 个项目,预计金额 ¥{{ totalAmount.toFixed(2) }}
</a-button>
2026-03-19 20:19:41 +08:00
</footer>
2026-03-19 20:19:41 +08:00
<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"
:class="{ active: draftArtistId === artist.id }"
@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>
2026-03-19 20:19:41 +08:00
<a-empty v-else description="暂无可用美甲师" />
</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-04 15:42:43 +08:00
import api from '../api'
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'
import { userApi } from '../api/user'
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 {
id: number
name: string
avatar?: string
}
interface CartItem {
id: number
productId: number
2026-03-19 20:19:41 +08:00
shopId?: number
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
appointmentTime?: string
selected: boolean
2026-03-19 14:10:59 +08:00
artistId?: number
2026-03-19 20:19:41 +08:00
artist?: ArtistOption
}
const cartItems = ref<CartItem[]>([])
const imageIdCache = ref<Record<string, string>>({})
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[]>([])
const draftArtistId = ref<number>()
const draftAppointmentTime = ref('')
const currentShopHours = ref('')
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 + item.price * 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 + ' 选择预约信息' : '选择预约信息')
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}`
const calculateCouponDiscount = (coupon: UserCoupon | null, amount: number) => {
if (!coupon || amount <= 0) {
return 0
}
if (coupon.couponType === 1) {
const discountValue = Number(coupon.discountValue || 0)
if (!discountValue) {
return 0
}
return amount - amount * discountValue / 10
}
if (coupon.couponType === 2) {
return Number(coupon.reduceAmount || 0)
}
return 0
}
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 findBestSystemVipCoupon = (coupons: UserCoupon[]) => {
return coupons
.filter(coupon => coupon.sourceType === 'SYSTEM_VIP')
.sort((left, right) => calculateCouponDiscount(right, subtotal.value) - calculateCouponDiscount(left, subtotal.value))[0] || null
}
2026-03-19 20:19:41 +08:00
const openProduct = (item: CartItem) => {
router.push('/product/' + item.productId)
}
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 => ({
...item,
selected: true,
originalProductImage: item.productImage,
productImage: '',
appointmentTime: item.appointmentTime
}))
couponSelectionTouched.value = false
couponSelectionKey.value = NO_COUPON_KEY
selectedCoupon.value = null
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]) {
imageIdCache.value[imageId] = await fileApi.getSignedUrl(Number(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 () => {
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 {
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-19 20:19:41 +08:00
cartItems.value = cartItems.value.filter(current => current.id !== item.id)
await Promise.all([loadAvailableCoupons(), updateCartCount()])
message.success('作品已删除')
} catch {
2026-03-05 16:08:27 +08:00
message.error('删除作品失败')
}
}
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) => {
const users = await userApi.listUsersByType(3) as unknown as any[]
const allowedIds = new Set((item.bookableArtists || '').split(',').map(id => Number(id.trim())).filter(id => Number.isFinite(id) && id > 0))
availableArtists.value = await Promise.all(
users
.filter(user => (!item.shopId || user.shopId === item.shopId) && (!allowedIds.size || allowedIds.has(user.id)))
.map(async user => {
try {
const detail = await api.get('/nail-artist/get/' + user.id) as any
return { id: user.id, name: user.nickname, avatar: user.avatar || detail?.avatar }
} catch {
return { id: user.id, name: user.nickname, avatar: user.avatar }
}
})
)
}
2026-03-19 20:19:41 +08:00
const loadShopHours = async (shopId?: number) => {
currentShopHours.value = ''
if (!shopId) return
try {
const shop = await shopApi.getShopById(shopId) as any
currentShopHours.value = shop?.businessHours || ''
} catch {
currentShopHours.value = ''
}
}
const formatAppointmentDisplay = (value?: string) => value ? value.replace('T', ' ').slice(0, 16) : '未选择预约时间'
2026-03-21 13:16:39 +08:00
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() < getMinAppointmentDate().getTime()
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: () => []
}
}
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
currentItem.value.artist = availableArtists.value.find(artist => 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
2026-03-19 20:19:41 +08:00
if (!items.length) return message.warning('请先选择要结算的作品')
if (items.some(item => !item.artistId)) return message.warning('请先为所有项目选择美甲师')
if (items.some(item => !item.appointmentTime)) return message.warning('请先为所有项目选择预约时间')
if (items.some(item => isPastAppointment(item.appointmentTime))) return message.warning('存在已过期的预约时间,请重新选择')
if (new Set(items.map(item => item.shopId).filter(Boolean)).size > 1) return message.warning('跨店铺商品请分开结算')
if (new Set(items.map(item => item.artistId).filter(Boolean)).size > 1) return message.warning('不同美甲师的项目请分开结算')
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>
2026-03-19 20:19:41 +08:00
.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; }
.content { padding: 15px; padding-bottom: 140px; }
.item-card, .coupon-card, .summary-card { margin-bottom: 12px; border-radius: 12px; }
.item-row { display: flex; gap: 12px; align-items: flex-start; }
.thumb { width: 80px; height: 80px; border-radius: 8px; 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-weight: 600; cursor: pointer; }
.price { margin: 4px 0 10px; color: #ff4d4f; font-weight: 700; }
.selector { display: flex; align-items: center; gap: 8px; padding: 10px 12px; margin-bottom: 10px; border-radius: 8px; background: #f8f9ff; cursor: pointer; }
.selector .label { min-width: 56px; color: #666; font-size: 13px; }
.selector .value { flex: 1; color: #1890ff; font-size: 13px; }
.actions, .qty, .coupon-row, .summary-row { display: flex; align-items: center; justify-content: space-between; }
.qty { gap: 8px; }
.duration, .coupon-discount, .helper, .coupon-tip { color: #666; font-size: 12px; }
.coupon-tip { margin-top: 12px; line-height: 1.6; }
2026-03-19 20:19:41 +08:00
.summary-row.total { font-weight: 700; }
.footer { bottom: 60px; padding: 15px; border-top: 1px solid #f0f0f0; box-shadow: 0 -2px 8px rgba(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: 600; }
.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: #1890ff; color: #1890ff; background: #f0f9ff; }
.artist-option img { width: 24px; height: 24px; border-radius: 50%; object-fit: cover; }
2026-03-21 13:16:39 +08:00
.time-picker { border-radius: 8px; }
2026-03-24 09:50:55 +08:00
@media (min-width: 992px) {
.content {
max-width: 980px;
margin: 0 auto;
padding: 24px 24px 140px;
2026-03-24 09:50:55 +08:00
}
}
2026-03-19 20:19:41 +08:00
</style>