// 全局变量
let currentFile = null;

// 标签页切换功能
function openTab(tabName) {
    // 隐藏所有标签页内容
    const tabContents = document.getElementsByClassName('tab-content');
    for (let i = 0; i < tabContents.length; i++) {
        tabContents[i].classList.remove('active');
    }
    
    // 移除所有标签按钮的激活状态
    const tabButtons = document.getElementsByClassName('tab-button');
    for (let i = 0; i < tabButtons.length; i++) {
        tabButtons[i].classList.remove('active');
    }
    
    // 显示选中的标签页内容
    document.getElementById(tabName).classList.add('active');
    
    // 激活对应的标签按钮
    event.currentTarget.classList.add('active');
    
    // 清空当前文件
    currentFile = null;
    clearResults();
}

// 文件上传处理
function setupFileUpload(inputId, uploadAreaId) {
    const fileInput = document.getElementById(inputId);
    const uploadArea = document.getElementById(uploadAreaId);
    
    fileInput.addEventListener('change', function(e) {
        if (this.files.length > 0) {
            handleFileUpload(this.files[0], uploadArea);
        }
    });
    
    // 拖拽上传功能
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.style.borderColor = '#2980b9';
        this.style.background = '#e9ecef';
    });
    
    uploadArea.addEventListener('dragleave', function(e) {
        e.preventDefault();
        this.style.borderColor = '#3498db';
        this.style.background = '#f8f9fa';
    });
    
    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        this.style.borderColor = '#3498db';
        this.style.background = '#f8f9fa';
        
        if (e.dataTransfer.files.length > 0) {
            handleFileUpload(e.dataTransfer.files[0], uploadArea);
        }
    });
}

