"use client";
import React, { useState, useEffect, useRef } from "react";
import {
DataTable,
Column,
Toast,
Button,
Toolbar,
Dialog,
Dropdown,
Calendar,
InputText,
Checkbox,
} from "primereact";
import axios from "axios";
import { FixedSizeList as List } from "react-window";
import "primereact/resources/themes/saga-blue/[Link]";
import "primereact/resources/[Link]";
import "primeicons/[Link]";
import {InputNumber} from "primereact/inputnumber";
const DeliveryOrderTable = () => {
const emptyDeliveryOrder = {
id: null,
orderNumber: "",
customerId: null,
scheduleId: null,
orderDate: null,
deliveryDate: null,
totalAmount: 0,
status: "",
notes: "",
shipScheduleContainerMap: {},
};
const [state, setState] = useState({
selectedDeliveryOrder: null,
deliveryOrders: [],
customers: [],
schedules: [],
containers: [],
shipSchedules: [],
deliveryOrderDialog: false,
deleteDeliveryOrderDialog: false,
deliveryOrder: emptyDeliveryOrder,
selectedDeliveryOrders: [],
submitted: false,
globalFilter: null,
page: 0, // Added for pagination
});
const toast = useRef(null);
const dt = useRef(null);
useEffect(() => {
fetchData();
}, []);
const getAuthConfig = () => ({
headers: {
Authorization: `Bearer ${[Link]("jwtToken")}`,
},
});
const fetchData = () => {
axios
.get(`[Link]
.then((response) => setState((prev) => ({ ...prev, deliveryOrders:
[Link] })));
axios
.get(`[Link]
.then((response) => setState((prev) => ({ ...prev, customers:
[Link] })));
axios
.get(`[Link]
.then((response) => setState((prev) => ({ ...prev, schedules:
[Link] })));
fetchContainers(); // Initial fetch for containers
};
const fetchContainers = () => {
axios
.get(`[Link] getAuthConfig())
.then((response) => {
setState((prev) => ({
...prev,
containers: [Link], // Load all containers at once
}));
});
};
const fetchShipSchedulesByScheduleId = (scheduleId) => {
axios
.get(`[Link]
{scheduleId}`)
.then((response) => {
const newShipScheduleContainerMap = [Link](
(map, shipSchedule) => ({ ...map, [[Link]]: [] }),
{}
);
setState((prev) => ({
...prev,
shipSchedules: [Link],
deliveryOrder: { ...[Link],
shipScheduleContainerMap: newShipScheduleContainerMap },
}));
});
};
const updateState = (updates) => setState((prev) => ({ ...prev, ...updates }));
const saveDeliveryOrder = () => {
if ([Link] && [Link]) {
const saveRequest = [Link]
? [Link](`[Link]
{[Link]}`, [Link])
: [Link](`[Link]
[Link]);
[Link]((response) => {
fetchData();
updateState({ deliveryOrderDialog: false, deliveryOrder:
emptyDeliveryOrder, shipSchedules: [], containers: [] });
[Link]({
severity: "success",
summary: "Successful",
detail: [Link] ? "Lệnh giao hàng đã được cập
nhật" : "Lệnh giao hàng đã được tạo",
life: 3000,
});
});
}
};
const deleteDeliveryOrder = () => {
[Link](`[Link]
{[Link]}`).then(() => {
updateState({
deliveryOrders: [Link]((val) => [Link] !==
[Link]),
deleteDeliveryOrderDialog: false,
deliveryOrder: emptyDeliveryOrder,
shipSchedules: [],
containers: [],
});
[Link]({
severity: "success",
summary: "Successful",
detail: "Xóa lệnh giao hàng thành công",
life: 3000,
});
});
};
const onInputChange = (e, name) => {
const val = ([Link] && [Link]) || "";
updateState({
deliveryOrder: { ...[Link], [name]: val },
});
};
const onDropdownChange = (e, name) => {
updateState({
deliveryOrder: { ...[Link], [name]: [Link] },
});
if (name === "scheduleId") fetchShipSchedulesByScheduleId([Link]);
};
const onContainerCheckboxChange = (e, shipScheduleId, containerCode) => {
if (![Link] || !
[Link]([Link]).flat().includes(contain
erCode)) {
const newMap = { ...[Link] };
newMap[shipScheduleId] = [Link]
? [...newMap[shipScheduleId], containerCode]
: newMap[shipScheduleId].filter((code) => code !== containerCode);
updateState({ deliveryOrder: { ...[Link],
shipScheduleContainerMap: newMap } });
} else {
[Link]({
severity: "warn",
summary: "Trùng container",
detail: "Container đã ở trong một lịch tàu khác",
life: 3000,
});
}
};
const renderContainerAssignment = () => {
return [Link]((shipSchedule) => (
<div className="field" key={[Link]}>
<label htmlFor={`container_${[Link]}`}>Containers for
ShipSchedule {[Link]}</label>
<List
height={150} // Adjust the height as necessary
itemCount={[Link]}
itemSize={35} // Adjust the size of each item as necessary
width={"100%"}
>
{({ index, style }) => (
<div style={style}
key={[Link][index].containerCode}>
<Checkbox
inputId={`container_$
{[Link][index].containerCode}`}
checked={[Link][[Link]]?.includes(st
[Link][index].containerCode)}
onChange={(e) => onContainerCheckboxChange(e,
[Link], [Link][index].containerCode)}
/>
<label htmlFor={`container_$
{[Link][index].containerCode}`}>{[Link][index].containerCode}</
label>
</div>
)}
</List>
</div>
));
};
const renderContainers = (rowData) => {
// Extract containers from shipScheduleContainerMap
const containers = [Link]([Link]).flat();
// Join all container codes into a single string or format them as you
prefer
return [Link](', ');
};
return (
<div>
<Toast ref={toast} />
<div className="card">
<Toolbar
className="mb-4"
left={() => (
<Button
label="Thêm"
icon="pi pi-plus"
onClick={() => updateState({
deliveryOrderDialog: true,
deliveryOrder: emptyDeliveryOrder, // Reset to
empty form
shipSchedules: [], // Reset shipSchedules
containers: [] // Reset containers
})}
/>
)}
right={() => <Button label="Xuất Excel" icon="pi pi-upload"
onClick={() => [Link]()} />}
/>
<DataTable
ref={dt}
value={[Link]}
selection={[Link]}
onSelectionChange={(e) => updateState({ selectedDeliveryOrders:
[Link] })}
dataKey="id"
paginator
rows={10}
globalFilter={[Link]}
header={<div className="flex align-items-center justify-
content-between"><h4 className="m-0">Quản lý lệnh giao hàng</h4><InputText
type="search" onInput={(e) => updateState({ globalFilter: [Link] })}
placeholder="Tìm kiếm..." /></div>}
>
<Column selectionMode="multiple" exportable={false}></Column>
<Column field="orderNumber" header="Mã đơn hàng"
sortable></Column>
<Column field="customerId" header="Tên khách hàng"
body={(rowData) => [Link]((c) => [Link] ===
[Link])?.username || "unknown"} sortable></Column>
<Column field="scheduleId" header="Mã lịch trình"
body={(rowData) => [Link]((s) => [Link] ===
[Link])?.codeSchedule || "unknown"} sortable></Column>
<Column header="Ngày đặt hàng" body={(rowData) => new
Date([Link]).toLocaleString()} sortable></Column>
<Column header="Ngày giao hàng" body={(rowData) => new
Date([Link]).toLocaleString()} sortable></Column>
<Column field="totalAmount" header="Tổng tiền"
sortable></Column>
<Column field="status" header="Trạng thái" sortable></Column>
<Column header="Containers" body={renderContainers} />
<Column body={(rowData) =>
<>
<Button
icon="pi pi-pencil"
className="p-button-rounded p-button-success mr-2"
onClick={() => {
// Set the selected order data, including
containers, to the state
updateState({
deliveryOrder: { ...rowData }, // Copy all
fields from the selected row
deliveryOrderDialog: true, // Open the
dialog
shipSchedules:
[Link]([Link]).map((id) => ({
id: parseInt(id),
containers:
[Link][id],
})), // Set the ship schedules for
rendering containers
});
}}
/>
<Button
icon="pi pi-trash"
className="p-button-rounded p-button-warning"
onClick={() => updateState({
deliveryOrder: rowData,
deleteDeliveryOrderDialog: true,
})}
/>
</>
} exportable={false}>
</Column>
</DataTable>
</div>
<Dialog visible={[Link]} style={{ width: "450px" }}
header="Chi tiết lệnh giao hàng" modal className="p-fluid" footer={<><Button
label="Cancel" icon="pi pi-times" outlined onClick={() =>
updateState({ deliveryOrderDialog: false, submitted: false })} /><Button
label="Save" icon="pi pi-check" onClick={saveDeliveryOrder} /></>} onHide={() =>
updateState({ deliveryOrderDialog: false, submitted: false })}>
<div className="field">
<label htmlFor="orderNumber">Mã lệnh giao hàng</label>
<InputText id="orderNumber"
value={[Link]} onChange={(e) => onInputChange(e,
"orderNumber")} />
</div>
<div className="field">
<label htmlFor="customer">Khách hàng</label>
<Dropdown id="customer" value={[Link]((customer)
=> [Link] === [Link])} options={[Link]}
onChange={(e) => onDropdownChange(e, "customerId")} optionLabel="name"
placeholder="Chọn khách hàng" />
</div>
<div className="field">
<label htmlFor="schedule">Lịch trình</label>
<Dropdown id="schedule" value={[Link]((schedule)
=> [Link] === [Link]) || null}
options={[Link]} onChange={(e) => onDropdownChange(e, "scheduleId")}
optionLabel="codeSchedule" placeholder="Chọn lịch trình" />
</div>
<div className="field">
<label htmlFor="orderDate">Ngày đặt hàng</label>
<Calendar id="orderDate" value={[Link] ?
new Date([Link]) : null} onChange={(e) => onInputChange(e,
"orderDate")} showTime showSeconds />
</div>
<div className="field">
<label htmlFor="deliveryDate">Ngày giao hàng</label>
<Calendar id="deliveryDate"
value={[Link] ? new
Date([Link]) : null} onChange={(e) => onInputChange(e,
"deliveryDate")} showTime showSeconds />
</div>
<div className="field">
<label htmlFor="totalAmount">Tổng tiền</label>
<InputText id="totalAmount"
value={[Link]} onChange={(e) => onInputChange(e,
"totalAmount")} />
</div>
<div className="field">
<label htmlFor="status">Trạng thái</label>
<InputText id="status" value={[Link]}
onChange={(e) => onInputChange(e, "status")} />
</div>
<div className="field">
<label htmlFor="notes">Ghi chú</label>
<InputText id="notes" value={[Link]}
onChange={(e) => onInputChange(e, "notes")} />
</div>
{renderContainerAssignment()}
</Dialog>
<Dialog visible={[Link]} style={{ width:
"450px" }} header="Xác nhận" modal footer={<><Button label="No" icon="pi pi-times"
outlined onClick={() => updateState({ deleteDeliveryOrderDialog: false })}
/><Button label="Yes" icon="pi pi-check" severity="danger"
onClick={deleteDeliveryOrder} /></>} onHide={() =>
updateState({ deleteDeliveryOrderDialog: false })}>
<div className="confirmation-content">
<i className="pi pi-exclamation-triangle mr-3"
style={{ fontSize: "2rem" }} />
{[Link] && <span>Bạn có chắc chắn muốn xóa lệnh
giao hàng <b>{[Link]}</b>?</span>}
</div>
</Dialog>
</div>
);
};
export default DeliveryOrderTable;