async function loadSidebar() {
    try {
        // 根据当前页面路径计算aside.html的相对路径
        const currentPath = window.location.pathname;
        // 计算目录深度：分割路径，过滤掉空字符串和文件名
        const pathParts = currentPath.split('/').filter(part => part && !part.endsWith('.html'));
        let asidePath = 'aside.html';
        
        // 如果页面在子目录中，需要向上查找
        if (pathParts.length > 0) {
            const upLevels = '../'.repeat(pathParts.length);
            asidePath = upLevels + 'aside.html';
        }
        
        const response = await fetch(asidePath);
        const html = await response.text();
        document.getElementById('sidebar-container').innerHTML = html;
    } catch (error) {
        console.error('加载侧边栏失败:', error);
    }
}

// 批量上传功能
function initBatchUpload() {
    const batchUploadBtn = document.getElementById('batch-upload-btn');
    const batchUploadModal = document.getElementById('batch-upload-modal');
    const closeBatchUploadModal = document.getElementById('close-batch-upload-modal');
    const cancelBatchUploadBtn = document.getElementById('cancel-batch-upload-btn');
    const startUploadBtn = document.getElementById('start-upload-btn');

    if (batchUploadBtn && batchUploadModal) {
        // 显示批量上传模态框
        batchUploadBtn.addEventListener('click', () => {
            batchUploadModal.style.display = 'flex';
        });

        // 关闭批量上传模态框
        function closeUploadModal() {
            batchUploadModal.style.display = 'none';
        }

        if (closeBatchUploadModal) {
            closeBatchUploadModal.addEventListener('click', closeUploadModal);
        }
        
        if (cancelBatchUploadBtn) {
            cancelBatchUploadBtn.addEventListener('click', closeUploadModal);
        }

        // 点击模态框外部区域关闭模态框
        batchUploadModal.addEventListener('click', (event) => {
            if (event.target === batchUploadModal) {
                closeUploadModal();
            }
        });
    }

    // 文件上传功能
    const uploadArea = document.getElementById('upload-area');
    const batchFileInput = document.getElementById('batch-file-input');
    const fileNameDisplay = document.getElementById('file-name-display');
    const progressSection = document.getElementById('progress-section');

    if (uploadArea && batchFileInput) {
        // 点击上传区域触发文件选择
        uploadArea.addEventListener('click', () => {
            batchFileInput.click();
        });

        // 文件选择事件
        batchFileInput.addEventListener('change', (event) => {
            if (event.target.files.length > 0) {
                const file = event.target.files[0];
                if (fileNameDisplay) {
                    fileNameDisplay.textContent = `已选择文件: ${file.name}`;
                    fileNameDisplay.style.display = 'block';
                }
                
                if (startUploadBtn) {
                    startUploadBtn.disabled = false;
                }
                
                if (progressSection) {
                    progressSection.style.display = 'block';
                }
            }
        });

        // 拖拽上传功能
        uploadArea.addEventListener('dragover', (event) => {
            event.preventDefault();
            uploadArea.classList.add('dragover');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });

        uploadArea.addEventListener('drop', (event) => {
            event.preventDefault();
            uploadArea.classList.remove('dragover');
            
            if (event.dataTransfer.files.length > 0) {
                const file = event.dataTransfer.files[0];
                // 检查文件类型
                if (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                    file.type === 'application/vnd.ms-excel' || 
                    file.type === 'text/csv') {
                    
                    // 创建新的FileList来更新input的值
                    batchFileInput.files = event.dataTransfer.files;
                    
                    if (fileNameDisplay) {
                        fileNameDisplay.textContent = `已选择文件: ${file.name}`;
                        fileNameDisplay.style.display = 'block';
                    }
                    
                    if (startUploadBtn) {
                        startUploadBtn.disabled = false;
                    }
                    
                    if (progressSection) {
                        progressSection.style.display = 'block';
                    }
                } else {
                    alert('请上传Excel或CSV文件');
                }
            }
        });
    }
}

