Загрузка данных


(function() {
    const oldPanel = document.getElementById('super-search-panel');
    if (oldPanel) oldPanel.remove();

    let globalDatabase = [];

    // Создаем основную панель
    const panel = document.createElement('div');
    panel.id = 'super-search-panel';
    panel.style.cssText = `
        position: fixed; top: 20px; right: 20px; width: 350px; max-height: 85vh;
        background: #fff; z-index: 99999; padding: 15px; border: 1px solid #e0e0e6;
        border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        display: flex; flex-direction: column; gap: 10px; font-family: sans-serif;
    `;

    const header = document.createElement('div');
    header.style.cssText = 'display: flex; justify-content: space-between; font-weight: bold;';
    header.innerHTML = `<span>Глобальный поиск</span> <span id="close-super-search" style="color: red; cursor: pointer; font-size: 12px; font-weight: normal;">Закрыть</span>`;

    const statusLabel = document.createElement('div');
    statusLabel.style.fontSize = '12px';
    statusLabel.innerText = 'Нажмите кнопку для сбора базы:';

    const collectBtn = document.createElement('button');
    collectBtn.innerText = 'Собрать данные (Авто-пролистывание)';
    collectBtn.style.cssText = 'padding: 8px; background: #2080f0; color: #fff; border: none; border-radius: 4px; cursor: pointer; font-weight: bold;';

    const searchInput = document.createElement('input');
    searchInput.type = 'text';
    searchInput.placeholder = 'Сначала соберите данные...';
    searchInput.disabled = true;
    searchInput.style.cssText = 'padding: 8px; border: 1px solid #ccc; border-radius: 4px; outline: none;';

    const resultsDiv = document.createElement('div');
    resultsDiv.style.cssText = 'overflow-y: auto; max-height: 400px; display: flex; flex-direction: column; gap: 6px; font-size: 13px;';

    panel.append(header, statusLabel, collectBtn, searchInput, resultsDiv);
    document.body.appendChild(panel);

    document.getElementById('close-super-search').onclick = () => panel.remove();

    // Логика автоматического пролистывания
    collectBtn.onclick = async () => {
        collectBtn.disabled = true;
        collectBtn.style.background = '#ccc';
        globalDatabase = [];
        let pageNum = 1;

        while (true) {
            statusLabel.innerText = `Сканирование... Страница ${pageNum}. Пожалуйста, подождите.`;
            
            // Собираем данные
            const rows = document.querySelectorAll('.n-data-table-tbody .n-data-table-tr');
            rows.forEach(row => {
                const cells = row.querySelectorAll('.n-data-table-td');
                if (cells.length >= 7) {
                    const lastName = cells[1].innerText.trim();
                    const firstName = cells[2].innerText.trim();
                    const middleName = cells[3].innerText.trim();
                    const birth = cells[4].innerText.trim();
                    const linkEl = cells[0].querySelector('a');
                    
                    globalDatabase.push({
                        fullName: `${lastName} ${firstName} ${middleName}`,
                        birth: birth,
                        link: linkEl ? linkEl.href : ''
                    });
                }
            });

            // Ищем кнопку именно по тексту внутри нее
            const buttons = Array.from(document.querySelectorAll('.n-button'));
            const nextBtn = buttons.find(btn => btn.textContent.includes('Следующая страница'));
            
            // Проверяем, не заблокирована ли она (если это последняя страница)
            const isDisabled = nextBtn && (
                nextBtn.classList.contains('n-button--disabled') || 
                nextBtn.disabled ||
                nextBtn.getAttribute('aria-disabled') === 'true'
            );

            if (nextBtn && !isDisabled) {
                // Кликаем по кнопке
                nextBtn.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true }));
                nextBtn.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true }));
                nextBtn.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true }));
                
                pageNum++;
                // Ждем 2 секунды для загрузки новой страницы
                await new Promise(r => setTimeout(r, 2000)); 
            } else {
                break; // Кнопки нет или она заблокирована — выходим из цикла
            }
        }

        statusLabel.innerText = `Успешно! Собрано записей: ${globalDatabase.length}.`;
        statusLabel.style.color = '#18a058';
        collectBtn.style.display = 'none';
        
        searchInput.disabled = false;
        searchInput.placeholder = 'Введите ФИО или дату...';
        searchInput.focus();
    };

    // Логика поиска
    searchInput.addEventListener('input', () => {
        const query = searchInput.value.toLowerCase().trim();
        resultsDiv.innerHTML = '';
        
        if (!query) return;

        const matches = globalDatabase.filter(item => 
            item.fullName.toLowerCase().includes(query) || 
            item.birth.includes(query)
        );
        
        if (matches.length === 0) {
            resultsDiv.innerHTML = '<div style="color:gray;">Совпадений нет</div>';
            return;
        }

        matches.forEach(m => {
            const itemDiv = document.createElement('div');
            itemDiv.style.cssText = 'padding: 8px; border: 1px solid #efeff5; border-radius: 4px; background: #fafafc;';
            itemDiv.innerHTML = `
                <div style="font-weight: bold;">
                    ${m.link ? `<a href="${m.link}" target="_blank" style="color:#18a058; text-decoration:none;">${m.fullName}</a>` : m.fullName}
                </div>
                <div style="color: #767c82; font-size: 12px; margin-top: 4px;">Дата рождения: ${m.birth}</div>
            `;
            resultsDiv.appendChild(itemDiv);
        });
    });
})();