import { useEffect, useState } from 'react'; import AddIcon from '@mui/icons-material/Add'; import CancelIcon from '@mui/icons-material/Cancel'; import DoneIcon from '@mui/icons-material/Done'; import PlayArrowIcon from '@mui/icons-material/PlayArrow'; import RemoveIcon from '@mui/icons-material/RemoveCircleOutlined'; import { Box, Button, Dialog, DialogActions, DialogContent, DialogTitle, TextField } from '@mui/material'; import { callAction } from '@/api/app'; import { dialogStyle } from 'CustomTheme'; import { useRequest } from 'alova/client'; import { ValidatedTextField } from 'components'; import { toast } from 'components/toast'; import { useI18nContext } from 'i18n/i18n-react'; import { updateValue } from 'utils'; import { ValidationError, validate } from 'validators'; import type Schema from 'validators/schema'; import type { ValidateFieldsError } from 'validators/schema'; import type { CommandItem } from './types'; interface CommandsDialogProps { open: boolean; creating: boolean; onClose: () => void; onSave: (ci: CommandItem) => void; selectedItem: CommandItem; validator: Schema; } const CommandsDialog = ({ open, creating, onClose, onSave, selectedItem, validator }: CommandsDialogProps) => { const { LL } = useI18nContext(); const [hasChanges, setHasChanges] = useState(false); const [editItem, setEditItem] = useState(selectedItem); const [fieldErrors, setFieldErrors] = useState(); const updateFormValue = updateValue( setEditItem as unknown as React.Dispatch< React.SetStateAction> > ); useEffect(() => { if (open) { setFieldErrors(undefined); setEditItem(selectedItem); } }, [open, selectedItem]); const hasChanged = (ci: CommandItem) => ci.id !== ci.o_id || (ci.name || '') !== (ci.o_name || '') || ci.cmd !== ci.o_cmd || ci.value !== ci.o_value || ci.deleted !== ci.o_deleted; useEffect(() => { setHasChanges(hasChanged(editItem)); }, [editItem]); const handleSave = async (itemToSave: CommandItem) => { try { setFieldErrors(undefined); await validate(validator, itemToSave); onSave(itemToSave); } catch (error) { setFieldErrors((error as ValidationError).fieldErrors); } finally { // setHasChanges(false); } }; const save = async () => { await handleSave(editItem); }; const { send: executeCommand } = useRequest( (id: string) => callAction({ action: 'executeCommand', param: id }), { immediate: false } ) .onSuccess(() => { toast.success(LL.EXECUTE_COMMAND_SENT()); }) .onError((error) => { toast.error(String(error.error?.message || 'An error occurred')); }); const execute = async () => { await executeCommand(editItem.name); }; const remove = () => { onSave({ ...editItem, deleted: true }); }; const handleClose = ( _event: React.SyntheticEvent, reason: 'backdropClick' | 'escapeKeyDown' ) => { if (reason !== 'backdropClick') { onClose(); } }; return ( {creating ? `${LL.ADD(1)} ${LL.NEW(0)}` : LL.EDIT()}  {LL.COMMAND(1)} {!creating && ( )} {hasChanges && ( )} {!creating && !hasChanges && editItem.cmd !== '' && ( )} ); }; export default CommandsDialog;