import React, { useState, useEffect, useRef } from "react"; interface VehicleAttribute { key: string; name: string; value: string; } interface InfoVinProps { vehicleName?: string; vehicleInfo?: string; vehicleAttributes?: VehicleAttribute[]; } const InfoVin: React.FC = ({ vehicleName = "VIN декодирование", vehicleInfo = "Поиск запчастей по VIN номеру автомобиля", vehicleAttributes = [] }) => { const [showTooltip, setShowTooltip] = useState(false); const [tooltipPosition, setTooltipPosition] = useState({ x: 0, y: 0 }); const timeoutRef = useRef(null); const iconRef = useRef(null); // Отладочный вывод атрибутов useEffect(() => { if (vehicleAttributes.length > 0) { console.log('🚗 Атрибуты автомобиля:', vehicleAttributes); console.log('🔍 Ключи атрибутов:', vehicleAttributes.map(attr => ({ key: attr.key, name: attr.name }))); } }, [vehicleAttributes]); // Определяем основные параметры для отображения const getMainParameters = (attributes: VehicleAttribute[]) => { // Приоритетные ключи для основных параметров const priorityKeys = [ // Двигатель { keys: ['engine', 'enginetype', 'engine_type', 'двигатель', 'тип двигателя', 'motor'], priority: 1 }, // VIN { keys: ['vin', 'вин', 'vin_code'], priority: 2 }, // Год выпуска { keys: ['year', 'год', 'год выпуска', 'production_year', 'model_year'], priority: 3 }, // Топливо { keys: ['fuel', 'топливо', 'тип топлива', 'fuel_type', 'fueltype'], priority: 4 }, // Коробка передач { keys: ['transmission', 'коробка', 'кпп', 'gearbox', 'transmissiontype'], priority: 5 } ]; const foundParams: Array<{ attr: VehicleAttribute; priority: number }> = []; // Ищем атрибуты по приоритетным ключам for (const priorityGroup of priorityKeys) { const foundAttr = attributes.find(attr => priorityGroup.keys.some(key => attr.key.toLowerCase().includes(key.toLowerCase()) || attr.name.toLowerCase().includes(key.toLowerCase()) ) ); if (foundAttr) { foundParams.push({ attr: foundAttr, priority: priorityGroup.priority }); } } // Сортируем по приоритету и берем максимум 4 параметра foundParams.sort((a, b) => a.priority - b.priority); const mainParams = foundParams.slice(0, 4).map(item => item.attr); // Если основных параметров меньше 3, добавляем первые доступные if (mainParams.length < 3) { const additionalParams = attributes .filter(attr => !mainParams.includes(attr)) .slice(0, 3 - mainParams.length); return [...mainParams, ...additionalParams]; } return mainParams; }; const mainParameters = getMainParameters(vehicleAttributes); const displayText = mainParameters.length > 0 ? mainParameters.map(attr => attr.value).join(' · ') : vehicleInfo; // Отладочный вывод выбранных параметров useEffect(() => { if (mainParameters.length > 0) { console.log('✅ Выбранные основные параметры:', mainParameters); console.log('📝 Отображаемый текст:', displayText); } }, [mainParameters, displayText]); // Вычисляем позицию tooltip const calculateTooltipPosition = () => { if (iconRef.current) { const rect = iconRef.current.getBoundingClientRect(); const tooltipWidth = 500; const tooltipHeight = 300; // примерная высота let x = rect.left + rect.width / 2 - tooltipWidth / 2; let y = rect.bottom + 8; // Проверяем, не выходит ли tooltip за границы экрана if (x < 10) x = 10; if (x + tooltipWidth > window.innerWidth - 10) { x = window.innerWidth - tooltipWidth - 10; } // Если tooltip не помещается снизу, показываем сверху if (y + tooltipHeight > window.innerHeight - 10) { y = rect.top - tooltipHeight - 8; } setTooltipPosition({ x, y }); } }; const handleMouseEnter = () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } timeoutRef.current = setTimeout(() => { calculateTooltipPosition(); setShowTooltip(true); }, 300); // Задержка 300ms }; const handleMouseLeave = () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } timeoutRef.current = setTimeout(() => { setShowTooltip(false); }, 100); // Небольшая задержка перед скрытием }; // Очищаем таймеры при размонтировании useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, []); return ( <>
{displayText}
{/* Tooltip с фиксированным позиционированием */} {showTooltip && vehicleAttributes.length > 0 && (
{/* Заголовок */}

Полная информация об автомобиле

{vehicleName}

{/* Атрибуты в сетке */}
{vehicleAttributes.map((attr, index) => (
{attr.name}
{attr.value}
))}
{/* Подвал */}
Всего параметров: {vehicleAttributes.length}
)} ); }; export default InfoVin;