// 处理文件上传
async function handleFileUpload(file, uploadArea) {
    const formData = new FormData();
    formData.append('file', file);
    
    showStatus('正在上传文件...', 'info');
    
    try {
        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            currentFile = result;
            uploadArea.innerHTML = `
                <div style="text-align: center;">
                    <p style="color: #27ae60; font-weight: bold;">✓ 文件上传成功</p>
                    <p>文件名: ${result.filename}</p>
                    <p>文件类型: ${result.file_type}</p>
                    <button onclick="clearFile('${uploadArea.id}')" class="btn" style="background: #e74c3c; color: white; margin-top: 10px;">重新选择</button>
                </div>
            `;
            showStatus('文件上传成功！', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        showStatus('上传失败: ' + error.message, 'error');
        uploadArea.innerHTML = `
            <div class="upload-placeholder" onclick="document.getElementById('${fileInput.id}').click()">
                <p>点击选择文件或拖拽文件到此处</p>
                <p class="file-types">上传失败，请重试</p>
            </div>
        `;
    }
}

// 清空文件选择
function clearFile(uploadAreaId) {
    const uploadArea = document.getElementById(uploadAreaId);
    const fileInputId = uploadAreaId.replace('-upload-area', '-file');
    
    uploadArea.innerHTML = `
        <input type="file" id="${fileInputId}" style="display: none;">
        <div class="upload-placeholder" onclick="document.getElementById('${fileInputId}').click()">
            <p>点击选择文件或拖拽文件到此处</p>
            <p class="file-types">支持格式: 根据标签页不同</p>
        </div>
    `;
    
    currentFile = null;
    clearResults();
    setupFileUpload(fileInputId, uploadAreaId);
}

// PDF处理功能
async function processPdf(action) {
    if (!currentFile) {
        showStatus('请先选择PDF文件', 'error');
        return;
    }
    
    showStatus('正在处理PDF文件...', 'info');
    
    try {
        const response = await fetch('/process/pdf', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                filepath: currentFile.filepath,
                action: action
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            if (action === 'extract') {
                document.getElementById('pdf-result').innerHTML = `
                    <h4>提取的文本内容:</h4>
                    <div style="max-height: 300px; overflow-y: auto; background: white; padding: 15px; border-radius: 5px;">
                        ${result.text || '未提取到文本内容'}
                    </div>
                `;
            } else if (action === 'to_excel') {
                document.getElementById('pdf-result').innerHTML = `
                    <h4>转换成功!</h4>
                    <p>PDF文件已成功转换为Excel格式</p>
                    <a href="${result.download_url}" class="download-link" download>下载Excel文件</a>
                `;
            }
            showStatus('PDF处理完成！', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        showStatus('处理失败: ' + error.message, 'error');
    }
}

// 图片处理功能
async function processImage(action) {
    if (!currentFile) {
        showStatus('请先选择图片文件', 'error');
        return;
    }
    
    showStatus('正在处理图片文件...', 'info');
    
    try {
        const response = await fetch('/process/image', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                filepath: currentFile.filepath,
                action: action
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            if (action === 'extract') {
                document.getElementById('image-result').innerHTML = `
                    <h4>识别的文字内容:</h4>
                    <div style="max-height: 300px; overflow-y: auto; background: white; padding: 15px; border-radius: 5px;">
                        ${result.text || '未识别到文字内容'}
                    </div>
                `;
            } else {
                const formatName = action === 'to_excel' ? 'Excel' : '文本';
                document.getElementById('image-result').innerHTML = `
                    <h4>转换成功!</h4>
                    <p>图片文件已成功转换为${formatName}格式</p>
                    <a href="${result.download_url}" class="download-link" download>下载${formatName}文件</a>
                `;
            }
            showStatus('图片处理完成！', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        showStatus('处理失败: ' + error.message, 'error');
    }
}

// 格式转换功能
async function processFormat() {
    if (!currentFile) {
        showStatus('请先选择文件', 'error');
        return;
    }
    
    const targetFormat = document.getElementById('target-format').value;
    
    showStatus('正在转换文件格式...', 'info');
    
    try {
        const response = await fetch('/process/format', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                filepath: currentFile.filepath,
                target_format: targetFormat
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            document.getElementById('format-result').innerHTML = `
                <h4>转换成功!</h4>
                <p>文件已成功转换为${targetFormat.toUpperCase()}格式</p>
                <a href="${result.download_url}" class="download-link" download>下载文件</a>
            `;
            showStatus('格式转换完成！', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        showStatus('转换失败: ' + error.message, 'error');
    }
}

// 网页抓取功能
async function processWeb() {
    const url = document.getElementById('web-url').value;
    const selector = document.getElementById('css-selector').value;
    
    if (!url) {
        showStatus('请输入网页URL', 'error');
        return;
    }
    
    showStatus('正在抓取网页内容...', 'info');
    
    try {
        const response = await fetch('/process/web', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                url: url,
                selector: selector
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            document.getElementById('web-result').innerHTML = `
                <h4>抓取结果:</h4>
                <div style="max-height: 300px; overflow-y: auto; background: white; padding: 15px; border-radius: 5px;">
                    ${result.content || '未抓取到内容'}
                </div>
            `;
            showStatus('网页抓取完成！', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        showStatus('抓取失败: ' + error.message, 'error');
    }
}

// 网页抓取并导出为Excel
async function processWebToExcel() {
    const url = document.getElementById('web-url').value;
    const selector = document.getElementById('css-selector').value;
    
    if (!url) {
        showStatus('请输入网页URL', 'error');
        return;
    }
    
    showStatus('正在抓取网页并导出为Excel...', 'info');
    
    try {
        const response = await fetch('/process/web', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                url: url,
                selector: selector
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            document.getElementById('web-result').innerHTML = `
                <h4>导出成功!</h4>
                <p>网页内容已成功导出为Excel格式</p>
                <a href="${result.download_url}" class="download-link" download>下载Excel文件</a>
            `;
            showStatus('网页导出完成！', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        showStatus('导出失败: ' + error.message, 'error');
    }
}

// 数据库导出功能
async function processDatabase() {
    if (!currentFile) {
        showStatus('请先选择数据库文件', 'error');
        return;
    }
    
    const targetFormat = document.getElementById('db-target-format').value;
    const tableName = document.getElementById('table-name').value;
    
    showStatus('正在导出数据库...', 'info');
    
    try {
        const response = await fetch('/process/database', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                filepath: currentFile.filepath,
                target_format: targetFormat,
                table_name: tableName
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            document.getElementById('database-result').innerHTML = `
                <h4>导出成功!</h4>
                <p>数据库已成功导出为${targetFormat.toUpperCase()}格式</p>
                <a href="${result.download_url}" class="download-link" download>下载文件</a>
            `;
            showStatus('数据库导出完成！', 'success');
        } else {
            throw new Error(result.error);
        }
    } catch (error) {
        showStatus('导出失败: ' + error.message, 'error');
    }
}

// 显示状态消息
function showStatus(message, type) {
    const statusEl = document.getElementById('status-message');
    statusEl.textContent = message;
    statusEl.className = `status-message status-${type}`;
    statusEl.style.display = 'block';
    
    setTimeout(() => {
        statusEl.style.display = 'none';
    }, 5000);
}

// 清空结果区域
function clearResults() {
    const resultAreas = document.getElementsByClassName('result-area');
    for (let i = 0; i < resultAreas.length; i++) {
        resultAreas[i].innerHTML = '';
    }
}

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    // 设置文件上传功能
    setupFileUpload('pdf-file', 'pdf-upload-area');
    setupFileUpload('image-file', 'image-upload-area');
    setupFileUpload('format-file', 'format-upload-area');
    setupFileUpload('db-file', 'db-upload-area');
    
    // 设置输入框回车事件
    document.getElementById('web-url').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            processWeb();
        }
    });
});