cart.js
5.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import { ref, provide, inject, watchEffect } from 'vue'
import { useRouter } from 'vue-router'
// 导入接口
import { addOrderAPI } from "@/api/order";
const CartSymbol = Symbol()
// 购物车模式配置
const CartMode = {
SINGLE: 'single', // 单一商品模式
MULTIPLE: 'multiple' // 多商品模式
}
export function provideCart(mode = CartMode.MULTIPLE) {
const router = useRouter()
const cartItems = ref([])
const cartMode = ref(mode)
// 从localStorage加载购物车数据
try {
const storedCart = localStorage.getItem('cart')
if (storedCart) {
const cartData = JSON.parse(storedCart)
// 检查是否为新格式(包含时间戳)
if (cartData && typeof cartData === 'object' && cartData.timestamp) {
const currentTime = Date.now()
const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
// 检查缓存是否过期(超过一天)
if (currentTime - cartData.timestamp > oneDay) {
// 购物车缓存已过期,清空购物车
localStorage.removeItem('cart')
cartItems.value = []
} else {
// 缓存未过期,加载购物车数据
cartItems.value = cartData.items || []
}
} else {
// 兼容旧格式(直接是数组)
if (Array.isArray(cartData)) {
cartItems.value = cartData
} else {
// 格式不正确,清空缓存
localStorage.removeItem('cart')
cartItems.value = []
}
}
}
} catch (error) {
console.error('Failed to parse cart from localStorage:', error)
localStorage.removeItem('cart')
}
// 监听购物车变化并保存到localStorage
watchEffect(() => {
const cartData = {
items: cartItems.value,
timestamp: Date.now() // 添加时间戳
}
localStorage.setItem('cart', JSON.stringify(cartData))
})
// 添加商品到购物车
function addToCart(item) {
if (cartMode.value === CartMode.SINGLE) {
// 单一商品模式:直接替换现有商品
cartItems.value = [{ ...item, quantity: 1 }]
} else {
// 多商品模式:累加商品数量
const existingItemIndex = cartItems.value.findIndex(
i => i.id === item.id && i.type === item.type
)
if (existingItemIndex >= 0) {
const updatedItems = [...cartItems.value]
updatedItems[existingItemIndex] = {
...updatedItems[existingItemIndex],
quantity: updatedItems[existingItemIndex].quantity + 1
}
cartItems.value = updatedItems
} else {
cartItems.value = [...cartItems.value, { ...item, quantity: 1 }]
}
}
}
// 从购物车移除商品
function removeFromCart(itemId, itemType) {
cartItems.value = cartItems.value.filter(
item => !(item.id === itemId && item.type === itemType)
)
}
// 更新商品数量
function updateQuantity(itemId, itemType, quantity) {
if (quantity < 1) return
if (cartMode.value === CartMode.SINGLE) {
// 单一商品模式:直接更新数量
if (cartItems.value.length === 1) {
cartItems.value = [{ ...cartItems.value[0], quantity }]
}
} else {
// 多商品模式:更新指定商品数量
cartItems.value = cartItems.value.map(item =>
item.id === itemId && item.type === itemType
? { ...item, quantity }
: item
)
}
}
// 清空购物车
function clearCart() {
cartItems.value = []
}
// 获取购物车商品总数
function getItemCount() {
return cartItems.value.reduce((total, item) => total + item.quantity, 0)
}
// 计算购物车总价
function getTotalPrice() {
return cartItems.value.reduce(
(total, item) => total + ((item.price ?? 0) * (item.quantity ?? 0)),
0
)
}
// 跳转到结账页面
function proceedToCheckout() {
if (cartItems.value.length > 0) {
router.push('/checkout')
}
}
// 处理结账流程
function handleCheckout(userData) {
// 构建订单数据
const orderData = {
details: cartItems.value.map(item => ({
good_id: item.id,
type: item.type,
number: item.quantity,
price: item.price,
title: item.title
})),
total_price: getTotalPrice(),
...userData,
orderDate: new Date().toISOString()
}
return addOrderAPI(orderData).then(response => {
if (response.code === 1) {
return {
success: true,
orderId: response.data.id,
orderStatus: response.data.status,
orderData: orderData
}
}
return {
success: false,
message: response.msg || '订单提交失败'
}
})
}
const cart = {
items: cartItems,
mode: cartMode,
addToCart,
removeFromCart,
updateQuantity,
clearCart,
getItemCount,
getTotalPrice,
proceedToCheckout,
handleCheckout
}
provide(CartSymbol, cart)
return cart
}
export function useCart() {
const cart = inject(CartSymbol)
if (!cart) {
throw new Error('useCart() must be used within a component that has called provideCart()')
}
return cart
}