import { Card, Col, Flex, Row, Typography, Image, Tag, Button, message } from "antd"
import { useEffect, useState } from "react";
import { myAPI } from "../axios";
import { DeleteOutlined, MinusCircleOutlined, PlusCircleOutlined } from "@ant-design/icons";
import Decimal from 'decimal.js';
const { Title, Text } = Typography;
const [messageApi, contextHolder] = message.useMessage();
const [products, setProducts] = useState<Product[]>([]);
const [cart, setCart] = useState<
myAPI.get('products.json')
const newProducts = response.data.products as Product[];
newProducts.forEach(product => {
product.realPrice = new Decimal(product.price).minus(product.discount).toDecimalPlaces(2).toNumber();
setProducts(newProducts);
let sum = new Decimal(0);
const product = products.find(product => product.id === item.id);
sum = sum.plus(new Decimal(product.realPrice).times(item.quantity));
return sum.toDecimalPlaces(2).toNumber();
const updateCart = (id: number, quantity: number) => {
const product = products.find(product => product.id === id);
if (!product || product.stock < quantity) {
newCart.forEach(item => {
item.quantity += quantity;
if (item.quantity <= 0) {
newCart = newCart.filter(item => item.id !== id);
if (!found && quantity > 0) {
newCart.push({ id, quantity });
const updateProducts = [...products];
updateProducts.forEach(product => {
product.stock -= quantity;
setProducts(updateProducts);
<Title level={3} style={{ marginTop: 0 }}>水果商城 🍎</Title>
{products.map(product => (
<Title level={5} style={{ marginTop: -10 }}>
<Tag color="cyan">#{product.id}</Tag>
<Text delete={product.discount > 0}>单价:${product.price}</Text>
{product.discount > 0 && <Text mark>折后价:${product.realPrice}</Text>}
<Text type="secondary">库存:{product.stock}</Text>
<Button style={{ marginTop: 10 }} onClick={() => updateCart(product.id, 1)} disabled={product.stock <= 0}>加入购物车</Button>
<Card key={item.id} size="small" style={{ marginBottom: 10 }}>
<DeleteOutlined style={{ marginRight: 10, color: 'red' }} onClick={() => updateCart(item.id, -item.quantity)} />
{products.find(product => product.id === item.id)?.name} - ${products.find(product => product.id === item.id)?.realPrice} |
数量:<MinusCircleOutlined onClick={() => updateCart(item.id, -1)} /> {item.quantity} <PlusCircleOutlined onClick={() => updateCart(item.id, +1)} />
<Title level={5}>总价:${total()}</Title>
<Button type="primary" onClick={() => { messageApi.success('已结算'); setCart([]) }}>结算</Button>