TTMT.ManageWebGUI/src/routes/_authenticated/command/index.tsx
2025-09-26 17:56:55 +07:00

74 lines
2.2 KiB
TypeScript

import { createFileRoute } from "@tanstack/react-router";
import { FormSubmitTemplate } from "@/template/form-submit-template";
import { ShellCommandForm } from "@/components/command-form";
import { useMutationData } from "@/hooks/useMutationData";
import { useQueryData } from "@/hooks/useQueryData";
import { BASE_URL, API_ENDPOINTS } from "@/config/api";
import { toast } from "sonner";
import type { Room } from "@/types/room";
type SendCommandRequest = { Command: string };
type SendCommandResponse = { status: string; message: string };
export const Route = createFileRoute("/_authenticated/command/")({
head: () => ({ meta: [{ title: "Gửi lệnh CMD" }] }),
component: CommandPage,
});
function CommandPage() {
// Lấy danh sách phòng từ API
const { data: roomData } = useQueryData({
queryKey: ["rooms"],
url: BASE_URL + API_ENDPOINTS.DEVICE_COMM.GET_ROOM_LIST,
});
// Map từ object sang string[]
const rooms: string[] = Array.isArray(roomData)
? (roomData as Room[]).map((r) => r.name)
: [];
// Mutation gửi lệnh
const sendCommandMutation = useMutationData<
SendCommandRequest,
SendCommandResponse
>({
url: "", // sẽ set động theo roomName khi gọi
method: "POST",
onSuccess: (data) => {
if (data.status === "OK") {
toast.success("Gửi lệnh thành công!");
} else {
toast.error("Gửi lệnh thất bại!");
}
},
onError: (error) => {
console.error("Send command error:", error);
toast.error("Gửi lệnh thất bại!");
},
});
return (
<FormSubmitTemplate
title="CMD Command"
description="Gửi lệnh shell xuống thiết bị để thực thi"
isLoading={sendCommandMutation.isPending}
rooms={rooms}
onSubmit={(roomName, command) => {
sendCommandMutation.mutateAsync({
url: BASE_URL + API_ENDPOINTS.DEVICE_COMM.SEND_COMMAND(roomName),
data: { Command: command },
});
}}
submitLoading={sendCommandMutation.isPending}
>
{({ command, setCommand }) => (
<ShellCommandForm
command={command}
onCommandChange={setCommand}
disabled={sendCommandMutation.isPending}
/>
)}
</FormSubmitTemplate>
);
}