// 爬虫网站管理功能
let crawlerSites = [
    {
        id: 1,
        siteName: '行业资讯网',
        siteUrl: 'https://www.industrynews.com',
        requestDept: '市场部',
        isCollected: '是',
        collectionPlan: '定期爬取行业动态和新闻资讯，每周更新一次数据',
        crawlFrequency: '每天一次',
        lastCrawlTime: '2026-01-05T14:30',
        nextCrawlTime: '2026-01-06T14:30',
        crawlStatus: '正常',
        systemUrl: 'https://sys.industrynews.com',
        statistics: '数据量: 500条/天, 成功率: 98.5%',
        targetDataType: '新闻标题、发布时间、内容摘要',
        pageStructureStable: '是',
        antiCrawlMechanism: 'IP限制，需使用代理池',
        crawlerScriptId: 'CRAWL_001',
        负责人: '张三',
        lastUpdater: '李四',
        lastUpdateTime: '2026-01-05T10:00',
        dailyDataVolume: 500,
        successRate: 98.5,
        备注: '需使用企业网络访问'
    },
    {
        id: 2,
        siteName: '竞品分析网',
        siteUrl: 'https://www.competitoranalysis.com',
        requestDept: '产品部/市场部',
        isCollected: '是',
        collectionPlan: '每日爬取竞品价格和功能更新，生成对比报告',
        crawlFrequency: '每小时一次',
        lastCrawlTime: '2026-01-06T10:15',
        nextCrawlTime: '2026-01-06T11:15',
        crawlStatus: '正常',
        systemUrl: 'https://sys.competitoranalysis.com',
        statistics: '数据量: 200条/天, 成功率: 92.3%',
        targetDataType: '产品价格、功能列表、更新日志',
        pageStructureStable: '否',
        antiCrawlMechanism: '验证码，需OCR识别',
        crawlerScriptId: 'CRAWL_002',
        负责人: '王五',
        lastUpdater: '赵六',
        lastUpdateTime: '2026-01-04T16:20',
        dailyDataVolume: 200,
        successRate: 92.3,
        备注: '仅在工作日运行'
    },
    {
        id: 3,
        siteName: '政策法规网',
        siteUrl: 'https://www.policyregulation.com',
        requestDept: '法务部',
        isCollected: '否',
        collectionPlan: '网站内容更新频繁但结构复杂，爬取成本过高',
        crawlFrequency: '',
        lastCrawlTime: '',
        nextCrawlTime: '',
        crawlStatus: '已停用',
        systemUrl: 'https://sys.policyregulation.com',
        statistics: '数据量: 0条/天, 成功率: 0%',
        targetDataType: '',
        pageStructureStable: '',
        antiCrawlMechanism: '',
        crawlerScriptId: '',
        负责人: '孙七',
        lastUpdater: '周八',
        lastUpdateTime: '2025-12-20T09:15',
        dailyDataVolume: 0,
        successRate: 0,
        备注: '需人工评估后再决定是否收录'
    }
];

let editingId = null;

// 渲染爬虫网站表格
function renderCrawlerSitesTable() {
    const tbody = document.getElementById('crawler-sites-tbody');
    if (!tbody) return;
    
    tbody.innerHTML = '';
    
    crawlerSites.forEach(site => {
        const row = document.createElement('tr');
        
        // 根据是否收录设置状态样式
        const statusClass = site.isCollected === '是' ? 'status active' : 'status inactive';
        
        // 根据爬取状态设置状态样式
        const crawlStatusClass = site.crawlStatus === '正常' ? 'status active' : 
                                site.crawlStatus === '失败' ? 'status inactive' : 
                                site.crawlStatus === '暂停' ? 'status inactive' : 
                                site.crawlStatus === '待审核' ? 'status' : 'status';
        
        row.innerHTML = `
            <td><strong>${site.siteName}</strong></td>
            <td><a href="${site.siteUrl}" target="_blank">${site.siteUrl}</a></td>
            <td>${site.requestDept}</td>
<!--            <td><span class="${statusClass}">${site.isCollected}</span></td>-->
<!--            <td>${site.collectionPlan}</td>-->
            <td>${site.crawlFrequency}</td>
            <td>${site.lastCrawlTime || '-'}</td>
            <td><span class="${crawlStatusClass}">${site.crawlStatus}</span></td>
            <td>${site.systemUrl || '-'}</td>
            <td>${site.statistics || '-'}</td>
<!--            <td>${site.targetDataType}</td>-->
<!--            <td>${site.antiCrawlMechanism}</td>-->
<!--            <td>${site.负责人}</td>-->
            <td>
                <div class="action-buttons">
                    <button class="action-btn edit-btn" data-id="${site.id}">
                        <i class="fas fa-edit"></i> 编辑
                    </button>
                    <button class="action-btn delete-btn" data-id="${site.id}">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </div>
            </td>
        `;
        
        tbody.appendChild(row);
    });
    
    // 为编辑和删除按钮添加事件监听器
    document.querySelectorAll('.action-btn.edit-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const id = parseInt(e.currentTarget.getAttribute('data-id'));
            editCrawlerSite(id);
        });
    });
    
    document.querySelectorAll('.action-btn.delete-btn').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const id = parseInt(e.currentTarget.getAttribute('data-id'));
            deleteCrawlerSite(id);
        });
    });
}

