<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>会话导出系统</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <div class="container">
        <header class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h1>会话导出系统</h1>
                </div>
                <div class="header-right">
                    <span class="doctor-name">{{ doctor_name }}</span>
                    <button id="logoutBtn" class="btn btn-ghost">退出</button>
                </div>
            </div>
            <div class="session-count" id="sessionCount">正在加载...</div>
        </header>

        <div class="actions-bar">
            <button id="exportSelected" class="btn btn-primary" disabled>
                <span>导出选中</span>
                <span id="selectedCount" class="count-badge" style="display: none;">0</span>
            </button>
            <button id="selectAll" class="btn btn-secondary">全选</button>
            <button id="deselectAll" class="btn btn-secondary">取消全选</button>
        </div>

        <div id="sessionsGrid" class="sessions-grid">
            <div class="loading">
                <div class="spinner"></div>
                <p>加载中</p>
            </div>
        </div>
    </div>

    <script src="/static/script.js"></script>
    <script>
        let sessions = [];
        let selectedSessions = new Set();

        window.addEventListener('DOMContentLoaded', () => {
            loadSessions();
            setupEventListeners();
        });

        function setupEventListeners() {
            document.getElementById('exportSelected').addEventListener('click', exportMultiple);
            document.getElementById('selectAll').addEventListener('click', selectAll);
            document.getElementById('deselectAll').addEventListener('click', deselectAll);
            document.getElementById('logoutBtn').addEventListener('click', logout);
        }

        async function loadSessions() {
            try {
                const response = await fetch('/api/sessions? page_size=100');

                if (response.status === 401) {
                    window.location.href = '/login';
                    return;
                }

                const data = await response.json();
                sessions = data.sessions;

                // Update count
                const countText = sessions.length === 0 ? '暂无会话' : `共 ${sessions.length} 个会话`;
                document.getElementById('sessionCount').textContent = countText;

                renderSessions();
            } catch (error) {
                console.error('Failed to load sessions:', error);
                document.getElementById('sessionCount').textContent = '加载失败';
                document.getElementById('sessionsGrid').innerHTML =
                    '<div class="error-state"><p>加载失败</p></div>';
            }
        }

        function renderSessions() {
            const grid = document.getElementById('sessionsGrid');

            if (sessions.length === 0) {
                grid.innerHTML = '<div class="empty-state"><p>暂无会话记录</p></div>';
                return;
            }

            grid.innerHTML = sessions.map((session, index) => `
                <div class="session-card" style="animation-delay: ${index * 0.03}s">
                    <div class="session-header">
                        <div class="checkbox-wrapper">
                            <input
                                type="checkbox"
                                class="checkbox session-checkbox"
                                data-session-id="${session.id}"
                                id="checkbox-${session.id}"
                                onchange="toggleSession('${session.id}')">
                            <label for="checkbox-${session.id}" class="checkbox-custom"></label>
                        </div>
                        <div class="session-info">
                            <h3>${escapeHtml(session.patient_name || '未知患者')}</h3>
                            ${session.clinic_number ?
                                `<div class="session-meta">门诊号: ${escapeHtml(session.clinic_number)}</div>` : ''}
                            ${session.medical_record_number ?
                                `<div class="session-meta">病历号: ${escapeHtml(session.medical_record_number)}</div>` : ''}
                            ${session.diagnosis ?
                                `<div class="session-meta">诊断: ${escapeHtml(session.diagnosis)}</div>` : ''}
                            <div class="session-meta">${formatDate(session.created_at)}</div>
                            <span class="status-badge status-${session.status.toLowerCase().replace('_', '-')}">
                                ${getStatusText(session.status)}
                            </span>
                        </div>
                    </div>
                    <button class="export-btn" onclick="exportSingle('${session.id}')">
                        导出
                    </button>
                </div>
            `).join('');
        }

        function toggleSession(sessionId) {
            if (selectedSessions.has(sessionId)) {
                selectedSessions.delete(sessionId);
            } else {
                selectedSessions.add(sessionId);
            }
            updateSelectedCount();
        }

        function selectAll() {
            sessions.forEach(session => {
                selectedSessions.add(session.id);
                const checkbox = document.querySelector(`[data-session-id="${session.id}"]`);
                if (checkbox) checkbox.checked = true;
            });
            updateSelectedCount();
        }

        function deselectAll() {
            selectedSessions.clear();
            document.querySelectorAll('.session-checkbox').forEach(cb => cb.checked = false);
            updateSelectedCount();
        }

        function updateSelectedCount() {
            const count = selectedSessions.size;
            const countBadge = document.getElementById('selectedCount');
            const exportBtn = document.getElementById('exportSelected');

            if (! countBadge || !exportBtn) return;

            if (count > 0) {
                countBadge.textContent = count;
                countBadge.style.display = 'flex';
                exportBtn.disabled = false;
            } else {
                countBadge.style.display = 'none';
                exportBtn.disabled = true;
            }
        }

        async function exportSingle(sessionId) {
            window.location.href = `/api/sessions/${sessionId}/export`;
        }

        async function exportMultiple() {
            if (selectedSessions.size === 0) return;

            const btn = document.getElementById('exportSelected');
            const originalHTML = btn.innerHTML;
            btn.disabled = true;
            btn.innerHTML = '<span>导出中...</span>';

            try {
                const response = await fetch('/api/sessions/export-multiple', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        session_ids: Array.from(selectedSessions)
                    })
                });

                if (! response.ok) {
                    const error = await response.json();
                    throw new Error(error.error || 'Export failed');
                }

                const blob = await response.blob();
                downloadBlob(blob, `sessions_export_${selectedSessions.size}.zip`);

                deselectAll();
            } catch (error) {
                console.error('Export failed:', error);
                alert('导出失败: ' + error.message);
            } finally {
                btn.disabled = false;
                btn.innerHTML = originalHTML;
                updateSelectedCount();
            }
        }

        async function logout() {
            try {
                await fetch('/api/logout', { method: 'POST' });
            } catch (error) {
                console.error('Logout failed:', error);
            } finally {
                window.location.href = '/login';
            }
        }

        function getStatusText(status) {
            const map = {
                'COMPLETED': 'completed',
                'IN_PROGRESS': 'in_progress',
                'DRAFT': 'draft',
                'CANCELLED': 'cancelled'
            };
            return map[status] || status.toLowerCase();
        }
    </script>
</body>
</html>
