import { defineStore } from 'pinia' import { ref, computed } from 'vue' import type { CartItem } from '../types' export const useCartStore = defineStore('cart', () => { const items = ref([]) /** 已勾选的商品 */ const checkedItems = computed(() => items.value.filter((item) => item.checked)) /** 已勾选商品总金额 */ const totalAmount = computed(() => checkedItems.value.reduce((sum, item) => sum + item.specData.totalPrice * item.quantity, 0), ) /** 从后端拉取购物车列表并同步到本地 */ async function fetchCart() { try { const { getCartList } = await import('../api/cart') const list = await getCartList() items.value = list.map((item) => ({ ...item, checked: true })) } catch { // 未登录或网络异常,保留本地数据 } } /** 添加商品到购物车(本地优先,后台同步) */ function addToCart(item: CartItem) { items.value.push(item) // 异步同步到后端 import('../api/cart').then(({ addToCart: apiAdd }) => { apiAdd({ productId: item.productId, specDataId: item.specDataId, quantity: item.quantity, }).catch(() => { /* 静默处理 */ }) }).catch(() => { /* 静默处理 */ }) } /** 移除购物车项 */ function removeFromCart(id: number) { const index = items.value.findIndex((item) => item.id === id) if (index !== -1) { items.value.splice(index, 1) import('../api/cart').then(({ deleteCartItem }) => { deleteCartItem(id).catch(() => { /* 静默处理 */ }) }).catch(() => { /* 静默处理 */ }) } } /** 更新数量 */ function updateQuantity(id: number, quantity: number) { const item = items.value.find((item) => item.id === id) if (item) { item.quantity = quantity import('../api/cart').then(({ updateCartItem }) => { updateCartItem(id, { quantity }).catch(() => { /* 静默处理 */ }) }).catch(() => { /* 静默处理 */ }) } } /** 切换勾选状态(纯本地操作) */ function toggleCheck(id: number) { const item = items.value.find((item) => item.id === id) if (item) { item.checked = !item.checked } } /** 全选/取消全选(纯本地操作) */ function toggleCheckAll() { const allChecked = items.value.every((item) => item.checked) items.value.forEach((item) => { item.checked = !allChecked }) } return { items, checkedItems, totalAmount, fetchCart, addToCart, removeFromCart, updateQuantity, toggleCheck, toggleCheckAll, } })