<!DOCTYPE html>
<html lang="zh">

<head>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title id="website-title"></title>
    <link rel="stylesheet" href="{{ url_for('serve_static', filename='style.css') }}">
    <style>
        .toast-container {
            position: fixed;
            top: 1rem;
            right: 1rem;
            z-index: 9999;
        }
        .toast {
            margin-bottom: 0.5rem;
            padding: 1rem;
            border-radius: 0.5rem;
            min-width: 300px;
            max-width: 500px;
            animation: slideIn 0.3s ease-in-out;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            word-wrap: break-word;
        }
        .toast-success {
            background-color: #10B981;
            color: white;
        }
        .toast-error {
            background-color: #EF4444;
            color: white;
        }
        .toast-info {
            background-color: #3B82F6;
            color: white;
        }
        .toast-warning {
            background-color: #F59E0B;
            color: white;
        }
        #debug-content {
            white-space: pre-wrap;
            word-wrap: break-word;
            max-height: 400px;
            overflow-y: auto;
        }
        @keyframes slideIn {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>
</head>

<body class="bg-background text-foreground flex flex-col items-center justify-center p-4">
    <h1 id="website-name" class="text-5xl font-bold text-primary mb-2"></h1>
    <div id="version-info" class="text-lg text-gray-600 mb-6"></div>

    <div id="error" class="error hidden text-destructive bg-red-100 border border-red-400 p-4 rounded mb-4"></div>
    <!-- <div id="success" class="success hidden text-accent bg-yellow-100 border border-yellow-400 p-4 rounded mb-4">处理成功！</div>
    <div id="loading" class="loading text-secondary hidden">处理中，请稍候...</div>  -->

    <div id="toast-container" class="toast-container"></div>

    <div id="debug-info" class="debug-info hidden bg-zinc-100 border border-zinc-300 p-4 rounded mb-4 rounded-lg shadow-lg ">
        <h3 class="font-semibold">调试信息汇总：</h3>
        <pre id="debug-content"></pre>
    </div>

    <!-- 下载历史记录 -->
    <div id="download-history" class="hidden bg-blue-50 border border-blue-300 p-4 rounded mb-4 rounded-lg shadow-lg">
        <h3 class="font-semibold mb-2">下载记录：</h3>
        <div id="history-list" class="space-y-2 max-h-60 overflow-y-auto">
            <!-- 历史记录将在这里动态添加 -->
        </div>
        <p class="mt-3 text-sm text-gray-600">
            提示: 下载文件默认保存在浏览器的默认下载文件夹中。您可以在浏览器设置中更改下载位置。
        </p>
    </div>

    <!-- 文件输入部分 -->
    <div class="bg-card p-6 rounded-lg shadow-lg form-container mb-4">
        <h2 class="text-xl font-bold mb-4">文件输入</h2>
        <label for="file" class="block font-bold mb-2">选择文件：</label>
        <label for="file" class="file-label">📂 选择文件 </label>
        <input type="file" id="file" required class="border border-border rounded p-2 mb-4 w-full"  />
        <div class="form-group mb-4">
            <label for="jieba_dict" class="block font-bold mb-2">可选：上传jieba自定义分词库</label>
            <label for="jieba_dict" class="file-label">📝 选择分词库文件</label>
            <input type="file" id="jieba_dict" name="jieba_dict" class="border border-border rounded p-2 mb-2 w-full" />
            <input type="text" id="jieba-dict-path" class="border border-border rounded p-2 mb-4 w-full" placeholder="未选择分词库文件" readonly />
        </div>
        <input type="text" id="file-path" class="border border-border rounded p-2 mb-4 w-full" placeholder="未选择文件" readonly />

        <label for="tool" class="block font-bold mb-2">选择工具：</label>
        <select id="tool-file" required class="border border-border rounded p-2 mb-4 w-full">
            <option value="selection">请选择工具</option>
            <option value="vcf">VCF</option>
            <!-- <option value="simple-english">Simple English</option> -->
            <option value="se">Simple English (se)</option>
            <!-- <option value="simple-chinese">Simple Chinese</option> -->
            <option value="sc">Simple Chinese (sc)</option>
            <option value="tosougou">To Sogou</option>
        </select>

        <button onclick="processFile('file')"
            class="bg-primary text-primary-foreground  rounded p-2 w-full transition duration-300">处理文件</button>
    </div>

    <!-- EPUB功能已注销的说明 -->
    <div class="bg-yellow-50 border border-yellow-300 p-4 rounded mb-4 rounded-lg shadow-lg">
        <h3 class="font-semibold mb-2 text-yellow-800">📢 功能说明</h3>
        <p class="text-yellow-700">
            EPUB 相关功能已注销，目前支持的功能包括：VCF联系人转换、简单英文/中文词库转换、搜狗词库转换等。
        </p>
    </div>

    <script>
        // 定义GUI版本变量
        const GUI_VERSION = '1.2.1';
        // 自动获取当前页面的主机和端口
        const BASE_URL = `${window.location.protocol}//${window.location.host}`;
        
        function log(message, type = 'info') {
            console.log(`[${type.toUpperCase()}] ${message}`);
            const debugContent = document.getElementById('debug-content');

            // 创建toast元素
            const toast = document.createElement('div');
            // 完整的日期时间格式，如 "2025年4月8日 14:30:45"
            const now = new Date();
            const timestamp = now.getFullYear() + '年' + 
                             (now.getMonth() + 1) + '月' + 
                             now.getDate() + '日 ' + 
                             now.getHours() + ':' + 
                             String(now.getMinutes()).padStart(2, '0') + ':' + 
                             String(now.getSeconds()).padStart(2, '0');
            
            debugContent.textContent += `[${timestamp}] ${message}\n`;
            document.getElementById('debug-info').style.display = 'block';

            // 如果是成功处理文件的消息，使用success类型
            if (message.includes('处理成功') && message.includes('outputs')) {
                type = 'success';
            }

            toast.className = `toast toast-${type}`;
            toast.innerHTML = `
                <div class="flex items-center">
                    <span class="font-bold mr-2">[${timestamp}]</span>
                    <span>${message}</span>
                </div>
            `;

            // 添加到容器
            const container = document.getElementById('toast-container');
            container.appendChild(toast);

            // 3秒后自动移除
            setTimeout(() => {
                toast.style.opacity = '0';
                toast.style.transform = 'translateX(100%)';
                toast.style.transition = 'all 0.3s ease-in-out';
                setTimeout(() => {
                    container.removeChild(toast);
                }, 300);
            }, 3000);
        }

        // 显示详细错误信息
        function showDetailedError(error) {
            log(`详细错误: ${JSON.stringify(error)}`, 'error');
            
            // 创建详细错误对话框
            const errorDialog = document.createElement('div');
            errorDialog.className = 'fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50';
            errorDialog.innerHTML = `
                <div class="bg-white p-6 rounded-lg shadow-lg max-w-lg w-full">
                    <h3 class="text-xl font-bold mb-4 text-red-600">错误详情</h3>
                    <div class="mb-4 overflow-auto max-h-96 bg-gray-100 p-4 rounded">
                        <pre class="whitespace-pre-wrap">${JSON.stringify(error, null, 2)}</pre>
                    </div>
                    <div class="flex justify-end">
                        <button id="close-error" class="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600">关闭</button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(errorDialog);
            
            document.getElementById('close-error').addEventListener('click', function() {
                document.body.removeChild(errorDialog);
            });
        }

        // 文件选择事件
        document.getElementById('file').addEventListener('change', function () {
            const filePathInput = document.getElementById('file-path');
            if (this.files.length > 0) {
                filePathInput.value = this.files[0].name;
            } else {
                filePathInput.value = '未选择文件';
            }
        });

        // jieba分词库文件选择事件
        document.getElementById('jieba_dict').addEventListener('change', function () {
            const jiebaDictPathInput = document.getElementById('jieba-dict-path');
            if (this.files.length > 0) {
                jiebaDictPathInput.value = this.files[0].name;
                log(`选择jieba分词库: ${this.files[0].name}`, 'info');
            } else {
                jiebaDictPathInput.value = '未选择分词库文件';
            }
        });

        function processFile(type) {
            log('开始处理');

            // 现在只支持单个文件处理
            if (type !== 'file') {
                log('EPUB功能已注销，请使用文件输入方式', 'error');
                const error = document.getElementById('error');
                error.textContent = 'EPUB功能已注销，请使用文件输入方式';
                error.style.display = 'block';
                return;
            }

            const fileInput = document.getElementById('file');
            const toolInput = document.getElementById('tool-file');
            const pathInput = document.getElementById('file-path');
            const error = document.getElementById('error');

            // 检查文件
            if (fileInput.files.length === 0) {
                const errorMsg = '请选择文件';
                log(errorMsg, 'error');
                error.textContent = errorMsg;
                error.style.display = 'block';
                return;
            }

            const tool = toolInput.value;

            // 准备表单数据
            const formData = new FormData();
            formData.append('file', fileInput.files[0]); // 文件对象
            formData.append('tool', tool); // 工具类型 (vcf, se, sc, tosougou)
            // 如果用户选择了jieba分词库，上传
            const jiebaDictInput = document.getElementById('jieba_dict');
            if (jiebaDictInput && jiebaDictInput.files.length > 0) {
                formData.append('jieba_dict', jiebaDictInput.files[0]);
                log(`附加jieba分词库: ${jiebaDictInput.files[0].name}`, 'info');
            }
            
            // 添加调试信息
            log(`准备发送请求 - 参数:`, 'info');
            log(`工具: ${tool}`, 'info');
            const fileObj = fileInput.files[0];
            log(`文件: "${fileObj.name}", 大小: ${(fileObj.size / 1024).toFixed(2)} KB`, 'info');

            log(`准备发送请求 - 文件: ${pathInput.value}, 工具: ${tool}`);

            // 更新 UI 状态
            error.style.display = 'none';

            // 设置请求超时错误处理
            const controller = new AbortController();
            const timeoutId = setTimeout(() => controller.abort(), 600000); // 10分钟超时，处理大文件
            
            // 先测试服务器是否可用
            fetch(`${BASE_URL}/`, { 
                method: 'GET',
                mode: 'cors'
            })
            .then(response => {
                if (response.ok) {
                    log('服务器连接正常，开始上传文件...', 'info');
                    sendMainRequest();
                } else {
                    throw new Error('服务器状态异常');
                }
            })
            .catch(err => {
                log('服务器连接测试失败，尝试继续上传...', 'warning');
                log(`连接测试错误: ${err.message}`, 'warning');
                // 即使连接测试失败，仍然尝试主请求
                sendMainRequest();
            });
            
            // 主请求函数
            function sendMainRequest() {
                // 发送请求
                fetch(`${BASE_URL}/process`, {
                    method: 'POST',
                    body: formData,
                    signal: controller.signal,
                    headers: {
                        'Accept': 'application/json',
                    },
                    mode: 'cors',
                    credentials: 'same-origin'
                })
                .then(response => {
                    clearTimeout(timeoutId); // 清除超时
                    
                    if (!response.ok) {
                        return response.text().then(text => {
                            throw new Error(text);
                        });
                    }
                    return response;
                })
                .then(response => {
                    log(`收到响应 - 状态: ${response.status}`);
                    
                    // 检查响应的Content-Type
                    const contentType = response.headers.get('Content-Type');
                    log(`响应内容类型: ${contentType}`);
                    
                    // 如果是下载文件的响应
                    if (contentType && (contentType.includes('application/octet-stream') || 
                                       contentType.includes('application/zip'))) {
                        log('检测到文件下载，开始下载...');
                        return response.blob().then(blob => {
                            // 创建一个临时的<a>元素用于下载
                            const url = window.URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.style.display = 'none';
                            a.href = url;
                            
                            // 从Content-Disposition头中提取文件名
                            const contentDisposition = response.headers.get('Content-Disposition');
                            let filename = '';
                            
                            if (contentDisposition) {
                                // 使用正则表达式从Content-Disposition中提取文件名
                                const matches = /filename=(.+)/.exec(contentDisposition);
                                if (matches && matches[1]) {
                                    filename = matches[1];
                                    log(`从响应头获取到文件名: ${filename}`, 'info');
                                } else {
                                    log('无法从Content-Disposition中提取文件名', 'warning');
                                }
                            }

                            // 如果没有成功获取文件名，使用时间戳生成文件名
                            if (!filename) {
                                const now = new Date();
                                const timestamp = now.getFullYear() +
                                    String(now.getMonth() + 1).padStart(2, '0') +
                                    String(now.getDate()).padStart(2, '0') + '_' +
                                    String(now.getHours()).padStart(2, '0') +
                                    String(now.getMinutes()).padStart(2, '0') +
                                    String(now.getSeconds()).padStart(2, '0');
                                
                                // 从响应头获取Content-Type来确定文件扩展名
                                const contentType = response.headers.get('Content-Type');
                                let extension = '.txt';
                                
                                if (contentType) {
                                    if (contentType.includes('application/zip')) {
                                        extension = '.zip';
                                    } else if (contentType.includes('text/plain')) {
                                        extension = '.txt';
                                    } else if (contentType.includes('application/yaml')) {
                                        extension = '.yaml';
                                    }
                                }
                                
                                filename = `output_${timestamp}${extension}`;
                                log(`使用生成的文件名: ${filename}`, 'info');
                            }
                            
                            a.download = filename;
                            
                            // 显示下载提示
                            showDownloadHelp(filename);
                            
                            document.body.appendChild(a);
                            a.click();
                            window.URL.revokeObjectURL(url);
                            log(`文件 "${filename}" 下载中...`, 'success');
                            
                            // 保存下载信息到本地存储
                            saveLastDownload(filename);
                            
                            return Promise.resolve();
                        });
                    } else {
                        // 不是下载文件的响应
                        log('处理成功，但未收到文件下载响应');
                        return Promise.resolve();
                    }
                })
                .then(() => {
                    error.style.display = 'none';
                    log('处理成功，处理好的文件位于 gui/outputs 文件夹中！');
                    log('如果没有自动下载，请查看后端日志获取详细信息');
                })
                .catch(err => {
                    clearTimeout(timeoutId); // 清除超时
                    
                    let errorMsg = err.message || '未知错误';
                    
                    // 处理特定类型的错误
                    if (err.name === 'AbortError') {
                        errorMsg = '请求超时（10分钟），服务器处理时间过长';
                    } else if (err instanceof TypeError && err.message.includes('Failed to fetch')) {
                        errorMsg = `无法连接到服务器(${BASE_URL})，请检查服务器是否运行`;
                        // 尝试提供更多调试信息
                        log('尝试连接服务器失败，请确保：', 'error');
                        log('1. Python服务器正在运行 (python new_app.py)', 'error');
                        log(`2. 服务器正在监听${window.location.port}端口`, 'error');
                        log('3. 没有防火墙阻止连接', 'error');
                        log('4. 浏览器允许跨域请求', 'error');
                    }
                    
                    log(`发生错误: ${errorMsg}`, 'error');
                    error.textContent = '错误：' + errorMsg;
                    error.style.display = 'block';
                    
                    // 添加详情按钮
                    const detailButton = document.createElement('button');
                    detailButton.textContent = '查看详情';
                    detailButton.className = 'bg-yellow-500 text-white px-4 py-2 rounded mt-2 mr-2';
                    detailButton.onclick = function() {
                        showDetailedError({
                            message: err.message,
                            name: err.name,
                            stack: err.stack,
                            type: type,
                            formData: Array.from(formData.entries())
                                .filter(pair => !pair[0].includes('file') && !pair[0].includes('zip_file'))
                                .reduce((obj, [key, value]) => {
                                    obj[key] = value;
                                    return obj;
                                }, {}),
                            server: {
                                url: `${BASE_URL}`,
                                endpoint: '/process',
                                method: 'POST'
                            }
                        });
                    };
                    error.appendChild(detailButton);
                    
                    // 添加重试按钮
                    const retryButton = document.createElement('button');
                    retryButton.textContent = '重试';
                    retryButton.className = 'bg-blue-500 text-white px-4 py-2 rounded mt-2';
                    retryButton.onclick = function() {
                        processFile(type);
                    };
                    error.appendChild(retryButton);
                });
            }
        }

        // 页面加载完成时的初始化
        window.onload = function () {
            log('页面已加载完成');
            
            // 显示上次下载的信息
            try {
                const lastDownloadStr = localStorage.getItem('lastDownload');
                if (lastDownloadStr) {
                    const lastDownload = JSON.parse(lastDownloadStr);
                    const now = new Date();
                    const timeDiff = (now.getTime() - lastDownload.timestamp) / (1000 * 60 * 60); // 小时
                    if (timeDiff < 24) { // 如果是24小时内的下载
                        // 确保时间格式是年月日格式
                        let displayTime = lastDownload.time;
                        if (!displayTime || displayTime.indexOf('年') === -1) {
                            const downloadDate = new Date(lastDownload.timestamp);
                            displayTime = downloadDate.getFullYear() + '年' + 
                                        (downloadDate.getMonth() + 1) + '月' + 
                                        downloadDate.getDate() + '日 ' + 
                                        downloadDate.getHours() + ':' + 
                                        String(downloadDate.getMinutes()).padStart(2, '0') + ':' + 
                                        downloadDate.getSeconds();
                        }
                        log(`上次下载: "${lastDownload.filename}" (${displayTime})`, 'info');
                    }
                }
                
                // 加载并显示下载历史
                updateDownloadHistory();
            } catch (e) {
                console.error('读取下载历史失败:', e);
            }
        };
        
        // 保存上次下载的信息
        function saveLastDownload(filename) {
            try {
                const now = new Date();
                const formattedTime = now.getFullYear() + '年' + 
                                     (now.getMonth() + 1) + '月' + 
                                     now.getDate() + '日 ' + 
                                     now.getHours() + ':' + 
                                     String(now.getMinutes()).padStart(2, '0') + ':' + 
                                     now.getSeconds();
                
                const downloadItem = {
                    filename: filename,
                    time: formattedTime,
                    timestamp: now.getTime()
                };
                
                // 保存最新的下载
                localStorage.setItem('lastDownload', JSON.stringify(downloadItem));
                
                // 获取历史记录
                let history = [];
                const historyStr = localStorage.getItem('downloadHistory');
                if (historyStr) {
                    history = JSON.parse(historyStr);
                }
                
                // 添加新记录到前面
                history.unshift(downloadItem);
                
                // 保留最新的10条记录
                if (history.length > 10) {
                    history = history.slice(0, 10);
                }
                
                // 保存历史记录
                localStorage.setItem('downloadHistory', JSON.stringify(history));
                
                // 更新显示
                updateDownloadHistory();
            } catch (e) {
                console.error('保存下载信息失败:', e);
            }
        }
        
        // 更新下载历史记录显示
        function updateDownloadHistory() {
            try {
                const historyStr = localStorage.getItem('downloadHistory');
                if (!historyStr) return;
                
                const history = JSON.parse(historyStr);
                if (history.length === 0) return;
                
                // 显示下载历史区域
                const downloadHistoryElem = document.getElementById('download-history');
                downloadHistoryElem.classList.remove('hidden');
                
                // 更新历史列表
                const historyListElem = document.getElementById('history-list');
                historyListElem.innerHTML = '';
                
                history.forEach(item => {
                    // 如果时间格式是时间戳，转换为格式化的日期时间
                    let displayTime = item.time;
                    if (!displayTime || displayTime.indexOf('年') === -1) {
                        const itemDate = new Date(item.timestamp);
                        displayTime = itemDate.getFullYear() + '年' + 
                                     (itemDate.getMonth() + 1) + '月' + 
                                     itemDate.getDate() + '日 ' + 
                                     itemDate.getHours() + ':' + 
                                     String(itemDate.getMinutes()).padStart(2, '0') + ':' + 
                                     itemDate.getSeconds();
                    }

                    const itemElem = document.createElement('div');
                    itemElem.className = 'border-b border-blue-200 pb-2';
                    itemElem.innerHTML = `
                        <div class="flex justify-between" style="margin: 0 10px;">
                            <span class="font-medium"  style="margin: 0 10px;">${item.filename}</span>
                            <span class="text-sm text-gray-500"  style="margin: 0 10px;">${displayTime}</span>
                        </div>
                    `;
                    historyListElem.appendChild(itemElem);
                });
            } catch (e) {
                console.error('更新下载历史失败:', e);
            }
        }
        
        // 显示下载帮助信息
        function showDownloadHelp(filename) {
            // 创建下载帮助对话框
            const helpDialog = document.createElement('div');
            helpDialog.className = 'fixed inset-0 flex items-center justify-center bg-black bg-opacity-50 z-50';
            helpDialog.innerHTML = `
                <div class="bg-white p-6 rounded-lg shadow-lg max-w-lg w-full">
                    <h3 class="text-xl font-bold mb-4">文件下载中</h3>
                    <p class="mb-4">文件 <strong>${filename}</strong> 正在下载。</p>
                    <p class="mb-4">由于浏览器安全限制，我们无法指定文件下载位置。请检查您的默认下载文件夹或浏览器下载栏。</p>
                    <p class="mb-6">提示：您可以在浏览器设置中修改默认下载位置。</p>
                    <div class="flex justify-end">
                        <button id="close-help" class="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600">我知道了</button>
                    </div>
                </div>
            `;
            
            document.body.appendChild(helpDialog);
            
            document.getElementById('close-help').addEventListener('click', function() {
                document.body.removeChild(helpDialog);
            });
            
            // 5秒后自动关闭
            setTimeout(() => {
                if (document.body.contains(helpDialog)) {
                    document.body.removeChild(helpDialog);
                }
            }, 5000);
        }
    </script>

    <footer class="mt-6 text-center">
        <a id="beian-link" href="https://beian.miit.gov.cn/" target="_blank" class="text-blue-500 hover:underline"></a>
    </footer>

    <script>
        // Fetch the text for the link from the server
        fetch('/get_beian_text')
            .then(response => response.json())
            .then(data => {
                const beianLink = document.getElementById('beian-link');
                beianLink.textContent = data.text || '备案信息';
            })
            .catch(error => {
                console.error('Failed to fetch Beian text:', error);
            });

        // Fetch the website name, title and version from the server
        fetch('/get_website_config')
            .then(response => response.json())
            .then(data => {
                document.getElementById('website-title').textContent = data.title || 'Default Title';
                document.getElementById('website-name').textContent = data.name || 'Default Name';
                document.getElementById('version-info').textContent = `后端版本 ${data.version || '未知'}`;
                // 在version-info元素的末尾添加一个显示GUI版本的元素
                const guiVersionEl = document.createElement('div');
                guiVersionEl.textContent = `GUI版本 ${GUI_VERSION}`;
                guiVersionEl.className = 'text-lg text-gray-600 mt-1';
                document.getElementById('version-info').appendChild(guiVersionEl);
            })
            .catch(error => {
                console.error('Failed to fetch website config:', error);
            });
    </script>
</body>
</html>