'use client'; import { useState, useRef, useEffect } from 'react'; interface Message { id: string; role: 'user' | 'assistant'; content: string; timestamp: Date; files?: File[]; } interface AIAgentModalProps { isOpen: boolean; onClose: () => void; } export default function AIAgentModal({ isOpen, onClose }: AIAgentModalProps) { const [messages, setMessages] = useState([ { id: '1', role: 'assistant', content: 'Здравствуйте! Я ИИ агент системы контроля лётной годности. Чем могу помочь? Я могу помочь с анализом документов, внесением данных в базу, поиском информации и другими задачами.', timestamp: new Date(), }, ]); const [inputValue, setInputValue] = useState(''); const [isLoading, setIsLoading] = useState(false); const [attachedFiles, setAttachedFiles] = useState([]); const messagesEndRef = useRef(null); const fileInputRef = useRef(null); useEffect(() => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [messages]); if (!isOpen) { return null; } const handleSend = async () => { if (!inputValue.trim() && attachedFiles.length === 0) { return; } const userMessage: Message = { id: Date.now().toString(), role: 'user', content: inputValue, timestamp: new Date(), files: attachedFiles.length > 0 ? [...attachedFiles] : undefined, }; setMessages(prev => [...prev, userMessage]); const currentInput = inputValue; const currentFiles = attachedFiles; setInputValue(''); setAttachedFiles([]); setIsLoading(true); try { // Если есть файлы, отправляем их через FormData let response: Response; if (currentFiles.length > 0) { const formData = new FormData(); formData.append('message', currentInput); formData.append('history', JSON.stringify(messages.map(m => ({ role: m.role, content: m.content, })))); // Добавляем файлы currentFiles.forEach((file, index) => { formData.append(`file_${index}`, file); }); formData.append('fileCount', currentFiles.length.toString()); response = await fetch('/api/ai-chat', { method: 'POST', body: formData, }); } else { // Обычный запрос без файлов response = await fetch('/api/ai-chat', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ message: currentInput, history: messages.map(m => ({ role: m.role, content: m.content, })), }), }); } const data = await response.json(); const assistantMessage: Message = { id: (Date.now() + 1).toString(), role: 'assistant', content: data.response || 'Извините, произошла ошибка при обработке запроса.', timestamp: new Date(), }; setMessages(prev => [...prev, assistantMessage]); } catch (error) { console.error('Ошибка при запросе к AI:', error); const errorMessage: Message = { id: (Date.now() + 1).toString(), role: 'assistant', content: 'Извините, произошла ошибка при подключении к ИИ агенту. Попробуйте позже.', timestamp: new Date(), }; setMessages(prev => [...prev, errorMessage]); } finally { setIsLoading(false); } }; const handleFileSelect = (event: React.ChangeEvent) => { if (event.target.files) { const newFiles = Array.from(event.target.files); // Фильтруем только разрешенные типы файлов const allowedTypes = [ 'application/pdf', 'image/jpeg', 'image/jpg', 'image/png', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'text/csv', 'text/plain', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', ]; const allowedExtensions = ['.pdf', '.jpeg', '.jpg', '.png', '.xls', '.xlsx', '.csv', '.txt', '.doc', '.docx']; const validFiles = newFiles.filter(file => { const extension = '.' + file.name.split('.').pop()?.toLowerCase(); return allowedTypes.includes(file.type) || allowedExtensions.includes(extension); }); if (validFiles.length !== newFiles.length) { alert('Некоторые файлы не поддерживаются. Разрешены: PDF, JPEG, PNG, XLS, XLSX, CSV, TXT, DOC, DOCX'); } setAttachedFiles(prev => [...prev, ...validFiles]); } }; const handleRemoveFile = (index: number) => { setAttachedFiles(prev => prev.filter((_, i) => i !== index)); }; const handleKeyPress = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }; return (
e.stopPropagation()} > {/* Header */}

ИИ Агент

Помощник по управлению системой контроля лётной годности

{/* Messages */}
{messages.map((message) => (
{message.files && message.files.length > 0 && (
{message.files.map((file, idx) => (
📎 {file.name} ({(file.size / 1024).toFixed(1)} KB)
))}
)}
{message.content}
{message.timestamp.toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}
))} {isLoading && (
)}
{/* Attached Files */} {attachedFiles.length > 0 && (
{attachedFiles.map((file, index) => (
📎 {file.name}
))}
)} {/* Input */}