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

410 lines
17 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>
2026-03-19 20:19:41 +08:00
<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>
2026-03-19 20:19:41 +08:00
<a-card v-if="selectedCount" class="coupon-card" @click="showCouponModal = true">
<div class="coupon-row">
<span>优惠券</span>
<span>{{ selectedCoupon?.couponName || '使用优惠券' }}</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="couponSelectionId" class="coupon-options">
<a-radio :value="0">不使用优惠券</a-radio>
<a-radio v-for="coupon in availableCoupons" :key="coupon.id" :value="coupon.id">
{{ coupon.couponName }}
</a-radio>
</a-radio-group>
</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>
<input v-model="draftAppointmentTime" class="time-input" type="datetime-local" :min="minAppointmentTime" step="1800" />
<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 () => {})
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)
2026-03-19 20:19:41 +08:00
const couponSelectionId = ref(0)
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('')
2026-03-19 20:19:41 +08:00
const selectedCount = computed(() => cartItems.value.filter(item => item.selected).length)
const totalQuantity = computed(() => cartItems.value.filter(item => item.selected).reduce((sum, item) => sum + item.quantity, 0))
const subtotal = computed(() => cartItems.value.filter(item => item.selected).reduce((sum, item) => sum + item.price * item.quantity, 0))
const discountAmount = computed(() => {
if (!selectedCoupon.value) return 0
2026-03-19 20:19:41 +08:00
if (selectedCoupon.value.couponType === 1) return subtotal.value - subtotal.value * parseFloat(selectedCoupon.value.discountValue) / 10
if (selectedCoupon.value.couponType === 2) return parseFloat(selectedCoupon.value.reduceAmount)
return 0
})
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)
return texts.join(' · ') || '请选择晚于当前时间的预约时间'
})
const minAppointmentTime = computed(() => {
const d = new Date()
d.setSeconds(0, 0)
d.setMinutes(d.getMinutes() + 5)
return [
d.getFullYear(),
'-',
String(d.getMonth() + 1).padStart(2, '0'),
'-',
String(d.getDate()).padStart(2, '0'),
'T',
String(d.getHours()).padStart(2, '0'),
':',
String(d.getMinutes()).padStart(2, '0')
].join('')
})
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
}))
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 {
2026-03-19 20:19:41 +08:00
if (!imageIdCache.value[imageId]) imageIdCache.value[imageId] = await fileApi.getSignedUrl(Number(imageId)) as any
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 () => {
try {
const tags = new Set<string>()
cartItems.value.filter(item => item.selected).forEach(item => item.tagNames?.split(',').map(tag => tag.trim()).forEach(tag => tag && tags.add(tag)))
const data = subtotal.value > 0 ? await couponApi.getAvailableCoupons(Array.from(tags).join(','), subtotal.value) as unknown as any[] : []
availableCoupons.value = data || []
if (selectedCoupon.value && !availableCoupons.value.some(coupon => coupon.id === selectedCoupon.value?.id)) selectedCoupon.value = null
couponSelectionId.value = selectedCoupon.value?.id || 0
} catch {
availableCoupons.value = []
selectedCoupon.value = null
couponSelectionId.value = 0
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
draftAppointmentTime.value = item.appointmentTime ? item.appointmentTime.replace(' ', 'T').slice(0, 16) : ''
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) : '未选择预约时间'
const isPastAppointment = (value?: string) => !!value && new Date(value.replace(' ', 'T')).getTime() <= Date.now()
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('请选择预约时间')
const normalizedTime = draftAppointmentTime.value.replace('T', ' ') + ':00'
if (isPastAppointment(normalizedTime)) return message.warning('预约时间必须晚于当前时间')
currentItem.value.artistId = draftArtistId.value
currentItem.value.artist = availableArtists.value.find(artist => artist.id === draftArtistId.value)
currentItem.value.appointmentTime = normalizedTime
closeBookingModal()
}
const applyCouponSelection = () => {
selectedCoupon.value = availableCoupons.value.find(coupon => coupon.id === couponSelectionId.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 = cartItems.value.filter(item => item.selected)
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,
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 {
message.error('创建订单失败')
}
}
2026-03-19 20:19:41 +08:00
watch(() => cartItems.value.map(item => String(item.id) + '-' + item.selected + '-' + item.quantity), 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 { color: #666; font-size: 12px; }
.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; }
.time-input { width: 100%; padding: 10px 12px; border: 1px solid #d9d9d9; border-radius: 8px; }
</style>