70 lines
2.2 KiB
TypeScript
70 lines
2.2 KiB
TypeScript
|
|
import { TypeCartItem } from '@/types/cart';
|
||
|
|
|
||
|
|
// data
|
||
|
|
import { productData } from '@/data/ListProduct';
|
||
|
|
|
||
|
|
export const addToCart = (productId: string | number) => {
|
||
|
|
// Lấy giỏ hàng hiện tại từ localStorage
|
||
|
|
const cart: TypeCartItem[] = JSON.parse(localStorage.getItem('cart') || '[]');
|
||
|
|
|
||
|
|
console.log('chay tiếp');
|
||
|
|
|
||
|
|
const product = productData.find((p) => p.productId == productId);
|
||
|
|
if (!product) return;
|
||
|
|
|
||
|
|
// Kiểm tra sản phẩm đã có trong giỏ chưa
|
||
|
|
const existing = cart.find((item) => item.item_info.id == productId);
|
||
|
|
|
||
|
|
if (existing) {
|
||
|
|
// Nếu có rồi thì tăng số lượng
|
||
|
|
existing.in_cart.quantity = (parseInt(existing.in_cart.quantity) + 1).toString();
|
||
|
|
existing.in_cart.total_price =
|
||
|
|
Number(existing.in_cart.quantity) * Number(existing.in_cart.price);
|
||
|
|
} else {
|
||
|
|
// Nếu chưa có thì thêm mới
|
||
|
|
const cartItem = {
|
||
|
|
_id: `product-${product.id}-0`,
|
||
|
|
item_type: 'product',
|
||
|
|
item_id: `${product.id}-0`,
|
||
|
|
item_info: {
|
||
|
|
id: product.productId,
|
||
|
|
priceUnit: product.priceUnit,
|
||
|
|
marketPrice: product.marketPrice,
|
||
|
|
hasVAT: product.hasVAT,
|
||
|
|
weight: product.weight,
|
||
|
|
price: product.price,
|
||
|
|
currency: product.currency,
|
||
|
|
bulk_price: product.bulk_price,
|
||
|
|
configurable: product.configurable,
|
||
|
|
productName: product.productName,
|
||
|
|
productImage: product.productImage,
|
||
|
|
productUrl: product.productUrl,
|
||
|
|
brand: product.brand,
|
||
|
|
productSKU: product.productSKU,
|
||
|
|
quantity: product.quantity,
|
||
|
|
addon: product.addon,
|
||
|
|
warranty: product.warranty,
|
||
|
|
variants: product.variants,
|
||
|
|
variant_option: product.variant_option,
|
||
|
|
extend: product.extend,
|
||
|
|
categories: product.categories,
|
||
|
|
specialOffer: product.specialOffer,
|
||
|
|
specialOfferGroup: product.specialOfferGroup,
|
||
|
|
sale_rules: product.sale_rules,
|
||
|
|
},
|
||
|
|
in_cart: {
|
||
|
|
quantity: '1',
|
||
|
|
buyer_note: '',
|
||
|
|
price: product.price,
|
||
|
|
total_price: Number(product.quantity) * Number(product.price),
|
||
|
|
weight: '0',
|
||
|
|
total_weight: '0',
|
||
|
|
},
|
||
|
|
};
|
||
|
|
cart.push(cartItem);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Lưu lại vào localStorage
|
||
|
|
localStorage.setItem('cart', JSON.stringify(cart));
|
||
|
|
};
|