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

904 lines
21 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="mobile-container">
<!-- 头部区域 -->
<header class="header">
<a-button class="back-btn" type="text" @click="handleBackClick">
<LeftOutlined :style="{ fontSize: '20px' }" />
</a-button>
<h1>购物车</h1>
<a-button class="edit-btn" type="text" @click="handleEditClick">
编辑
</a-button>
</header>
<!-- 购物车商品列表 -->
<div class="cart-items">
<a-empty v-if="cartItems.length === 0" description="购物车是空的">
<a-button type="primary" @click="handleBrowseProducts">去逛逛</a-button>
</a-empty>
<a-card
v-for="item in cartItems"
:key="item.id"
class="cart-item"
:body-style="{ padding: '16px' }"
>
<div class="item-content">
<!-- 复选框 -->
<a-checkbox v-model:checked="item.selected" @change="handleSelectChange" />
<!-- 商品图片 -->
<div class="item-image" v-if="item.productImage">
<img :src="item.productImage" :alt="item.productTitle" />
</div>
<div class="item-image" v-else :style="{ backgroundColor: getRandomColor() }">
<span>{{ item.productTitle[0] }}</span>
</div>
<!-- 商品详情 -->
<div class="item-details">
<h3 class="item-name">{{ item.productTitle }}</h3>
<p class="item-price">¥{{ item.price.toFixed(2) }}</p>
<!-- 数量控制和删除按钮 -->
<div class="item-actions">
<div class="quantity-control">
<a-button
size="small"
:disabled="item.quantity <= 1"
@click="handleDecreaseQuantity(item)"
>
-
</a-button>
<span class="quantity-value">{{ item.quantity }}</span>
<a-button
size="small"
:disabled="item.quantity >= 99"
@click="handleIncreaseQuantity(item)"
>
+
</a-button>
</div>
<a-popconfirm
title="确定要删除这个商品吗?"
ok-text="确定"
cancel-text="取消"
@confirm="handleDeleteItem(item)"
>
<a-button type="text" danger size="small">
<DeleteOutlined />
</a-button>
</a-popconfirm>
</div>
</div>
</div>
</a-card>
</div>
<!-- 优惠券选择 -->
<div class="coupon-section" v-if="cartItems.length > 0 && selectedCount > 0">
<a-card class="coupon-card">
<div class="coupon-header" @click="showCouponModal = true">
<span class="coupon-title">优惠券</span>
<div class="coupon-value">
{{ selectedCoupon ? '已选择: ' + selectedCoupon.couponName : '请选择' }}
<RightOutlined :style="{ marginLeft: '4px' }" />
</div>
</div>
<div class="coupon-discount" v-if="selectedCoupon">
<span class="discount-label">优惠金额</span>
<span class="discount-amount">-¥{{ discountAmount.toFixed(2) }}</span>
</div>
</a-card>
</div>
<!-- 订单摘要 -->
<div class="summary" v-if="cartItems.length > 0">
<div class="summary-row">
<span>商品数量</span>
<span>{{ totalQuantity }} 件</span>
</div>
<div class="summary-row">
<span>小计</span>
<span>¥{{ subtotal.toFixed(2) }}</span>
</div>
<div class="summary-row" v-if="selectedCoupon">
<span>优惠</span>
<span class="discount">-¥{{ discountAmount.toFixed(2) }}</span>
</div>
<div class="summary-row total">
<span>总计</span>
<span class="total-price">¥{{ totalAmount.toFixed(2) }}</span>
</div>
</div>
<!-- 结算按钮 -->
<div class="checkout-section" v-if="cartItems.length > 0">
<a-button
type="primary"
size="large"
block
@click="handleCheckout"
>
结算 ({{ selectedCount }}) - ¥{{ totalAmount.toFixed(2) }}
</a-button>
</div>
<!-- 优惠券选择弹窗 -->
<a-modal
v-model:visible="showCouponModal"
title="选择优惠券"
width="90%"
@ok="confirmCouponSelection"
@cancel="cancelCouponSelection"
>
<div class="coupon-modal-content">
<a-empty v-if="availableCoupons.length === 0" description="暂无可用优惠券" />
<div v-else class="coupon-list">
<!-- 取消选择选项 -->
<a-card
class="modal-coupon-card"
:class="{ active: !selectedCoupon }"
@click="selectedCoupon = null"
>
<div class="coupon-content">
<div class="coupon-value">
不使用
</div>
<div class="coupon-info">
<div class="coupon-name">不使用优惠券</div>
<div class="coupon-condition">
直接结算
</div>
<div class="coupon-select" v-if="!selectedCoupon">
<CheckCircleOutlined />
</div>
</div>
</div>
</a-card>
<a-divider />
<!-- 优惠券列表 -->
<a-card
v-for="coupon in availableCoupons"
:key="coupon.id"
class="modal-coupon-card"
:class="{ active: selectedCoupon && selectedCoupon.id === coupon.id }"
@click="selectedCoupon = coupon"
>
<div class="coupon-content">
<div class="coupon-value">
{{ coupon.couponType === 1 ? `${coupon.discountValue}折` : `¥${coupon.reduceAmount}` }}
</div>
<div class="coupon-info">
<div class="coupon-name">{{ coupon.couponName }}</div>
<div class="coupon-condition" v-if="coupon.couponType === 2">
满{{ coupon.minAmount }}元可用
</div>
<div class="coupon-time">
{{ coupon.startTime }} 至 {{ coupon.endTime }}
</div>
<div class="coupon-select" v-if="selectedCoupon && selectedCoupon.id === coupon.id">
<CheckCircleOutlined />
</div>
</div>
</div>
</a-card>
</div>
</div>
</a-modal>
<!-- 美甲师选择弹窗 -->
<a-modal
v-model:visible="showArtistModal"
title="选择美甲师"
width="90%"
@ok="selectArtistAndCheckout"
@cancel="closeArtistModal"
>
<div class="artist-modal-content">
<a-empty v-if="availableArtists.length === 0" description="暂无可用美甲师" />
<div v-else class="artist-list">
<a-radio-group v-model:value="selectedArtist" name="artist">
<a-radio
v-for="artist in availableArtists"
:key="artist.id"
:value="artist"
class="artist-item"
>
<div class="artist-info">
<span class="artist-name">{{ artist.name }}</span>
</div>
</a-radio>
</a-radio-group>
</div>
</div>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch, inject } from 'vue'
import { useRouter } from 'vue-router'
import {
LeftOutlined,
DeleteOutlined,
RightOutlined,
CheckCircleOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { cartApi } from '../api/cart'
import { orderApi } from '../api/order'
import { fileApi } from '../api/index'
import { couponApi, type UserCoupon } from '../api/coupon'
import { userApi } from '../api/user'
// 注入更新购物车数量的方法
const updateCartCount = inject<() => Promise<void>>('updateCartCount', async () => {})
interface CartItem {
id: number
productId: number
productTitle: string
productImage: string
price: number
quantity: number
totalPrice: number
tags: string
selected: boolean
}
const router = useRouter()
// 购物车商品数据
const cartItems = ref<CartItem[]>([])
// 图片缓存
const imageIdCache = ref<Record<string, string>>({})
// 优惠券相关状态
const availableCoupons = ref<UserCoupon[]>([])
const selectedCoupon = ref<UserCoupon | null>(null)
const showCouponModal = ref(false)
// 加载购物车数据
const loadCartItems = async () => {
try {
const data = await cartApi.getCartList()
cartItems.value = data.map((item: any) => ({
...item,
selected: true
}))
// 加载商品图片的临时加签链接
await loadProductImages(cartItems.value)
// 加载可用优惠券
await loadAvailableCoupons()
} catch (error) {
message.error('获取购物车数据失败')
}
}
// 加载商品图片
const loadProductImages = async (items: CartItem[]) => {
for (const item of items) {
if (item.productImage) {
// 过滤掉HTML标签
const cleanImageUrl = item.productImage.replace(/<[^>]*>/g, '')
// 从cleanImageUrl中提取图片ID
// 假设图片URL的格式为 '/api/file/get/123'
const match = cleanImageUrl.match(/\/api\/file\/get\/(\d+)/)
if (match && match[1]) {
const imageId = match[1]
try {
// 检查缓存
if (!imageIdCache.value[imageId]) {
const signedUrl = await fileApi.getSignedUrl(Number(imageId))
imageIdCache.value[imageId] = signedUrl
}
// 更新商品图片为临时加签链接
item.productImage = imageIdCache.value[imageId]
} catch (error) {
console.error('获取图片签名链接失败:', error)
// 如果获取签名链接失败,清除无效的图片URL
item.productImage = ''
}
} else {
// 如果不是有效的图片URL格式,清除无效的图片URL
item.productImage = ''
}
}
}
}
// 加载可用优惠券
const loadAvailableCoupons = async () => {
try {
// 计算商品总价
const totalPrice = subtotal.value
// 收集商品标签
const productTagsSet = new Set<string>()
cartItems.value
.filter(item => item.selected)
.forEach(item => {
if (item.tags) {
const tags = item.tags.split(',').map(tag => tag.trim())
tags.forEach(tag => {
if (tag) productTagsSet.add(tag)
})
}
})
const productTags = Array.from(productTagsSet).join(',')
if (totalPrice > 0) {
const coupons = await couponApi.getAvailableCoupons(productTags, totalPrice)
availableCoupons.value = coupons
} else {
availableCoupons.value = []
}
} catch (error) {
console.error('获取可用优惠券失败:', error)
availableCoupons.value = []
}
}
// 计算选中的商品数量
const selectedCount = computed(() => {
return cartItems.value.filter(item => item.selected).length
})
// 计算商品总数量
const totalQuantity = computed(() => {
return cartItems.value.reduce((sum, item) => sum + item.quantity, 0)
})
// 计算小计
const subtotal = computed(() => {
return cartItems.value
.filter(item => item.selected)
.reduce((sum, item) => sum + item.totalPrice, 0)
})
// 计算优惠金额
const discountAmount = computed(() => {
if (!selectedCoupon.value) return 0
const total = subtotal.value
const coupon = selectedCoupon.value
if (coupon.couponType === 1) {
// 折扣券
return total - (total * parseFloat(coupon.discountValue) / 10)
} else if (coupon.couponType === 2) {
// 满减券
return parseFloat(coupon.reduceAmount)
}
return 0
})
// 计算总金额
const totalAmount = computed(() => {
return Math.max(0, subtotal.value - discountAmount.value)
})
// 生成随机颜色
const getRandomColor = () => {
const colors = ['#ffe4d6', '#d6eaff', '#e2ffd6', '#fff2d6', '#d6ffe4', '#e4d6ff']
return colors[Math.floor(Math.random() * colors.length)]
}
// 处理返回按钮点击
const handleBackClick = () => {
router.back()
}
// 处理编辑按钮点击
const handleEditClick = () => {
console.log('编辑按钮被点击')
}
// 处理选择状态变化
const handleSelectChange = async () => {
console.log('选择状态改变')
// 重新加载可用优惠券
await loadAvailableCoupons()
}
// 处理减少数量
const handleDecreaseQuantity = async (item: CartItem) => {
if (item.quantity > 1) {
item.quantity--
try {
await cartApi.updateCartQuantity({ productId: item.productId, quantity: item.quantity })
// 重新加载可用优惠券
await loadAvailableCoupons()
// 更新购物车数量
await updateCartCount()
} catch (error) {
message.error('更新数量失败')
item.quantity++
}
}
}
// 处理增加数量
const handleIncreaseQuantity = async (item: CartItem) => {
if (item.quantity < 99) {
item.quantity++
try {
await cartApi.updateCartQuantity({ productId: item.productId, quantity: item.quantity })
// 重新加载可用优惠券
await loadAvailableCoupons()
// 更新购物车数量
await updateCartCount()
} catch (error) {
message.error('更新数量失败')
item.quantity--
}
}
}
// 处理删除商品
const handleDeleteItem = async (item: CartItem) => {
try {
await cartApi.removeFromCart(item.productId)
const index = cartItems.value.findIndex(i => i.id === item.id)
if (index > -1) {
cartItems.value.splice(index, 1)
message.success('商品已删除')
// 重新加载可用优惠券
await loadAvailableCoupons()
// 更新购物车数量
await updateCartCount()
}
} catch (error) {
message.error('删除商品失败')
}
}
// 处理浏览商品
const handleBrowseProducts = () => {
router.push('/products')
}
// 确认优惠券选择
const confirmCouponSelection = () => {
showCouponModal.value = false
}
// 取消优惠券选择
const cancelCouponSelection = () => {
showCouponModal.value = false
}
// 美甲师选择相关状态
const showArtistModal = ref(false)
const selectedArtist = ref<{id: number, name: string} | null>(null)
const availableArtists = ref<{id: number, name: string}[]>([])
// 加载可用美甲师
const loadAvailableArtists = async () => {
try {
// 获取美甲师列表(用户类型为3)
const artists = await userApi.listUsersByType(3)
availableArtists.value = artists.map(artist => ({
id: artist.id,
name: artist.nickname
}))
} catch (error) {
console.error('获取美甲师列表失败:', error)
availableArtists.value = []
}
}
// 处理结算
const handleCheckout = async () => {
const selectedItems = cartItems.value.filter(item => item.selected)
if (selectedItems.length === 0) {
message.warning('请先选择要结算的商品')
return
}
// 加载可用美甲师
await loadAvailableArtists()
// 显示美甲师选择弹窗
showArtistModal.value = true
}
// 选择美甲师并创建订单
const selectArtistAndCheckout = async () => {
if (!selectedArtist.value) {
message.warning('请选择美甲师')
return
}
try {
const order = await orderApi.createOrder({
couponId: selectedCoupon.value ? selectedCoupon.value.id : undefined,
artistId: selectedArtist.value.id
})
message.success('订单创建成功')
showArtistModal.value = false
// 更新购物车数量(因为订单创建后购物车会被清空)
await updateCartCount()
router.push('/profile')
} catch (error) {
message.error('创建订单失败')
}
}
// 关闭美甲师选择弹窗
const closeArtistModal = () => {
showArtistModal.value = false
selectedArtist.value = null
}
// 监听选中商品变化,重新加载可用优惠券
watch(
() => cartItems.value.map(item => ({ id: item.id, selected: item.selected, quantity: item.quantity })),
async () => {
await loadAvailableCoupons()
},
{ deep: true }
)
// 页面加载时获取购物车数据
onMounted(() => {
loadCartItems()
})
</script>
<style scoped>
.mobile-container {
padding-top: 60px;
min-height: 100vh;
background: #f5f5f5;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 100;
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
border-bottom: 1px solid #f0f0f0;
background: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
.header h1 {
font-size: 18px;
font-weight: bold;
margin: 0;
}
.back-btn,
.edit-btn {
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.cart-items {
padding: 15px;
padding-bottom: 20px;
}
.cart-item {
margin-bottom: 12px;
border-radius: 12px;
overflow: hidden;
}
.cart-item :deep(.ant-card-body) {
padding: 16px;
}
.item-content {
display: flex;
gap: 12px;
align-items: flex-start;
}
.item-image {
width: 80px;
height: 80px;
border-radius: 8px;
display: flex;
justify-content: center;
align-items: center;
font-size: 30px;
font-weight: bold;
color: rgba(0,0,0,0.1);
flex-shrink: 0;
overflow: hidden;
}
.item-image img {
width: 100%;
height: 100%;
object-fit: cover;
}
.item-details {
flex: 1;
display: flex;
flex-direction: column;
min-height: 80px;
}
.item-name {
font-size: 15px;
font-weight: 600;
margin: 0 0 4px 0;
line-height: 1.4;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.item-price {
color: #ff4d4f;
font-weight: bold;
margin: 0;
font-size: 16px;
}
.item-duration {
color: #666;
font-size: 13px;
margin: 4px 0 0 0;
}
.item-actions {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 8px;
}
.quantity-control {
display: flex;
align-items: center;
gap: 8px;
}
.quantity-value {
min-width: 30px;
text-align: center;
font-weight: 600;
font-size: 16px;
}
.summary {
margin: 0 15px 15px;
padding: 16px;
background: #fafafa;
border-radius: 12px;
}
.summary-row {
display: flex;
justify-content: space-between;
padding: 8px 0;
font-size: 14px;
color: #666;
}
.summary-row.total {
font-size: 16px;
font-weight: bold;
color: #333;
border-top: 1px solid #e8e8e8;
padding-top: 12px;
margin-top: 4px;
}
.total-price {
color: #ff4d4f;
font-size: 20px;
}
.duration {
color: #667eea;
font-weight: 600;
}
.checkout-section {
position: fixed;
bottom: 60px;
left: 0;
right: 0;
padding: 15px;
background: white;
border-top: 1px solid #f0f0f0;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.06);
}
.checkout-section :deep(.ant-btn-lg) {
height: 48px;
border-radius: 24px;
font-weight: 600;
font-size: 16px;
}
/* 优惠券样式 */
.coupon-section {
margin: 0 15px 15px;
}
.coupon-card {
border-radius: 12px;
overflow: hidden;
}
.coupon-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px;
cursor: pointer;
}
.coupon-header:hover {
background-color: #f5f5f5;
}
.coupon-title {
font-size: 15px;
font-weight: 600;
color: #333;
}
.coupon-value {
font-size: 14px;
color: #1890ff;
display: flex;
align-items: center;
gap: 4px;
}
.coupon-discount {
padding: 12px 16px;
background-color: #f0f9ff;
border-top: 1px solid #e6f7ff;
display: flex;
justify-content: space-between;
align-items: center;
}
.discount-label {
font-size: 14px;
color: #333;
}
.discount-amount {
font-size: 16px;
font-weight: 600;
color: #1890ff;
}
.discount {
color: #1890ff;
font-weight: 600;
}
/* 优惠券弹窗样式 */
.coupon-modal-content {
max-height: 400px;
overflow-y: auto;
}
.coupon-list {
padding: 8px 0;
}
.modal-coupon-card {
margin-bottom: 12px;
border-radius: 12px;
overflow: hidden;
cursor: pointer;
transition: all 0.3s;
}
.modal-coupon-card:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
.modal-coupon-card.active {
border: 2px solid #1890ff;
}
.coupon-content {
display: flex;
align-items: center;
padding: 16px;
gap: 16px;
}
.coupon-value {
font-size: 24px;
font-weight: 600;
color: #ff4d4f;
flex-shrink: 0;
}
.coupon-info {
flex: 1;
min-width: 0;
}
.coupon-name {
font-size: 15px;
font-weight: 600;
color: #333;
margin-bottom: 4px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.coupon-condition {
font-size: 13px;
color: #666;
margin-bottom: 4px;
}
.coupon-time {
font-size: 12px;
color: #999;
}
.coupon-select {
color: #1890ff;
font-size: 20px;
flex-shrink: 0;
}
/* 美甲师选择弹窗样式 */
.artist-modal-content {
max-height: 400px;
overflow-y: auto;
}
.artist-list {
padding: 8px 0;
}
.artist-item {
display: block;
width: 100%;
padding: 12px 0;
border-bottom: 1px solid #f0f0f0;
}
.artist-item:last-child {
border-bottom: none;
}
.artist-info {
display: flex;
align-items: center;
gap: 12px;
}
.artist-name {
font-size: 15px;
font-weight: 600;
color: #333;
}
</style>