80 lines
2.0 KiB
TypeScript
80 lines
2.0 KiB
TypeScript
"use client";
|
|
|
|
import { LocationContext } from "@/components/locationContext";
|
|
import { useContext, useState } from "react";
|
|
import Grouping from "./Grouping";
|
|
import { Group, JobCategory, updateGroups } from "./action";
|
|
|
|
type Props = {
|
|
allJobs: JobCategory[];
|
|
};
|
|
|
|
export default function GroupCreator({ allJobs }: Props) {
|
|
const locationContext = useContext(LocationContext);
|
|
const [usedJobs, setUsedJobs] = useState<number[]>([]);
|
|
const [groups, setGroup] = useState<Group[]>(
|
|
[...Array(4).keys()].map((i) => ({ id: i + 1, jobs: [] })),
|
|
);
|
|
function useJob(id: number) {
|
|
setUsedJobs((u) => [...u, id]);
|
|
}
|
|
|
|
function freeJob(id: number) {
|
|
setUsedJobs((u) => u.filter((j) => j != id));
|
|
}
|
|
|
|
function updateGroup(id: number, jobs: number[]) {
|
|
setGroup((groups) =>
|
|
groups.map((g) => {
|
|
if (g.id != id) return g;
|
|
else return { id, jobs };
|
|
}),
|
|
);
|
|
}
|
|
|
|
async function submit() {
|
|
if (
|
|
locationContext?.zone[0] == undefined ||
|
|
locationContext?.province[0] == undefined
|
|
) {
|
|
alert("ยังไม่ได้เลือกพื้นที่");
|
|
return;
|
|
}
|
|
await updateGroups(
|
|
locationContext.province[0],
|
|
locationContext.zone[0],
|
|
groups,
|
|
);
|
|
|
|
alert("อัพเดทสำเร็จ");
|
|
}
|
|
|
|
if (
|
|
locationContext?.zone[0] == undefined ||
|
|
locationContext?.province[0] == undefined
|
|
) {
|
|
return undefined;
|
|
}
|
|
return (
|
|
<div>
|
|
{groups.map((g) => (
|
|
<div className="flex flex-col items-center" key={g.id}>
|
|
<p>สายที่: {g.id}</p>
|
|
<Grouping
|
|
availableJobs={allJobs.filter((j) => !usedJobs.includes(j.id))}
|
|
selectJob={useJob}
|
|
removeJob={freeJob}
|
|
updateGroup={(ids) => updateGroup(g.id, ids)}
|
|
/>
|
|
</div>
|
|
))}
|
|
|
|
<div className="flex justify-center">
|
|
<button className="rounded-md bg-green-300 p-2" onClick={submit}>
|
|
ยืนยัน
|
|
</button>
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|