<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Excel 预览 - {{ filename }}</title>
    <script src="/static/lib/xlsx.full.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            background-color: #f8f9fa;
            min-height: 100vh;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        .header a {
            color: white;
            text-decoration: none;
            padding: 8px 16px;
            background: rgba(255,255,255,0.2);
            border-radius: 6px;
            font-size: 14px;
        }
        .header a:hover {
            background: rgba(255,255,255,0.3);
        }
        .filename {
            font-size: 16px;
            font-weight: 500;
        }
        .spreadsheet-container {
            padding: 20px;
            overflow: auto;
        }
        .sheet-tabs {
            display: flex;
            gap: 5px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }
        .sheet-tab {
            padding: 8px 16px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 6px 6px 0 0;
            cursor: pointer;
            font-size: 14px;
        }
        .sheet-tab.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        .spreadsheet {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: auto;
        }
        table {
            border-collapse: collapse;
            width: 100%;
            min-width: 600px;
        }
        td, th {
            border: 1px solid #e0e0e0;
            padding: 10px 12px;
            font-size: 13px;
            white-space: nowrap;
        }
        th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 500;
            position: sticky;
            top: 0;
            z-index: 10;
        }
        tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        tr:hover {
            background-color: #e8f4ff;
        }
        .cell-number {
            text-align: right;
            font-family: 'Consolas', monospace;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        .error {
            text-align: center;
            padding: 40px;
            color: #cf222e;
            background: #ffebe9;
            border-radius: 8px;
            margin: 20px;
        }
        @media (max-width: 768px) {
            .header {
                padding: 10px;
            }
            .spreadsheet-container {
                padding: 10px;
            }
            td, th {
                padding: 6px 8px;
                font-size: 12px;
            }
        }
    </style>
</head>
<body>
    <div class="header">
        <a href="{{ url_for('browser.browse', path=get_relative_path(current_dir)) }}">← 返回目录</a>
        <span class="filename">{{ filename }}</span>
        <a href="{{ url_for('file.download_file', path=file_path) }}">📥 下载</a>
    </div>
    
    <div class="spreadsheet-container">
        <div id="sheet-tabs" class="sheet-tabs"></div>
        <div class="spreadsheet">
            <div id="spreadsheet-content" class="loading">正在加载 Excel 文件...</div>
        </div>
    </div>

    <script>
        const filePath = '{{ file_path }}';
        let workbook = null;
        let currentSheet = 0;

        // 加载 Excel 文件
        fetch('/serve/' + encodeURIComponent(filePath))
            .then(response => {
                if (!response.ok) throw new Error('文件加载失败');
                return response.arrayBuffer();
            })
            .then(data => {
                workbook = XLSX.read(data, { type: 'array' });
                renderSheetTabs();
                renderSheet(0);
            })
            .catch(error => {
                document.getElementById('spreadsheet-content').innerHTML = 
                    '<div class="error">加载失败: ' + error.message + '</div>';
            });

        // 渲染工作表标签
        function renderSheetTabs() {
            const tabsContainer = document.getElementById('sheet-tabs');
            tabsContainer.innerHTML = '';
            
            workbook.SheetNames.forEach((name, index) => {
                const tab = document.createElement('div');
                tab.className = 'sheet-tab' + (index === currentSheet ? ' active' : '');
                tab.textContent = name;
                tab.onclick = () => switchSheet(index);
                tabsContainer.appendChild(tab);
            });
        }

        // 切换工作表
        function switchSheet(index) {
            currentSheet = index;
            renderSheetTabs();
            renderSheet(index);
        }

        // 渲染工作表内容
        function renderSheet(sheetIndex) {
            const sheet = workbook.Sheets[workbook.SheetNames[sheetIndex]];
            const container = document.getElementById('spreadsheet-content');
            
            // 获取数据范围
            const range = XLSX.utils.decode_range(sheet['!ref'] || 'A1');
            
            let html = '<table>';
            
            // 生成表头
            html += '<thead><tr><th>#</th>';
            for (let c = range.s.c; c <= range.e.c; c++) {
                const cell = sheet[XLSX.utils.encode_cell({ r: 0, c: c })];
                const colName = XLSX.utils.encode_col(c);
                html += `<th>${colName}</th>`;
            }
            html += '</tr></thead>';
            
            // 生成数据行
            html += '<tbody>';
            for (let r = range.s.r; r <= range.e.r; r++) {
                html += `<tr><td class="cell-number">${r + 1}</td>`;
                for (let c = range.s.c; c <= range.e.c; c++) {
                    const cell = sheet[XLSX.utils.encode_cell({ r: r, c: c })];
                    let value = cell ? (cell.v || '') : '';
                    
                    // 格式化数字
                    if (typeof value === 'number') {
                        if (Math.abs(value) >= 1000000) {
                            value = value.toLocaleString('en-US', { maximumFractionDigits: 2 });
                        } else if (Math.abs(value) < 0.01 && value !== 0) {
                            value = value.toPrecision(4);
                        }
                    }
                    
                    html += `<td>${escapeHtml(String(value))}</td>`;
                }
                html += '</tr>';
            }
            html += '</tbody></table>';
            
            container.innerHTML = html;
        }

        // HTML 转义
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    </script>
</body>
</html>