// 显示新增网站模态框
function showAddSiteModal() {
    const modal = document.getElementById('crawler-site-modal');
    const modalTitle = document.getElementById('modal-title');
    const siteForm = document.getElementById('crawler-site-form');
    
    if (!modal || !modalTitle || !siteForm) return;
    
    modalTitle.textContent = '新增网站';
    siteForm.reset();
    document.getElementById('site-id').value = '';
    editingId = null;
    
    modal.style.display = 'flex';
}

// 显示编辑网站模态框
function showEditSiteModal(site) {
    const modal = document.getElementById('crawler-site-modal');
    const modalTitle = document.getElementById('modal-title');
    const siteForm = document.getElementById('crawler-site-form');
    
    if (!modal || !modalTitle || !siteForm) return;
    
    modalTitle.textContent = '编辑网站';
    document.getElementById('site-id').value = site.id;
    document.getElementById('site-name').value = site.siteName;
    document.getElementById('site-url').value = site.siteUrl;
    document.getElementById('request-dept').value = site.requestDept;
    document.getElementById('is-collected').value = site.isCollected;
    document.getElementById('collection-plan').value = site.collectionPlan;
    document.getElementById('crawl-frequency').value = site.crawlFrequency || '';
    document.getElementById('crawl-status').value = site.crawlStatus || '';
    document.getElementById('system-url').value = site.systemUrl || '';
    document.getElementById('statistics').value = site.statistics || '';
    document.getElementById('target-data-type').value = site.targetDataType || '';
    document.getElementById('anti-crawl-mechanism').value = site.antiCrawlMechanism || '';
    document.getElementById('负责人').value = site.负责人 || '';
    document.getElementById('last-crawl-time').value = site.lastCrawlTime || '';
    document.getElementById('备注').value = site.备注 || '';
    
    editingId = site.id;
    
    modal.style.display = 'flex';
}

// 编辑网站
function editCrawlerSite(id) {
    const site = crawlerSites.find(s => s.id === id);
    if (site) {
        showEditSiteModal(site);
    }
}

// 删除网站
function deleteCrawlerSite(id) {
    if (confirm('确定要删除这个网站吗？此操作不可恢复。')) {
        crawlerSites = crawlerSites.filter(site => site.id !== id);
        renderCrawlerSitesTable();
    }
}

// 计算下次爬取时间的辅助函数
function calculateNextCrawlTime(lastTime, frequency) {
    if (!lastTime) {
        // 如果没有上次爬取时间，使用当前时间
        lastTime = new Date().toISOString().slice(0, 16).replace('T', ' ');
    }
    
    // 将字符串转换为日期对象
    let date = new Date(lastTime.replace(' ', 'T'));
    
    // 根据频率计算下次爬取时间
    switch(frequency) {
        case '每天一次':
            date.setDate(date.getDate() + 1);
            break;
        case '每小时一次':
            date.setHours(date.getHours() + 1);
            break;
        case '每周一上午':
            // 计算到下一个周一
            const day = date.getDay();
            const daysUntilMonday = day === 0 ? 1 : (8 - day);
            date.setDate(date.getDate() + daysUntilMonday);
            date.setHours(9, 0, 0, 0); // 设置为上午9点
            break;
        case '每30分钟':
            date.setMinutes(date.getMinutes() + 30);
            break;
        case '每月1号':
            date.setMonth(date.getMonth() + 1);
            date.setDate(1);
            date.setHours(9, 0, 0, 0); // 设置为每月1号上午9点
            break;
        default:
            date.setDate(date.getDate() + 1); // 默认每天一次
    }
    
    // 返回格式化的日期字符串
    return date.toISOString().slice(0, 16).replace('T', ' ');
}

