tosanoob's picture
update a lot
0d37b12
import BasicTemplate from "../../templates/BasicTemplate";
import { Container, Row, Col, Card, Button, Modal, Form } from "react-bootstrap";
import { useState, useEffect } from "react";
import CacheStorage from "../../organisms/CacheStorage";
import DataStorage from "../../organisms/DataStorage";
import axios from "axios";
export default function CartPage() {
const [cartItems, setCartItems] = useState([]);
const [show, setShow] = useState(false);
const [branches, setBranches] = useState([]);
const defaultSelectedStore = CacheStorage.get('selectedStore') || "";
const [selectedStore, setSelectedStore] = useState(defaultSelectedStore);
const [loadingBranches, setLoadingBranches] = useState(true);
const [address, setAddress] = useState('');
// const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchBranches = async () => {
try {
const response = await axios.get(process.env.REACT_APP_API_URL + '/branchs'); // Thay 'API_ENDPOINT' bằng URL của API
setBranches(response.data); // Lưu dữ liệu vào state
setLoadingBranches(false); // Đặt loading thành false khi hoàn tất
CacheStorage.set('stores', JSON.stringify(Object(response.data)));
} catch (error) {
console.error('Error fetching branches:', error);
setLoadingBranches(false); // Đặt loading thành false nếu lỗi
}
};
if (CacheStorage.get('stores')) {
setBranches(JSON.parse(CacheStorage.get('stores')));
setLoadingBranches(false);
} else {
fetchBranches();
}
}, [])
const handleSelectStore = (e) => {
setSelectedStore(e.target.value);
CacheStorage.set('selectedStore', e.target.value);
// setLoading(true);
};
let selectboxContent;
if (loadingBranches) {
selectboxContent = (<p>Đang tải dữ liệu...</p>)
} else {
selectboxContent = (<Form>
<Form.Group controlId="branchSelect">
<Form.Label>Chọn chi nhánh:</Form.Label>
<Form.Control as="select" onChange={handleSelectStore} value={selectedStore}>
<option value="">-- Chọn chi nhánh --</option>
{branches.map((store) => (
<option key={store.id} value={store.id}>
{store.name + ' - ' + store.location}
</option>
))}
</Form.Control>
</Form.Group>
</Form>);
}
useEffect(() => {
// Lấy giỏ hàng từ sessionStorage
const cart = JSON.parse(DataStorage.get('cart')) || {};
// Chuyển cart thành mảng chứa các món có số lượng > 0
const items = Object.entries(cart).map(([id, item]) => ({
id: id,
name: item.name,
amount: item.amount,
imageSrc: item.imageSrc,
price: item.price
}));
console.log(items);
setCartItems(items);
}, []);
const handleShow = () => {
setShow(true);
}
const handleClose = () => {
setShow(false);
}
const handleSubmit = () => {
// tạo order, gửi order && gửi lấy urlpayment
if (selectedStore === '') {
setShow(false);
} else {
// try {
// let orderData;
// orderData.order_type = 2;
// orderData.order_items = cartItems.map((item) => { return { menu_id: item.id, quantity: item.amount } })
// const orderResponse = axios.post(process.env.REACT_APP_API_URL + `/branches/${selectedStore}/orders`, {
// headers: {
// Authorization: `Bearer ${DataStorage.get('accessToken')}`,
// },
// })
// let paymentData;
// paymentData.orderType='other';
// paymentData.orderDescription=''
// } catch (error) {
// console.log('error');
// }
setShow(false);
}
}
return (
<BasicTemplate content={
(
<Container className="d-flex align-items-center justify-content-center my-5" style={{ minHeight: '70vh' }}>
<Modal show={show} onHide={handleClose} className="text-center">
<Modal.Header closeButton className="text-center">
<Modal.Title >Xác nhận thanh toán</Modal.Title>
</Modal.Header>
<Modal.Body>
{
(selectedStore !== '' && address !== '' ?
`Bạn sắp thanh toán ${Object.values(cartItems).reduce((total, item) => { return total + item.price * item.amount; }, 0)} VND qua VNPAY.
Vui lòng xác nhận để chuyển tiếp đến trang thanh toán.` : `Hãy đảm bảo bạn chọn địa điểm giao hàng, và chi nhánh đặt món`
)
}
</Modal.Body>
<Modal.Footer>
<Button variant="primary" onClick={handleSubmit}>
Xác nhận
</Button>
<Button variant='outline-primary' onClick={handleClose}>
Quay lại
</Button>
</Modal.Footer>
</Modal>
{cartItems.length > 0 ? (
<Container fluid className="d-flex text-center align-items-center justify-content-center">
<Row style={{ maxWidth: "90vw" }} className="justify-content-center">
<Col xs="12" md="8" lg="8" className="my-5 text-center">
{selectboxContent}
</Col>
<Col xs="12" md="8" className="my-5 text-center">
<Form>
<Form.Group>
<Form.Label>Chọn địa chỉ giao hàng</Form.Label>
<Form.Control
type="text"
name="address"
placeholder='Địa chỉ giao hàng'
value={address || ''}
onChange={(e) => setAddress(e.target.value)}
/>
</Form.Group>
</Form>
</Col>
<Col xs="12" className="text-center">
<h2 className="text-center mb-4">Giỏ hàng của bạn</h2>
</Col>
{cartItems.map((item, idx) => (
<Col xs="12" md="8" lg="8" key={idx} className="m-3 text-center">
<Card className="shadow-sm" style={{ display: 'flex', flexDirection: 'row' }}>
<Card.Img
variant="left"
src={item.imageSrc}
style={{ width: '150px', objectFit: 'cover' }}
/>
<Card.Body>
<Row xs={4} className="text-center" style={{ height: '100px' }}>
<Col className="d-flex align-items-center justify-content-center">
<Card.Title>{item.name}</Card.Title>
</Col>
<Col className="d-flex align-items-center justify-content-center">
<Card.Text>Đơn giá: {item.price} VND</Card.Text>
</Col>
<Col className="d-flex align-items-center justify-content-center">
<Card.Text>Số lượng: {item.amount}</Card.Text>
</Col>
<Col className="d-flex align-items-center justify-content-center">
<Card.Text>Tổng cộng: {item.price * item.amount} VND</Card.Text>
</Col>
</Row>
</Card.Body>
</Card>
</Col>
))}
<Col xs="12" className="text-center">
<Button className="m-3" onClick={handleShow}>
Thanh toán
</Button>
<Button as="a" href="/menu" variant="outline-primary" className="m-3">
Xem menu
</Button>
</Col>
</Row>
</Container>
) : (
<div className="text-center">
<p className="text-center my-3">Giỏ hàng của bạn hiện đang trống.</p>
<Button as='a' href='/menu'>Xem menu</Button>
</div>
)}
</Container>
)
} />
)
}