import React from 'react'; import { Modal } from '../Modal'; import { Input } from '../Input'; import { Button } from '../Button'; import { Select } from '../Select'; import api from '../../services/api'; import { useAuth } from '../../context/useAuth'; import { useToast } from '../../hooks/useToast'; import type { PaintingScheme, TechnicalDataSheet } from '../../types'; interface CreatePaintingSchemeModalProps { isOpen: boolean; onClose: () => void; onSuccess: () => void; projectId?: string; initialData?: PaintingScheme; } export const CreatePaintingSchemeModal: React.FC = ({ isOpen, onClose, onSuccess, projectId, initialData }) => { const { isGuest } = useAuth(); const { showGuestWarning } = useToast(); const [loading, setLoading] = React.useState(false); const [projects, setProjects] = React.useState<{ id: string, name: string }[]>([]); const [dataSheets, setDataSheets] = React.useState([]); const [selectedProjectId, setSelectedProjectId] = React.useState(projectId || ''); const [formData, setFormData] = React.useState({ name: '', type: '', coat: '', solidsVolume: '', yieldTheoretical: '', epsMin: '', epsMax: '', dilution: '', manufacturer: '', color: '', notes: '', paintConsumption: '', thinnerConsumption: '', paintId: '', thinnerId: '', thinnerSymbol: '', colorHex: '#ffffff' }); React.useEffect(() => { if (!projectId) { api.get('/projects').then(response => { setProjects(response.data); }).catch(err => console.error("Error loading projects", err)); } else { setSelectedProjectId(projectId); } api.get('/datasheets').then(response => { console.log('Frontend: Datasheets received:', response.data.length); setDataSheets(response.data); }).catch(err => { console.error("Frontend: Error loading datasheets:", err); }); }, [projectId, isOpen]); React.useEffect(() => { if (initialData) { setFormData({ name: initialData.name || '', type: initialData.type || '', coat: initialData.coat || '', solidsVolume: initialData.solidsVolume?.toString() || '', yieldTheoretical: initialData.yieldTheoretical?.toString() || '', epsMin: initialData.epsMin?.toString() || '', epsMax: initialData.epsMax?.toString() || '', dilution: initialData.dilution?.toString() || '', manufacturer: initialData.manufacturer || '', color: initialData.color || '', notes: initialData.notes || '', paintConsumption: initialData.paintConsumption?.toString() || '', thinnerConsumption: initialData.thinnerConsumption?.toString() || '', paintId: typeof initialData.paintId === 'object' ? (initialData.paintId?._id || '') : (initialData.paintId as string) || '', thinnerId: typeof initialData.thinnerId === 'object' ? (initialData.thinnerId?._id || '') : (initialData.thinnerId as string) || '', thinnerSymbol: initialData.thinnerSymbol || '', colorHex: initialData.colorHex || '#ffffff' }); if (initialData.projectId) setSelectedProjectId(initialData.projectId); } else { setFormData({ name: '', type: '', coat: '', solidsVolume: '', yieldTheoretical: '', epsMin: '', epsMax: '', dilution: '', manufacturer: '', color: '', notes: '', paintConsumption: '', thinnerConsumption: '', paintId: '', thinnerId: '', thinnerSymbol: '', colorHex: '#ffffff' }); if (projectId) setSelectedProjectId(projectId); } }, [initialData, isOpen, projectId]); const handleChange = (e: React.ChangeEvent) => { const { name, value } = e.target; // Mantém a atualização básica do estado setFormData(prev => { const newState = { ...prev, [name]: value }; // Lógica Proativa: Se mudar o NOME do produto no topo, tenta preencher tudo if (name === 'name' && value) { const ds = dataSheets.find(d => d.name === value); if (ds) { let mappedType = ''; const dsTypeNormalized = ds.type?.toLowerCase() || ''; if (dsTypeNormalized.includes('epóxi')) mappedType = 'epoxy'; else if (dsTypeNormalized.includes('poliuretano')) mappedType = 'polyurethane'; else if (dsTypeNormalized.includes('zinco')) mappedType = 'silicate-zinc'; else if (dsTypeNormalized.includes('acríl')) mappedType = 'acrylic'; else if (dsTypeNormalized.includes('alquíd')) mappedType = 'alkyd'; // Se a tinta tem um redutor na ficha, tenta achar o ID dele na biblioteca let thinnerId = ''; // Resetar redutor ao trocar a tinta if (ds.reducer) { const reducerCode = ds.reducer.trim().toLowerCase(); console.log(`Auto-fill: Looking for reducer "${reducerCode}" for paint "${ds.name}"`); // Busca flexível: exata ou contém const matchingReducer = dataSheets.find(d => d.name.toLowerCase() === reducerCode || d.name.toLowerCase().includes(reducerCode) || reducerCode.includes(d.name.toLowerCase()) ); if (matchingReducer) { thinnerId = matchingReducer._id || matchingReducer.id || ''; console.log(`Auto-fill: Found matching reducer: ${matchingReducer.name}`); } else { console.log(`Auto-fill: No matching reducer found in library for "${reducerCode}"`); } } return { ...newState, type: mappedType || newState.type, solidsVolume: ds.solidsVolume?.toString() || newState.solidsVolume, yieldTheoretical: ds.yieldTheoretical?.toString() || newState.yieldTheoretical, epsMin: ds.dftMin?.toString() || newState.epsMin, epsMax: ds.dftMax?.toString() || newState.epsMax, manufacturer: ds.manufacturer || newState.manufacturer, dilution: ds.dilution?.toString() || newState.dilution, paintId: ds._id || ds.id || newState.paintId, thinnerId: thinnerId, thinnerSymbol: ds.reducer || '' }; } } return newState; }); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); console.log("Submitting form with data:", formData); if (isGuest()) { showGuestWarning(); return; } if (!selectedProjectId) { alert("Selecione um projeto"); return; } setLoading(true); try { const payload = { ...formData, projectId: selectedProjectId, solidsVolume: formData.solidsVolume ? parseFloat(formData.solidsVolume) : null, yieldTheoretical: formData.yieldTheoretical ? parseFloat(formData.yieldTheoretical) : null, epsMin: formData.epsMin ? parseFloat(formData.epsMin) : null, epsMax: formData.epsMax ? parseFloat(formData.epsMax) : null, dilution: formData.dilution ? parseFloat(formData.dilution) : null, paintConsumption: formData.paintConsumption ? parseFloat(formData.paintConsumption) : null, thinnerConsumption: formData.thinnerConsumption ? parseFloat(formData.thinnerConsumption) : null, paintId: formData.paintId || null, thinnerId: formData.thinnerId || null, thinnerSymbol: formData.thinnerSymbol || null }; if (initialData) { await api.put(`/painting-schemes/${initialData.id}`, payload); } else { await api.post('/painting-schemes', payload); } onSuccess(); onClose(); } catch (error) { console.error('Error saving scheme', error); alert('Erro ao salvar esquema'); } finally { setLoading(false); } }; return (
{!projectId && ( ({ label: ds.name, value: ds.name })) ]} value={formData.name} onChange={handleChange} required /> {formData.name === '' && ( )}
{formData.colorHex}