// 保存网站
function saveCrawlerSite() {
    const id = document.getElementById('site-id').value;
    const siteName = document.getElementById('site-name').value;
    const siteUrl = document.getElementById('site-url').value;
    const requestDept = document.getElementById('request-dept').value;
    const isCollected = document.getElementById('is-collected').value;
    const collectionPlan = document.getElementById('collection-plan').value;
    const crawlFrequency = document.getElementById('crawl-frequency').value;
    const crawlStatus = document.getElementById('crawl-status').value;
    const systemUrl = document.getElementById('system-url').value;
    const statistics = document.getElementById('statistics').value;
    const targetDataType = document.getElementById('target-data-type').value;
    const antiCrawlMechanism = document.getElementById('anti-crawl-mechanism').value;
    const 负责人 = document.getElementById('负责人').value;
    const lastCrawlTime = document.getElementById('last-crawl-time').value;
    const 备注 = document.getElementById('备注').value;
    
    // 验证必填字段
    if (!siteName || !siteUrl || !requestDept || !isCollected || !collectionPlan || !crawlFrequency || !crawlStatus || !targetDataType || !负责人) {
        alert('请填写所有必填字段');
        return;
    }
    
    // 验证网址格式
    try {
        new URL(siteUrl);
    } catch (e) {
        alert('请输入有效的网址格式');
        return;
    }
    
    if (editingId) {
        // 编辑现有网站
        const index = crawlerSites.findIndex(s => s.id === editingId);
        if (index !== -1) {
            crawlerSites[index] = {
                id: editingId,
                siteName,
                siteUrl,
                requestDept,
                isCollected,
                collectionPlan,
                crawlFrequency,
                lastCrawlTime,
                // 计算下次爬取时间（这里只是模拟，实际应根据频率计算）
                nextCrawlTime: calculateNextCrawlTime(lastCrawlTime, crawlFrequency),
                crawlStatus,
                systemUrl,
                statistics,
                targetDataType,
                pageStructureStable: '是', // 默认值，实际应用中可能需要从表单获取
                antiCrawlMechanism,
                crawlerScriptId: `CRAWL_${editingId.toString().padStart(3, '0')}`, // 生成脚本ID
                负责人,
                lastUpdater: '当前用户', // 实际应用中应从会话获取
                lastUpdateTime: new Date().toISOString().slice(0, 16).replace('T', ' '), // 当前时间
                dailyDataVolume: 0, // 默认值，实际应用中可能需要从表单获取
                successRate: 100, // 默认值，实际应用中可能需要从表单获取
                备注
            };
        }
    } else {
        // 添加新网站
        const newId = crawlerSites.length > 0 ? Math.max(...crawlerSites.map(s => s.id)) + 1 : 1;
        const currentTime = new Date().toISOString().slice(0, 16).replace('T', ' ');
        crawlerSites.push({
            id: newId,
            siteName,
            siteUrl,
            requestDept,
            isCollected,
            collectionPlan,
            crawlFrequency,
            lastCrawlTime,
            // 计算下次爬取时间（这里只是模拟，实际应根据频率计算）
            nextCrawlTime: calculateNextCrawlTime(lastCrawlTime, crawlFrequency),
            crawlStatus,
            systemUrl,
            statistics,
            targetDataType,
            pageStructureStable: '是', // 默认值
            antiCrawlMechanism,
            crawlerScriptId: `CRAWL_${newId.toString().padStart(3, '0')}`, // 生成脚本ID
            负责人,
            lastUpdater: '当前用户', // 实际应用中应从会话获取
            lastUpdateTime: currentTime, // 当前时间
            dailyDataVolume: 0, // 默认值
            successRate: 100, // 默认值
            备注
        });
    }
    
    renderCrawlerSitesTable();
    closeSiteModal();
}

// 关闭模态框
function closeSiteModal() {
    const modal = document.getElementById('crawler-site-modal');
    if (modal) {
        modal.style.display = 'none';
    }
}

// 初始化爬虫网站管理功能
function initCrawlerSiteManagement() {
    // 绑定新增网站按钮事件
    const addSiteBtn = document.getElementById('add-site-btn');
    if (addSiteBtn) {
        addSiteBtn.addEventListener('click', showAddSiteModal);
    }
    
    // 绑定模态框相关事件
    const closeSiteModalBtn = document.getElementById('close-site-modal');
    const cancelSiteBtn = document.getElementById('cancel-site-btn');
    const saveSiteBtn = document.getElementById('save-site-btn');
    
    if (closeSiteModalBtn) {
        closeSiteModalBtn.addEventListener('click', closeSiteModal);
    }
    
    if (cancelSiteBtn) {
        cancelSiteBtn.addEventListener('click', closeSiteModal);
    }
    
    if (saveSiteBtn) {
        saveSiteBtn.addEventListener('click', saveCrawlerSite);
    }
    
    // 点击模态框外部区域关闭模态框
    const modal = document.getElementById('crawler-site-modal');
    if (modal) {
        modal.addEventListener('click', (event) => {
            if (event.target === modal) {
                closeSiteModal();
            }
        });
    }
    
    // 绑定回车键事件，当在表单中按下回车时保存数据
    const siteForm = document.getElementById('crawler-site-form');
    if (siteForm) {
        siteForm.addEventListener('keypress', (event) => {
            if (event.key === 'Enter') {
                event.preventDefault();
                saveCrawlerSite();
            }
        });
    }
    
    // 渲染表格
    renderCrawlerSitesTable();
}

document.addEventListener('DOMContentLoaded', () => {
    loadSidebar();
    initBatchUpload();
    initCrawlerSiteManagement();
});