<?php
// 包含认证检查
require_once 'includes/auth.php';
checkLogin();
?>

<!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="assets/css/style.css">
    <link rel="stylesheet" href="assets/css/vendor/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/vendor/font-awesome.min.css">
    <script src="assets/js/vendor/bootstrap.bundle.min.js"></script>
    <script src="assets/js/vendor/html2pdf.bundle.min.js"></script>

    <style>
        .photo-selection-container {
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 1rem;
            background-color: #f8f9fa;
        }

        .photo-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 0.75rem;
            max-height: 300px;
            overflow-y: auto;
            padding: 0.5rem;
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 0.25rem;
        }

        .photo-item {
            position: relative;
        }

        .photo-checkbox {
            position: relative;
            width: 100%;
        }

        .photo-checkbox input[type="checkbox"] {
            position: absolute;
            top: 5px;
            right: 5px;
            z-index: 2;
            width: 18px;
            height: 18px;
        }

        .photo-label {
            display: block;
            cursor: pointer;
            position: relative;
            border-radius: 0.25rem;
            overflow: hidden;
            transition: all 0.2s ease;
        }

        .photo-label:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.15);
        }

        .photo-thumbnail {
            width: 100%;
            height: 80px;
            object-fit: cover;
            border-radius: 0.25rem;
            display: block;
        }

        .photo-info {
            padding: 0.25rem;
            background: rgba(0,0,0,0.7);
            color: white;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            font-size: 0.75rem;
        }

        .photo-name {
            display: block;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .photo-date {
            display: block;
            opacity: 0.8;
        }

        .photo-selection-controls {
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
        }

        /* 选中状态样式 */
        .photo-checkbox input[type="checkbox"]:checked + .photo-label {
            box-shadow: 0 0 0 2px #007bff;
        }

        .photo-checkbox input[type="checkbox"]:checked + .photo-label::after {
            content: '';
            position: absolute;
            top: 5px;
            right: 5px;
            width: 20px;
            height: 20px;
            background: rgba(0,123,255,0.9);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 12px;
        }

        .photo-checkbox input[type="checkbox"]:checked + .photo-label::after {
            content: '✓';
            font-weight: bold;
        }

        /* 照片确认模态框样式 */
        .selected-photo-thumbnail {
            width: 50px;
            height: 50px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid #dee2e6;
        }

        .selected-photo-item {
            padding: 8px;
            border-radius: 6px;
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
        }

        .stats-info p {
            margin-bottom: 8px;
            font-size: 14px;
        }

        /* 编辑影像选择样式 */
        .edit-image-item {
            transition: all 0.2s ease;
        }

        .edit-image-item:hover {
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transform: translateY(-1px);
        }

        .edit-image-item.bg-light {
            background-color: #f8f9fa !important;
            border-color: #007bff !important;
        }

        .edit-image-grid {
            scrollbar-width: thin;
            scrollbar-color: #dee2e6 #f8f9fa;
        }

        .edit-image-grid::-webkit-scrollbar {
            width: 6px;
        }

        .edit-image-grid::-webkit-scrollbar-track {
            background: #f8f9fa;
            border-radius: 3px;
        }

        .edit-image-grid::-webkit-scrollbar-thumb {
            background: #dee2e6;
            border-radius: 3px;
        }

        .edit-image-grid::-webkit-scrollbar-thumb:hover {
            background: #adb5bd;
        }

        /* PDF导出专用样式 */
        @media print, (max-width: 0) {
            .report-content {
                font-family: 'Microsoft YaHei', 'SimHei', sans-serif !important;
                font-size: 14px !important;
                line-height: 1.6 !important;
                color: #333 !important;
                background: white !important;
            }

            .report-content h2, .report-content h3 {
                color: #333 !important;
                page-break-after: avoid;
            }

            .report-content table {
                page-break-inside: avoid;
            }

            .report-content img {
                max-width: 100% !important;
                height: auto !important;
                page-break-inside: avoid;
            }

            .image-grid-print {
                display: grid !important;
                grid-template-columns: repeat(2, 1fr) !important;
                gap: 15px !important;
                margin: 20px 0 !important;
            }

            .image-item-print {
                text-align: center !important;
                border: 1px solid #dee2e6 !important;
                border-radius: 4px !important;
                padding: 8px !important;
                page-break-inside: avoid;
            }
        }
    </style>
    <script src="assets/js/vendor/jquery.min.js"></script>
</head>
<body>
    <!-- Modern Dashboard Layout -->
    <div class="dashboard-container">
        <!-- Sidebar -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <div class="sidebar-logo">
                    <i class="fas fa-tooth"></i>
                    <span>口腔检查系统</span>
                </div>
                <button class="sidebar-toggle" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
            </div>

            <ul class="sidebar-menu">
                <li class="menu-item">
                    <a href="index.php" class="menu-link">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>仪表板</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="patients.php" class="menu-link">
                        <i class="fas fa-users"></i>
                        <span>患者管理</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="capture.php" class="menu-link">
                        <i class="fas fa-camera"></i>
                        <span>影像采集</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="comparison.php" class="menu-link">
                        <i class="fas fa-exchange-alt"></i>
                        <span>影像对比</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="edit.php" class="menu-link">
                        <i class="fas fa-edit"></i>
                        <span>影像编辑</span>
                    </a>
                </li>
                <li class="menu-item active">
                    <a href="reports.php" class="menu-link">
                        <i class="fas fa-file-medical"></i>
                        <span>报告管理</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="settings.php" class="menu-link">
                        <i class="fas fa-cog"></i>
                        <span>系统设置</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="help.php" class="menu-link">
                        <i class="fas fa-question-circle"></i>
                        <span>帮助中心</span>
                    </a>
                </li>
            </ul>
        </nav>

        <!-- Sidebar Overlay for Mobile -->
        <div class="sidebar-overlay"></div>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Header -->
            <header class="top-header">
                <div class="header-left">
                    <h1 class="page-title">报告管理</h1>
                </div>
                <div class="header-right">
                    <div class="header-notifications">
                        <button class="notification-btn">
                            <i class="fas fa-bell"></i>
                            <span class="notification-badge">3</span>
                        </button>
                    </div>
                    <div class="header-user">
                        <div class="user-avatar">
                            <i class="fas fa-user"></i>
                        </div>
                        <span class="user-name">管理员</span>
                    </div>
                </div>
            </header>

            <!-- Reports Content -->
            <div class="content-wrapper">

                <!-- 报告生成区域 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5>生成报告</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <label for="report-patient-select" class="form-label">选择患者</label>
                                <div class="input-group">
                                    <input type="text" id="report-patient-search" class="form-control" placeholder="搜索患者姓名、电话或身份证号...">
                                    <select id="report-patient-select" class="form-select">
                                        <option value="">请选择患者...</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label for="report-template-select" class="form-label">报告模板</label>
                                <select id="report-template-select" class="form-select">
                                    <option value="standard">标准报告</option>
                                    <option value="detailed">详细报告</option>
                                    <option value="simple">简化报告</option>
                                    <option value="custom">自定义模板</option>
                                </select>
                            </div>
                            <div class="col-md-8">
                                <!-- 照片选择区域 -->
                                <div id="photo-selection-area" class="photo-selection-container" style="display: none;">
                                    <label class="form-label">选择包含的照片</label>
                                    <div id="patient-photos" class="photo-grid">
                                        <!-- 患者照片将在这里显示 -->
                                    </div>
                                    <div class="photo-selection-controls mt-2">
                                        <button type="button" class="btn btn-sm btn-outline-primary me-2" onclick="selectAllPhotos()">全选</button>
                                        <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="clearPhotoSelection()">清空选择</button>
                                        <small class="text-muted">
                                            已选择 <span id="selected-photos-count">0</span> 张照片
                                            <span class="text-info">(AI分析最多选择4张)</span>
                                        </small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">导出格式</label>
                                <div class="btn-group w-100" role="group">
                                    <input type="radio" class="btn-check" name="export-format" id="format-pdf" value="pdf" checked>
                                    <label class="btn btn-outline-primary btn-sm" for="format-pdf">PDF</label>
                                    <input type="radio" class="btn-check" name="export-format" id="format-html" value="html">
                                    <label class="btn btn-outline-primary btn-sm" for="format-html">HTML</label>
                                    <input type="radio" class="btn-check" name="export-format" id="format-word" value="word">
                                    <label class="btn btn-outline-primary btn-sm" for="format-word">Word</label>
                                </div>
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <button class="btn btn-primary me-2" onclick="generateReport()">生成报告</button>
                                <button class="btn btn-outline-warning me-2" onclick="aiAnalysis()" id="ai-analysis-btn">
                                    <i class="fas fa-robot me-1"></i>AI分析
                                </button>
                                <button class="btn btn-outline-info me-2" onclick="previewReport()">预览</button>
                                <button class="btn btn-outline-success me-2" onclick="manageTemplates()">模板管理</button>
                                <button class="btn btn-secondary" onclick="clearReport()">清空</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 排行数据区域 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5>数据统计排行</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="stats-ranking">
                                    <h6>常见病情排行</h6>
                                    <div id="condition-ranking" class="ranking-list">
                                        <p class="text-muted text-center">加载中...</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="stats-ranking">
                                    <h6>患者影像排行</h6>
                                    <div id="patient-image-ranking" class="ranking-list">
                                        <p class="text-muted text-center">加载中...</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="stats-ranking">
                                    <h6>就诊频率排行</h6>
                                    <div id="patient-visit-ranking" class="ranking-list">
                                        <p class="text-muted text-center">加载中...</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="mt-3 text-center">
                            <button class="btn btn-sm btn-outline-primary" onclick="refreshRankings()">
                                <i class="fas fa-sync"></i> 刷新数据
                            </button>
                        </div>
                    </div>
                </div>

                <!-- 报告预览区域 -->
                <div id="report-preview" class="card" style="display: none;">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">报告预览</h5>
                        <div>
                            <button class="btn btn-sm btn-outline-primary me-2" onclick="editReport()">编辑报告</button>
                            <button class="btn btn-sm btn-outline-success me-2" onclick="printReport()">打印报告</button>
                            <button class="btn btn-sm btn-outline-info me-2" onclick="exportReport('pdf')">导出PDF</button>
                            <button class="btn btn-sm btn-outline-secondary" onclick="saveReport()">保存报告</button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="report-content" class="report-content">
                            <!-- 报告内容将在这里显示 -->
                        </div>
                    </div>

                    <div>
                            <button class="btn btn-sm btn-outline-primary me-2" onclick="editReport()">编辑报告</button>
                            <button class="btn btn-sm btn-outline-success me-2" onclick="printReport()">打印报告</button>
                            <button class="btn btn-sm btn-outline-info me-2" onclick="exportReport('pdf')">导出PDF</button>
                            <button class="btn btn-sm btn-outline-secondary" onclick="saveReport()">保存报告</button>
                        </div>
                </div>

                <!-- 报告历史 -->
                <div class="card">
                    <div class="card-header">
                        <h5>报告历史</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped" id="reports-table">
                                <thead>
                                    <tr>
                                        <th>患者姓名</th>
                                        <th>报告类型</th>
                                        <th>生成时间</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="reports-list">
                                    <tr>
                                        <td colspan="5" class="text-center text-muted">暂无报告记录</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑报告模态框 -->
    <div class="modal fade" id="editReportModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑报告</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">牙齿病情选择</label>
                        <div id="dental-conditions" class="border rounded p-3">
                            <div class="text-center">
                                <div class="spinner-border spinner-border-sm" role="status"></div>
                                加载病情数据中...
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="edit-diagnosis" class="form-label">诊断结论</label>
                        <textarea id="edit-diagnosis" class="form-control" rows="4" placeholder="请输入详细的诊断结论，或让系统根据选择的病情自动生成..."></textarea>
                        <div class="mt-2">
                            <button type="button" class="btn btn-sm btn-outline-info" onclick="generateDiagnosisForEdit()">
                                <i class="fas fa-magic"></i> 根据病情自动生成
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="edit-treatment" class="form-label">治疗建议</label>
                        <textarea id="edit-treatment" class="form-control" rows="4" placeholder="请输入治疗建议..."></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="edit-notes" class="form-label">备注</label>
                        <textarea id="edit-notes" class="form-control" rows="3" placeholder="其他备注信息..."></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">选择包含的影像</label>
                        <div id="image-selection" class="border rounded p-3">
                            <p class="text-muted">影像选择功能开发中...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateReport()">保存修改</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 模板管理模态框 -->
    <div class="modal fade" id="templateManagerModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">报告模板管理</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4">
                            <h6>模板列表</h6>
                            <div id="template-list" class="list-group">
                                <!-- 模板列表将在这里显示 -->
                            </div>
                            <button class="btn btn-primary btn-sm w-100 mt-2" onclick="createNewTemplate()">
                                <i class="fas fa-plus"></i> 创建新模板
                            </button>
                        </div>
                        <div class="col-md-8">
                            <h6>模板编辑器</h6>
                            <div id="template-editor" class="border rounded p-3" style="min-height: 400px;">
                                <div class="text-center text-muted">
                                    <p>请先选择或创建模板</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="saveTemplate()">保存模板</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 照片确认模态框 -->
    <div class="modal fade" id="photoConfirmationModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-images me-2"></i>
                        生成报告 - 患者：<span id="confirmation-patient-name"></span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="confirmation-message" class="mb-3">
                        <!-- 确认消息将在这里显示 -->
                    </div>

                    <div class="row">
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">
                                        <i class="fas fa-check-circle text-success me-2"></i>
                                        已选择照片 (<span id="confirmation-selected-count">0</span>)
                                    </h6>
                                </div>
                                <div class="card-body" style="max-height: 300px; overflow-y: auto;">
                                    <div id="selected-photos-list">
                                        <!-- 选中的照片列表将在这里显示 -->
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">
                                        <i class="fas fa-info-circle text-info me-2"></i>
                                        统计信息
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="stats-info">
                                        <p><strong>患者总照片数：</strong><span id="total-photos-count">0</span> 张</p>
                                        <p><strong>报告包含照片：</strong><span id="report-photos-count">0</span> 张</p>
                                        <p><strong>报告模板：</strong><span id="report-template-name">-</span></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">
                                        <i class="fas fa-tooth me-2"></i>
                                        牙齿病情选择 <span class="text-danger">*</span>
                                    </h6>
                                </div>
                                <div class="card-body" style="max-height: 300px; overflow-y: auto;">
                                    <div id="confirmation-dental-conditions">
                                        <!-- 牙齿病情选择将在这里显示 -->
                                    </div>
                                    <div id="condition-validation-message" class="mt-2 text-danger" style="display: none;">
                                        <small><i class="fas fa-exclamation-triangle me-1"></i>请选择至少一种牙齿病情</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="alert alert-light mt-3">
                        <i class="fas fa-lightbulb text-warning me-2"></i>
                        <strong>提示：</strong>请选择牙齿病情后生成报告。报告生成后将自动保存，您可以在编辑报告中修改诊断结论和治疗建议。
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="fas fa-arrow-left me-2"></i>返回选择
                    </button>
                    <button type="button" class="btn btn-primary" onclick="confirmGenerateReport()">
                        <i class="fas fa-file-medical me-2"></i>生成并保存报告
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 报告预览模态框 -->
    <div class="modal fade" id="reportPreviewModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">报告预览</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="report-preview-content" style="max-height: 600px; overflow-y: auto;">
                        <!-- 报告预览内容将在这里显示 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-success" onclick="confirmPrint()">
                        <i class="fas fa-print"></i> 确认打印
                    </button>
                    <button type="button" class="btn btn-primary" onclick="exportReport()">
                        <i class="fas fa-download"></i> 导出
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="assets/js/main.js"></script>
    <script>
        let currentReport = null;
        let currentPatient = null;
        let selectedPhotos = []; // 选中的照片ID数组

        // 为报告页面加载患者选择器（包含统计数据）
        function loadPatientSelectorsForReports() {
            apiRequest('api/patients.php?action=list&limit=1000')
                .then(data => {
                    if (data.success && data.data && data.data.patients) {
                        const select = document.getElementById('report-patient-select');
                        if (select) {
                            select.innerHTML = '<option value="">请选择患者...</option>';
                            data.data.patients.forEach(patient => {
                                const option = document.createElement('option');
                                option.value = patient.id;
                                option.textContent = `${patient.name} (${patient.age}岁, ${patient.gender === 'male' ? '男' : '女'})`;

                                // 设置默认统计数据，后续选择时会更新
                                option.dataset.stats = JSON.stringify({images: 0, medical_records: 0, appointments: 0});

                                select.appendChild(option);
                            });
                        }
                    } else {
                        console.warn('患者数据加载失败或数据格式不正确');
                    }
                })
                .catch(error => {
                    console.error('加载患者列表失败:', error);
                });
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadPatientSelectorsForReports();
            loadReportsHistory();
            loadRankings(); // 加载排行数据

            // 绑定患者选择事件
            document.getElementById('report-patient-select').addEventListener('change', function() {
                currentPatient = this.value;
                if (currentPatient) {
                    showPatientStats(currentPatient, this);
                } else {
                    clearPatientStats();
                }
            });

            // 绑定患者搜索事件
            document.getElementById('report-patient-search').addEventListener('input', function() {
                searchPatients(this.value, 'report-patient-select');
            });

            // 为搜索框添加自动清空功能
            const reportSearchInput = document.getElementById('report-patient-search');
            if (reportSearchInput) {
                reportSearchInput.addEventListener('focus', function() {
                    clearSearchPlaceholder(this);
                });
            }
        });

        // 清空搜索框默认文字
        function clearSearchPlaceholder(input) {
            // 如果输入框的值等于占位符文字（表示用户还没有输入内容），则清空
            if (input.value === input.placeholder || input.value.trim() === '') {
                input.value = '';
            }
        }

        // AI分析功能
        async function aiAnalysis() {
            const patientId = document.getElementById('report-patient-select').value;

            if (!patientId) {
                showMessage('请先选择患者', 'warning');
                return;
            }

            // 检查是否选择了照片
            if (selectedPhotos.length === 0) {
                showMessage('请先选择要分析的照片（最多4张）', 'warning');
                return;
            }

            // 检查选择的照片数量是否超过4张
            if (selectedPhotos.length > 4) {
                showMessage('最多只能选择4张照片进行AI分析', 'warning');
                return;
            }

            // 获取患者信息和照片
            try {
                showMessage(`正在对${selectedPhotos.length}张照片进行AI分析，请稍候...`, 'info');

                // 禁用按钮
                const aiBtn = document.getElementById('ai-analysis-btn');
                aiBtn.disabled = true;
                aiBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>分析中...';

                // 获取患者信息
                const patientResponse = await apiRequest(`api/patients.php?action=get&id=${patientId}`);
                const patient = patientResponse.patient;

                // 获取患者所有照片
                const imagesResponse = await apiRequest(`api/images.php?action=list&patient_id=${patientId}`);
                const allImages = imagesResponse.images || [];

                // 从所有照片中筛选出用户选中的照片
                const selectedImages = allImages.filter(img => {
                    const imgId = parseInt(img.id);
                    return selectedPhotos.includes(imgId) || selectedPhotos.includes(img.id.toString());
                });

                if (selectedImages.length === 0) {
                    showMessage('选择的照片未找到，请重新选择', 'warning');
                    aiBtn.disabled = false;
                    aiBtn.innerHTML = '<i class="fas fa-robot me-1"></i>AI分析';
                    return;
                }

                // 使用用户选中的照片进行AI分析
                const oralImages = selectedImages;

                // 构建AI分析提示
                const analysisPrompt = buildAIAnalysisPrompt(patient, oralImages);

                // 调用DeepSeek API
                const aiResponse = await callDeepSeekAPI(analysisPrompt);

                if (aiResponse.success) {
                    // 解析AI响应并生成报告
                    await generateAIReport(patient, oralImages, aiResponse.data);
                    showMessage('AI分析完成，报告已生成', 'success');
                } else {
                    showMessage('AI分析失败：' + aiResponse.error, 'danger');
                }

            } catch (error) {
                console.error('AI分析出错:', error);
                showMessage('AI分析过程中发生错误，请重试', 'danger');
            } finally {
                // 恢复按钮状态
                const aiBtn = document.getElementById('ai-analysis-btn');
                aiBtn.disabled = false;
                aiBtn.innerHTML = '<i class="fas fa-robot me-1"></i>AI分析';
            }
        }

        // 构建AI分析提示
        function buildAIAnalysisPrompt(patient, images) {
            const age = patient.age;
            const gender = patient.gender === 'male' ? '男' : '女';
            const imageCount = images.length;

            return `请作为一名专业的口腔科医生，分析以下患者信息并生成详细的口腔检查报告。

患者基本信息：
- 姓名：${patient.name}
- 年龄：${age}岁
- 性别：${gender}
- 检查照片数量：${imageCount}张

请基于患者年龄和口腔照片，分析可能存在的牙齿问题，包括但不限于：
1. 龋齿（Caries）
2. 牙周炎（Periodontitis）
3. 牙龈炎（Gingivitis）
4. 牙齿裂纹（Cracks）
5. 错牙合（Malocclusion）
6. 牙齿敏感（Sensitivity）
7. 其他牙齿问题

请提供：
1. 详细的诊断结论
2. 具体的治疗建议
3. 预防措施建议

请用专业、详细的医学术语书写报告。`;
        }

        // 调用DeepSeek API
        async function callDeepSeekAPI(prompt) {
            const apiUrl = 'https://api.deepseek.com/chat/completions';
            const apiKey = 'sk-97fa8cb5c2e34750af339f2307b49e13';

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${apiKey}`
                    },
                    body: JSON.stringify({
                        model: 'deepseek-chat',
                        messages: [
                            {
                                role: 'system',
                                content: '你是一位专业的口腔科医生，擅长分析患者的口腔检查结果并提供准确的诊断和治疗建议。'
                            },
                            {
                                role: 'user',
                                content: prompt
                            }
                        ],
                        temperature: 0.7,
                        max_tokens: 2000
                    })
                });

                if (!response.ok) {
                    throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
                }

                const data = await response.json();

                if (data.choices && data.choices[0] && data.choices[0].message) {
                    return {
                        success: true,
                        data: data.choices[0].message.content
                    };
                } else {
                    throw new Error('API响应格式错误');
                }

            } catch (error) {
                console.error('DeepSeek API调用失败:', error);
                return {
                    success: false,
                    error: error.message
                };
            }
        }

        // 生成AI报告
        async function generateAIReport(patient, images, aiAnalysis) {
            try {
                // 解析AI分析结果
                const diagnosis = extractDiagnosisFromAI(aiAnalysis);
                const treatment = extractTreatmentFromAI(aiAnalysis);

                // 获取设置
                const settingsResponse = await apiRequest('api/settings.php?action=get');
                const settings = settingsResponse.settings || {};

                // 构建报告数据
                currentReport = {
                    patient: patient,
                    images: images,
                    settings: settings,
                    template: 'ai-generated',
                    dental_conditions: [], // AI分析后可手动添加
                    diagnosis: diagnosis,
                    treatment: treatment,
                    notes: '本报告由AI智能分析生成，仅供临床参考',
                    created_at: new Date().toISOString()
                };

                // 显示报告
                displayReport(currentReport);
                document.getElementById('report-preview').style.display = 'block';

                // 自动保存
                saveReport();

            } catch (error) {
                console.error('生成AI报告失败:', error);
                throw error;
            }
        }

        // 从AI响应中提取诊断结论
        function extractDiagnosisFromAI(aiResponse) {
            // 简单的文本解析，实际可以更复杂
            const lines = aiResponse.split('\n');
            let diagnosis = '';

            // 查找诊断相关的内容
            for (const line of lines) {
                if (line.includes('诊断') || line.includes('结论') || line.includes('检查结果')) {
                    diagnosis += line + '\n';
                }
            }

            // 如果没找到特定内容，使用整个响应
            if (!diagnosis.trim()) {
                diagnosis = aiResponse;
            }

            return diagnosis.trim();
        }

        // 从AI响应中提取治疗建议
        function extractTreatmentFromAI(aiResponse) {
            // 简单的文本解析，实际可以更复杂
            const lines = aiResponse.split('\n');
            let treatment = '';

            // 查找治疗相关的内容
            for (const line of lines) {
                if (line.includes('治疗') || line.includes('建议') || line.includes('措施')) {
                    treatment += line + '\n';
                }
            }

            // 如果没找到特定内容，尝试分割响应
            if (!treatment.trim()) {
                const parts = aiResponse.split(/[2-9]?\./);
                treatment = parts.length > 1 ? parts.slice(1).join('\n') : aiResponse;
            }

            return treatment.trim();
        }

        // 生成报告
        function generateReport() {
            const patientId = document.getElementById('report-patient-select').value;
            const template = document.getElementById('report-template-select').value;

            if (!patientId) {
                showMessage('请先选择患者', 'warning');
                return;
            }

            // 如果有选中的照片，显示确认模态框；否则直接生成报告
            if (selectedPhotos.length > 0) {
                showPhotoConfirmationModal(patientId, template);
            } else {
                // 没有选择特定照片，直接生成包含所有照片的报告
                generateReportDirect(patientId, template);
            }
        }

        // 显示照片确认模态框
        function showPhotoConfirmationModal(patientId, template) {
            const modal = document.getElementById('photoConfirmationModal');
            const selectedPhotosList = document.getElementById('selected-photos-list');
            const totalPhotosCount = document.getElementById('total-photos-count');

            // 获取患者信息和照片
            Promise.all([
                apiRequest(`api/patients.php?action=get&id=${patientId}`),
                apiRequest(`api/images.php?action=list&patient_id=${patientId}`)
            ]).then(([patientData, imageData]) => {
                const patient = patientData.patient;
                const allImages = imageData.images;

                // 更新模态框标题
                document.getElementById('confirmation-patient-name').textContent = patient.name;

                // 显示照片统计信息
                totalPhotosCount.textContent = allImages.length;

                // 显示选中的照片列表
                if (selectedPhotos.length > 0) {
                    // 确保ID类型匹配
                    const selectedImages = allImages.filter(img => {
                        const imgId = parseInt(img.id);
                        return selectedPhotos.includes(imgId) || selectedPhotos.includes(img.id.toString());
                    });

                    if (selectedImages.length > 0) {
                        const html = selectedImages.map(image => `
                            <div class="selected-photo-item d-flex align-items-center mb-2">
                                <img src="${image.file_path}" alt="${image.original_name}" class="selected-photo-thumbnail me-2">
                                <div>
                                    <small class="fw-bold">${image.original_name}</small><br>
                                    <small class="text-muted">${formatDateTime(image.capture_date)}</small>
                                </div>
                            </div>
                        `).join('');
                        selectedPhotosList.innerHTML = html;
                    } else {
                        selectedPhotosList.innerHTML = '<p class="text-warning mb-0">选择的照片未找到，可能存在数据问题</p>';
                    }

                    document.getElementById('confirmation-selected-count').textContent = selectedImages.length;
                    document.getElementById('confirmation-message').innerHTML = `
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            已选择 ${selectedImages.length} 张照片，将只包含这些照片在报告中。
                        </div>
                    `;
                    document.getElementById('report-photos-count').textContent = selectedImages.length;
                } else {
                    selectedPhotosList.innerHTML = '<p class="text-muted mb-0">未选择特定照片，将包含所有照片</p>';
                    document.getElementById('confirmation-selected-count').textContent = '0';
                    document.getElementById('confirmation-message').innerHTML = `
                        <div class="alert alert-warning">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            未选择特定照片，报告将包含该患者的所有 ${allImages.length} 张照片。
                        </div>
                    `;
                    document.getElementById('report-photos-count').textContent = allImages.length;
                }

                // 初始化牙齿病情选择
                initConfirmationDentalConditions();

                // 更新模板名称
                const templateNames = {
                    'standard': '标准报告',
                    'detailed': '详细报告',
                    'simple': '简化报告',
                    'custom': '自定义模板'
                };
                document.getElementById('report-template-name').textContent = templateNames[template] || template;

                // 存储参数用于确认后生成报告
                modal.dataset.patientId = patientId;
                modal.dataset.template = template;

                // 显示模态框
                const bsModal = new bootstrap.Modal(modal);
                bsModal.show();
            }).catch(error => {
                showMessage('加载照片信息失败: ' + error.message, 'danger');
            });
        }

        // 直接生成报告（不通过模态框确认）
        function generateReportDirect(patientId, template) {
            // 提示用户必须选择病情才能生成报告
            showMessage('请先选择患者照片，然后选择牙齿病情再生成报告', 'warning');
            return;
        }

        // 初始化确认模态框中的牙齿病情选择
        function initConfirmationDentalConditions() {
            const container = document.getElementById('confirmation-dental-conditions');

            // 显示加载状态
            container.innerHTML = '<div class="text-center"><div class="spinner-border spinner-border-sm" role="status"></div> 加载病情数据中...</div>';

            // 从API获取牙齿病情数据
            apiRequest('api/dental_conditions.php?action=list')
                .then(data => {
                    if (data.success && data.conditions && data.conditions.length > 0) {
                        // 按分类分组
                        const groupedConditions = {
                            common: data.conditions.filter(c => c.category === 'common' && c.active !== false),
                            other: data.conditions.filter(c => c.category !== 'common' && c.active !== false)
                        };

                        let html = '<div class="row">';

                        // 显示常见问题
                        if (groupedConditions.common.length > 0) {
                            html += `
                                <div class="col-md-6">
                                    <div class="mb-2">
                                        <strong>常见牙齿问题：</strong>
                                    </div>
                                    <div class="dental-condition-options">
                                        ${groupedConditions.common.map(condition => `
                                            <div class="form-check">
                                                <input class="form-check-input confirmation-condition" type="checkbox"
                                                       id="confirmation-condition-${condition.id}"
                                                       value="${condition.name}">
                                                <label class="form-check-label" for="confirmation-condition-${condition.id}">
                                                    ${condition.name}${condition.name_en ? ` (${condition.name_en})` : ''}
                                                </label>
                                            </div>
                                        `).join('')}
                                    </div>
                                </div>
                            `;
                        }

                        // 显示其他问题
                        if (groupedConditions.other.length > 0) {
                            html += `
                                <div class="col-md-6">
                                    <div class="mb-2">
                                        <strong>其他牙齿问题：</strong>
                                    </div>
                                    <div class="dental-condition-options">
                                        ${groupedConditions.other.map(condition => `
                                            <div class="form-check">
                                                <input class="form-check-input confirmation-condition" type="checkbox"
                                                       id="confirmation-condition-${condition.id}"
                                                       value="${condition.name}">
                                                <label class="form-check-label" for="confirmation-condition-${condition.id}">
                                                    ${condition.name}${condition.name_en ? ` (${condition.name_en})` : ''}
                                                </label>
                                            </div>
                                        `).join('')}
                                        <div class="form-check">
                                            <input class="form-check-input confirmation-condition" type="checkbox" id="confirmation-condition-other">
                                            <input type="text" class="form-control form-control-sm d-inline-block ms-2" id="confirmation-condition-other-text" placeholder="其他..." style="width: 100px;">
                                            <label class="form-check-label ms-1" for="confirmation-condition-other">
                                                其他
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            `;
                        }

                        html += '</div>';
                        container.innerHTML = html;
                    } else {
                        // 如果没有数据，使用基本的默认数据
                        loadBasicConfirmationConditions();
                    }
                })
                .catch(error => {
                    console.warn('从API获取病情数据失败，使用默认数据:', error);
                    loadBasicConfirmationConditions();
                });
        }

        // 加载基本的确认病情选择（当API不可用时）
        function loadBasicConfirmationConditions() {
            const container = document.getElementById('confirmation-dental-conditions');

            const dentalConditionsHtml = `
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-2">
                            <strong>常见牙齿问题：</strong>
                        </div>
                        <div class="dental-condition-options">
                            <div class="form-check">
                                <input class="form-check-input confirmation-condition" type="checkbox" id="confirmation-condition-caries" value="龋齿">
                                <label class="form-check-label" for="confirmation-condition-caries">
                                    龋齿 (Caries)
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input confirmation-condition" type="checkbox" id="confirmation-condition-periodontitis" value="牙周炎">
                                <label class="form-check-label" for="confirmation-condition-periodontitis">
                                    牙周炎 (Periodontitis)
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input confirmation-condition" type="checkbox" id="confirmation-condition-gingivitis" value="牙龈炎">
                                <label class="form-check-label" for="confirmation-condition-gingivitis">
                                    牙龈炎 (Gingivitis)
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-2">
                            <strong>其他牙齿问题：</strong>
                        </div>
                        <div class="dental-condition-options">
                            <div class="form-check">
                                <input class="form-check-input confirmation-condition" type="checkbox" id="confirmation-condition-malocclusion" value="错牙合">
                                <label class="form-check-label" for="confirmation-condition-malocclusion">
                                    错牙合 (Malocclusion)
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input confirmation-condition" type="checkbox" id="confirmation-condition-sensitivity" value="牙齿敏感">
                                <label class="form-check-label" for="confirmation-condition-sensitivity">
                                    牙齿敏感 (Tooth Sensitivity)
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input confirmation-condition" type="checkbox" id="confirmation-condition-other">
                                <input type="text" class="form-control form-control-sm d-inline-block ms-2" id="confirmation-condition-other-text" placeholder="其他..." style="width: 100px;">
                                <label class="form-check-label ms-1" for="confirmation-condition-other">
                                    其他
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            container.innerHTML = dentalConditionsHtml;
        }

        // 获取确认模态框中选中的牙齿病情
        function getConfirmationSelectedDentalConditions() {
            const conditions = [];
            const checkboxes = document.querySelectorAll('#confirmation-dental-conditions .confirmation-condition:checked');

            checkboxes.forEach(checkbox => {
                if (checkbox.id === 'confirmation-condition-other') {
                    const otherText = document.getElementById('confirmation-condition-other-text').value.trim();
                    if (otherText) {
                        conditions.push(otherText);
                    }
                } else {
                    conditions.push(checkbox.value);
                }
            });

            return conditions;
        }

        // 确认生成报告
        function confirmGenerateReport() {
            const modal = document.getElementById('photoConfirmationModal');
            const patientId = modal.dataset.patientId;
            const template = modal.dataset.template;

            // 检查是否选择了牙齿病情
            const selectedConditions = getConfirmationSelectedDentalConditions();
            const validationMessage = document.getElementById('condition-validation-message');

            if (selectedConditions.length === 0) {
                validationMessage.style.display = 'block';
                showMessage('请至少选择一种牙齿病情', 'warning');
                return;
            } else {
                validationMessage.style.display = 'none';
            }

            // 隐藏模态框
            bootstrap.Modal.getInstance(modal).hide();

            // 继续生成报告的原有逻辑
            generateReportConfirmed(patientId, template, selectedConditions);
        }

        // 确认生成报告后的实际处理
        function generateReportConfirmed(patientId, template, dentalConditions = []) {
            // 获取患者信息、影像和设置
            Promise.all([
                apiRequest(`api/patients.php?action=get&id=${patientId}`),
                apiRequest(`api/images.php?action=list&patient_id=${patientId}`),
                apiRequest('api/settings.php?action=get')
            ]).then(([patientData, imageData, settingsData]) => {
                const patient = patientData.patient;
                const allImages = imageData.images;
                const settings = settingsData.settings || {};

                // 如果有选中的照片，则只使用选中的照片，否则使用所有照片
                const images = selectedPhotos.length > 0
                    ? allImages.filter(img => {
                        const imgId = parseInt(img.id);
                        return selectedPhotos.includes(imgId) || selectedPhotos.includes(img.id.toString());
                    })
                    : allImages;

                // 生成诊断结论和治疗建议
                const diagnosisResult = generateDiagnosisFromConditions(dentalConditions);

                currentReport = {
                    patient: patient,
                    images: images,
                    settings: settings,
                    template: template,
                    dental_conditions: dentalConditions,
                    diagnosis: diagnosisResult.diagnosis,
                    treatment: diagnosisResult.treatment,
                    notes: '',
                    created_at: new Date().toISOString()
                };

                displayReport(currentReport);
                document.getElementById('report-preview').style.display = 'block';

                // 生成报告后自动保存
                saveReport();

                showMessage('报告生成并保存成功', 'success');
            }).catch(error => {
                showMessage('生成报告失败: ' + error.message, 'danger');
            });
        }

        // 显示报告
        function displayReport(report) {
            const container = document.getElementById('report-content');

            let imagesHtml = '';
            if (report.images && report.images.length > 0) {
                // 对影像进行分类整理
                const imageFiles = report.images.filter(img => img.file_type === 'image');
                const videoFiles = report.images.filter(img => img.file_type === 'video');

                imagesHtml = `
                    <div class="images-section mb-4">
                        ${imageFiles.length > 0 ? `
                            <h4>影像文件 (${imageFiles.length}个)</h4>
                            <div class="image-grid-print">
                                ${imageFiles.slice(0, 6).map(image => `
                                    <div class="image-item-print">
                                        <img src="${image.file_path}" alt="${image.original_name}" style="width:100%; height: auto; max-height: 250px; object-fit: contain;">
                                        
                                    </div>
                                `).join('')}
                            </div>
                        ` : ''}

                        ${videoFiles.length > 0 ? `
                            <h4>视频文件 (${videoFiles.length}个)</h4>
                            <div class="video-list">
                                ${videoFiles.slice(0, 3).map(video => `
                                    <div class="video-item mb-2">
                                        <i class="fas fa-video text-primary me-2"></i>
                                        <span>${video.original_name}</span>
                                        <small class="text-muted ms-2">${formatDateTime(video.capture_date)}</small>
                                    </div>
                                `).join('')}
                            </div>
                        ` : ''}
                    </div>
                `;
            } else {
                imagesHtml = '<p class="text-muted">暂无影像数据</p>';
            }

            container.innerHTML = `
                <!-- 医院和报告信息 -->
                <div class="report-header-section">
                    <div class="hospital-info" style="text-align: center;">
                        <h2 class="hospital-name" style="font-size: 28px; font-weight: bold;color: #d30c3d;">${report.settings.hospital_name || '口腔诊所'}</h2>
                        <h3 class="report-title" style="font-size: 20px; font-weight: bold;color:rgb(16, 22, 27);">${report.settings.report_title || '口腔检查报告'}</h3>
                       
                    </div>
                </div>

                <div class="patient-info">
                    <h3>患者信息</h3>
                    <table class="table table-bordered">
                        <tr>
                            <td><strong>姓名:</strong></td>
                            <td>${report.patient.name}</td>
                            <td><strong>性别:</strong></td>
                            <td>${report.patient.gender === 'male' ? '男' : '女'}</td>
                            <td><strong>年龄:</strong></td>
                            <td>${report.patient.age}岁</td>
                            <td><strong>身份证号:</strong></td>
                            <td>${report.patient.id_card || '未填写'}</td>
                          
                        </tr>
                    
                        <tr>
                          <td><strong>电话:</strong></td>
                            <td>${report.patient.phone || '未填写'}</td>
                            <td><strong>医生签名:</strong></td>
                            <td>${report.settings.doctor_name || '未填写'}</td>
                             <td><strong>报告生成时间:</strong></td>
                            <td>${report.patient.created_at}</td>
                            <td><strong>地址:</strong></td>
                            <td>${report.patient.address || '未填写'}</td>
                           
                        </tr>
                    </table>
                </div>

                <div class="findings-section">
                    <h3>检查结果</h3>
                    <p>共采集 ${report.images ? report.images.length : 0} 个影像文件</p>
                </div>

                <div class="images-section">
                    <h3>影像文件</h3>
                    <div class="print-images">
                        ${imagesHtml}
                    </div>
                </div>

                ${report.dental_conditions && Array.isArray(report.dental_conditions) && report.dental_conditions.length > 0 ? `
                    <div class="conditions-section mb-4">
                        <h3>牙齿病情</h3>
                        <p class="dental-conditions-text">${report.dental_conditions.join('，')}</p>
                    </div>
                ` : ''}

                <div class="conclusion-section mb-4">
                    <h3>诊断结论</h3>
                    <div id="diagnosis-content">
                        ${report.diagnosis || '<p class="text-muted">暂无诊断结论，请点击"编辑报告"添加</p>'}
                    </div>
                </div>

                <div class="treatment-section mb-4">
                    <h3>治疗建议</h3>
                    <div id="treatment-content">
                        ${report.treatment || '<p class="text-muted">暂无治疗建议，请点击"编辑报告"添加</p>'}
                    </div>
                </div>

                ${report.notes ? `
                    <div class="notes-section mb-4">
                        <h3>备注</h3>
                        <div id="notes-content">${report.notes}</div>
                    </div>
                ` : ''}

                <div class="report-footer text-center mt-5">
                    <hr>
                        ${report.settings.report_footer ? `<div class="mb-3" style="text-align: center;color: red;font-size:16px;">${report.settings.report_footer}</div>` : ''}
                </div>
            `;
        }

        // 编辑报告
        function editReport() {
            if (!currentReport) {
                showMessage('请先生成报告', 'warning');
                return;
            }

            // 加载牙齿病情选择
            initEditDentalConditions();

            document.getElementById('edit-diagnosis').value = currentReport.diagnosis || '';
            document.getElementById('edit-treatment').value = currentReport.treatment || '';
            document.getElementById('edit-notes').value = currentReport.notes || '';

            const modal = new bootstrap.Modal(document.getElementById('editReportModal'));
            modal.show();
        }

        // 全局变量存储所有可用的影像数据（用于编辑时快速访问）
        let allAvailableImages = [];

        // 初始化编辑报告模态框中的影像选择
        function initEditImageSelection() {
            return new Promise((resolve, reject) => {
                const container = document.getElementById('image-selection');

                if (!currentReport || !currentReport.patient) {
                    container.innerHTML = '<p class="text-muted">无法获取患者信息</p>';
                    resolve();
                    return;
                }

                // 显示加载状态
                container.innerHTML = '<div class="text-center"><div class="spinner-border spinner-border-sm" role="status"></div> 加载影像数据中...</div>';

                // 获取患者的所有影像
                apiRequest(`api/images.php?action=list&patient_id=${currentReport.patient.id}`)
                    .then(data => {
                        if (data.images && data.images.length > 0) {
                            // 保存所有影像数据到全局变量
                            allAvailableImages = data.images;
                            displayEditImageSelection(data.images);
                            resolve();
                        } else {
                            allAvailableImages = [];
                            container.innerHTML = '<p class="text-muted">该患者暂无影像数据</p>';
                            resolve();
                        }
                    })
                    .catch(error => {
                        console.warn('获取患者影像失败:', error);
                        allAvailableImages = [];
                        container.innerHTML = '<p class="text-danger">加载影像数据失败，请重试</p>';
                        resolve(); // 即使失败也要resolve，确保流程继续
                    });
            });
        }

        // 显示编辑报告中的影像选择界面
        function displayEditImageSelection(images) {
            const container = document.getElementById('image-selection');

            // 获取当前报告中包含的影像ID列表
            const currentReportImageIds = currentReport.images ? currentReport.images.map(img => img.id.toString()) : [];

            const html = `
                <div class="row">
                    <div class="col-12 mb-2">
                        <small class="text-muted">选择要在报告中显示的影像（${currentReportImageIds.length}/${images.length} 已选择）</small>
                    </div>
                </div>
                <div class="edit-image-grid" style="max-height: 300px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: 4px; padding: 10px;">
                    <div class="row g-2">
                        ${images.map(image => {
                            const isSelected = currentReportImageIds.includes(image.id.toString());
                            return `
                                <div class="col-md-6 col-lg-4">
                                    <div class="edit-image-item border rounded p-2 ${isSelected ? 'bg-light border-primary' : ''}" style="cursor: pointer;" onclick="toggleEditImageSelection('${image.id}')">
                                        <div class="form-check mb-1">
                                            <input class="form-check-input edit-image-checkbox" type="checkbox"
                                                   id="edit-image-${image.id}"
                                                   value="${image.id}"
                                                   ${isSelected ? 'checked' : ''}>
                                            <label class="form-check-label" for="edit-image-${image.id}" style="font-size: 0.8rem;">
                                                ${isSelected ? '<strong>已包含</strong>' : '包含在报告中'}
                                            </label>
                                        </div>
                                        <img src="${image.file_path}" alt="${image.original_name}"
                                             style="width: 100%; height: 60px; object-fit: cover; border-radius: 3px; border: 1px solid #dee2e6;">
                                        <div style="font-size: 0.7rem; color: #666; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                                            ${image.original_name}
                                        </div>
                                        <div style="font-size: 0.6rem; color: #999;">
                                            ${formatDateTime(image.capture_date)}
                                        </div>
                                    </div>
                                </div>
                            `;
                        }).join('')}
                    </div>
                </div>
                <div class="mt-2">
                    <button type="button" class="btn btn-sm btn-outline-primary me-2" onclick="selectAllEditImages()">全选</button>
                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearEditImageSelection()">清空选择</button>
                </div>
            `;

            container.innerHTML = html;
        }

        // 切换编辑报告中影像的选择状态
        function toggleEditImageSelection(imageId) {
            const checkbox = document.getElementById(`edit-image-${imageId}`);
            if (checkbox) {
                checkbox.checked = !checkbox.checked;
                updateEditImageSelectionCount();
                updateReportImages();
            }
        }

        // 更新编辑报告中影像选择的数量显示
        function updateEditImageSelectionCount() {
            const selectedCount = document.querySelectorAll('#image-selection .edit-image-checkbox:checked').length;
            const totalCount = document.querySelectorAll('#image-selection .edit-image-checkbox').length;

            // 更新显示文本
            const countText = document.querySelector('#image-selection small');
            if (countText) {
                countText.textContent = `选择要在报告中显示的影像（${selectedCount}/${totalCount} 已选择）`;
            }
        }

        // 更新报告中的影像列表
        function updateReportImages() {
            const selectedImageIds = Array.from(document.querySelectorAll('#image-selection .edit-image-checkbox:checked'))
                .map(checkbox => checkbox.value);

            // 从全局影像数据中筛选出选中的影像
            const selectedImages = allAvailableImages.filter(image =>
                selectedImageIds.includes(image.id.toString())
            );

            // 更新currentReport中的影像列表
            currentReport.images = selectedImages;

            // 重新显示报告
            displayReport(currentReport);
        }

        // 全选编辑报告中的影像
        function selectAllEditImages() {
            document.querySelectorAll('#image-selection .edit-image-checkbox').forEach(checkbox => {
                checkbox.checked = true;
            });
            updateEditImageSelectionCount();
            updateReportImages();
        }

        // 清空编辑报告中的影像选择
        function clearEditImageSelection() {
            document.querySelectorAll('#image-selection .edit-image-checkbox').forEach(checkbox => {
                checkbox.checked = false;
            });
            updateEditImageSelectionCount();
            updateReportImages();
        }

        // 初始化编辑报告模态框中的牙齿病情选择
        function initEditDentalConditions() {
            return new Promise((resolve, reject) => {
                const container = document.getElementById('dental-conditions');

                // 显示加载状态
                container.innerHTML = '<div class="text-center"><div class="spinner-border spinner-border-sm" role="status"></div> 加载病情数据中...</div>';

                // 从API获取牙齿病情数据
                apiRequest('api/dental_conditions.php?action=list')
                    .then(data => {
                        if (data.success && data.conditions && data.conditions.length > 0) {
                            // 按分类分组，只显示启用的病情
                            const groupedConditions = {
                                common: data.conditions.filter(c => c.category === 'common' && c.active !== false),
                                other: data.conditions.filter(c => c.category !== 'common' && c.active !== false)
                            };

                            let html = '<div class="row">';

                            // 显示常见问题
                            if (groupedConditions.common.length > 0) {
                                html += `
                                    <div class="col-md-6">
                                        <div class="mb-2">
                                            <strong>常见牙齿问题：</strong>
                                        </div>
                                        <div class="dental-condition-options">
                                            ${groupedConditions.common.map(condition => `
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           id="condition-${condition.id}"
                                                           value="${condition.name}">
                                                    <label class="form-check-label" for="condition-${condition.id}">
                                                        ${condition.name}${condition.name_en ? ` (${condition.name_en})` : ''}
                                                    </label>
                                                </div>
                                            `).join('')}
                                        </div>
                                    </div>
                                `;
                            }

                            // 显示其他问题
                            if (groupedConditions.other.length > 0) {
                                html += `
                                    <div class="col-md-6">
                                        <div class="mb-2">
                                            <strong>其他牙齿问题：</strong>
                                        </div>
                                        <div class="dental-condition-options">
                                            ${groupedConditions.other.map(condition => `
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox"
                                                           id="condition-${condition.id}"
                                                           value="${condition.name}">
                                                    <label class="form-check-label" for="condition-${condition.id}">
                                                        ${condition.name}${condition.name_en ? ` (${condition.name_en})` : ''}
                                                    </label>
                                                </div>
                                            `).join('')}
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="condition-other">
                                                <input type="text" class="form-control form-control-sm d-inline-block ms-2" id="condition-other-text" placeholder="其他..." style="width: 120px;">
                                                <label class="form-check-label ms-1" for="condition-other">
                                                    其他
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }

                            html += `
                                </div>
                                <div class="mt-3">
                                    <small class="text-muted">可多选，系统将自动生成相应的诊断描述</small>
                                </div>
                            `;

                            container.innerHTML = html;
                            resolve();
                        } else {
                            // 如果没有数据，使用基本的默认数据
                            loadBasicEditConditions();
                            resolve();
                        }
                    })
                    .catch(error => {
                        console.warn('从API获取病情数据失败，使用默认数据:', error);
                        loadBasicEditConditions();
                        resolve(); // 即使出错也resolve，确保流程继续
                    });
            });
        }

        // 加载基本的编辑病情选择（当API不可用时）
        function loadBasicEditConditions() {
            return new Promise((resolve) => {
                const container = document.getElementById('dental-conditions');

            const dentalConditionsHtml = `
                <div class="row">
                    <div class="col-md-6">
                        <div class="mb-2">
                            <strong>常见牙齿问题：</strong>
                        </div>
                        <div class="dental-condition-options">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="condition-caries" value="龋齿">
                                <label class="form-check-label" for="condition-caries">
                                    龋齿 (Caries)
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="condition-periodontitis" value="牙周炎">
                                <label class="form-check-label" for="condition-periodontitis">
                                    牙周炎 (Periodontitis)
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="condition-gingivitis" value="牙龈炎">
                                <label class="form-check-label" for="condition-gingivitis">
                                    牙龈炎 (Gingivitis)
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="mb-2">
                            <strong>其他牙齿问题：</strong>
                        </div>
                        <div class="dental-condition-options">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="condition-malocclusion" value="错牙合">
                                <label class="form-check-label" for="condition-malocclusion">
                                    错牙合 (Malocclusion)
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="condition-sensitivity" value="牙齿敏感">
                                <label class="form-check-label" for="condition-sensitivity">
                                    牙齿敏感 (Tooth Sensitivity)
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="condition-other">
                                <input type="text" class="form-control form-control-sm d-inline-block ms-2" id="condition-other-text" placeholder="其他..." style="width: 120px;">
                                <label class="form-check-label ms-1" for="condition-other">
                                    其他
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="mt-3">
                    <small class="text-muted">可多选，系统将自动生成相应的诊断描述</small>
                </div>
            `;

            container.innerHTML = dentalConditionsHtml;
            resolve();
        });
    }

        // 更新报告
        function updateReport() {
            currentReport.diagnosis = document.getElementById('edit-diagnosis').value;
            currentReport.treatment = document.getElementById('edit-treatment').value;
            currentReport.notes = document.getElementById('edit-notes').value;

            displayReport(currentReport);
            bootstrap.Modal.getInstance(document.getElementById('editReportModal')).hide();
            showMessage('报告更新成功', 'success');
        }

        // 打印报告
        function printReport() {
            if (!currentReport) {
                showMessage('请先生成报告', 'warning');
                return;
            }

            // 获取报告内容（只获取报告预览的内容）
            const reportContent = document.getElementById('report-content').innerHTML;

            // 创建隐藏的iframe来专门处理打印
            const printFrame = document.createElement('iframe');
            printFrame.style.position = 'absolute';
            printFrame.style.left = '-9999px';
            printFrame.style.top = '-9999px';
            printFrame.style.width = '0';
            printFrame.style.height = '0';
            printFrame.style.border = 'none';

            // 将iframe添加到页面
            document.body.appendChild(printFrame);

            // 获取iframe的文档对象
            const frameDoc = printFrame.contentDocument || printFrame.contentWindow.document;

            // 写入打印内容
            frameDoc.open();
            frameDoc.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>口腔检查报告 - 打印</title>
                    <meta charset="UTF-8">
                    <style>
                        @media print {
                            body {
                                background: white !important;
                                margin: 0;
                                padding: 10px;
                                font-family: 'Microsoft YaHei', 'SimHei', sans-serif;
                            }
                            .no-print { display: none !important; }
                            .report-content { max-width: none; margin: 0; padding: 0; }
                            .card { border: none !important; box-shadow: none !important; }
                        }
                        @page {
                            size: A4;
                            margin-top: 2mm;
                            margin-bottom: 2mm;
                            margin-left: 10mm;
                            margin-right: 10mm;
                        }
                        body {
                            font-family: 'Microsoft YaHei', 'SimHei', sans-serif;
                            font-size: 14px;
                            line-height: 0.9;
                            color: #333;
                            background: white;
                        }
                        .report-content {
                            font-family: 'Microsoft YaHei', 'SimHei', sans-serif;
                            max-width: 800px;
                            margin: 0 auto;
                            font-size: 14px;
                            line-height: 0.9;
                            color: #333;
                        }
                        .report-content h2, .report-content h3 {
                            color: #333;
                            page-break-after: avoid;
                        }
                        .report-content table {
                            page-break-inside: avoid;
                            width: 100%;
                            border-collapse: collapse;
                        }
                        .report-content img {
                            max-width: 100%;
                            height: auto;
                            page-break-inside: avoid;
                        }
                        .image-grid-print {
                            display: grid;
                            grid-template-columns: repeat(2, 1fr);
                            gap: 15px;
                            margin: 5px 0;
                        }
                        .image-item-print {
                            text-align: center;
                            border: 1px solid #dee2e6;
                            border-radius: 4px;
                            padding: 4px;
                            page-break-inside: avoid;
                        }
                        .print-watermark {
                            position: fixed;
                            top: 50%;
                            left: 50%;
                            transform: translate(-50%, -50%) rotate(-45deg);
                            font-size: 72px;
                            color: rgba(200, 200, 200, 0.1);
                            z-index: -1;
                            pointer-events: none;
                        }
                        .print-footer {
                            margin-top: 10px;
                            padding-top: 10px;
                            border-top: 1px solid #dee2e6;
                            text-align: center;
                            font-size: 12px;
                            color: #666;
                        }
                    </style>
                </head>
                <body>
                    <!-- 水印 -->
                    <div class="print-watermark">口腔检查报告</div>

                    <!-- 报告内容 -->
                    <div class="report-content">
                        ${reportContent}
                    </div>

                    <!-- 页脚 -->
                    <div class="print-footer">
                        <div>本报告仅供临床参考，具体治疗方案请遵医嘱</div>
                    </div>
                </body>
                </html>
            `);
            frameDoc.close();

            // 等待内容加载完成后触发打印
            setTimeout(() => {
                try {
                    printFrame.contentWindow.focus();
                    printFrame.contentWindow.print();

                    // 打印完成后移除iframe
                    setTimeout(() => {
                        if (document.body.contains(printFrame)) {
                            document.body.removeChild(printFrame);
                        }
                    }, 1000);
                } catch (error) {
                    console.error('打印失败:', error);
                    // 如果iframe打印失败，移除iframe
                    if (document.body.contains(printFrame)) {
                        document.body.removeChild(printFrame);
                    }
                    showMessage('打印功能暂时不可用，请稍后重试', 'danger');
                }
            }, 500);
        }

        // 导出PDF
        function exportReport(format) {
            if (!currentReport) {
                showMessage('请先生成报告', 'warning');
                return;
            }

            if (format === 'pdf') {
                const reportContent = document.getElementById('report-content').innerHTML;
                const filename = `口腔检查报告_${currentReport.patient.name}_${new Date().toISOString().split('T')[0]}`;
                exportAsPDF(reportContent, filename);
            } else {
                showMessage(`${format.toUpperCase()}导出功能开发中...`, 'info');
            }
        }

        // 导出为PDF
        function exportAsPDF(content, filename) {
            try {
                // 创建临时容器来放置报告内容
                const tempContainer = document.createElement('div');
                tempContainer.innerHTML = content;
                tempContainer.style.width = '210mm'; // A4宽度
                tempContainer.style.minHeight = '297mm'; // A4高度
                tempContainer.style.padding = '20mm';
                tempContainer.style.boxSizing = 'border-box';
                tempContainer.style.fontFamily = '"Microsoft YaHei", "SimHei", sans-serif';
                tempContainer.style.fontSize = '14px';
                tempContainer.style.lineHeight = '1.1';
                tempContainer.style.backgroundColor = 'white';
                tempContainer.style.color = '#333';

                // 临时添加到body中（隐藏）
                tempContainer.style.position = 'absolute';
                tempContainer.style.left = '-9999px';
                tempContainer.style.top = '-9999px';
                document.body.appendChild(tempContainer);

                // PDF导出选项
                const options = {
                    margin: [10, 10, 10, 10], // 上下左右边距
                    filename: filename + '.pdf',
                    image: { type: 'jpeg', quality: 0.98 },
                    html2canvas: {
                        scale: 2, // 提高清晰度
                        useCORS: true,
                        letterRendering: true,
                        allowTaint: false
                    },
                    jsPDF: {
                        unit: 'mm',
                        format: 'a4',
                        orientation: 'portrait'
                    }
                };

                // 显示导出进度
                showMessage('正在生成PDF文件，请稍候...', 'info');

                // 使用html2pdf生成PDF
                html2pdf()
                    .set(options)
                    .from(tempContainer)
                    .save()
                    .then(() => {
                        showMessage('PDF文件导出成功！', 'success');
                        // 清理临时容器
                        document.body.removeChild(tempContainer);
                    })
                    .catch(error => {
                        console.error('PDF导出失败:', error);
                        showMessage('PDF导出失败，请重试或使用打印功能', 'danger');
                        // 清理临时容器
                        if (document.body.contains(tempContainer)) {
                            document.body.removeChild(tempContainer);
                        }
                    });

            } catch (error) {
                console.error('PDF导出初始化失败:', error);
                showMessage('PDF导出功能初始化失败', 'danger');
            }
        }

        // 保存报告
        function saveReport() {
            if (!currentReport) {
                showMessage('请先生成报告', 'warning');
                return;
            }

            // 保存到本地存储（实际应用中应该保存到数据库）
            const reports = JSON.parse(localStorage.getItem('saved_reports') || '[]');
            const reportToSave = {
                ...currentReport,
                id: Date.now(),
                saved_at: new Date().toISOString()
            };

            reports.push(reportToSave);
            localStorage.setItem('saved_reports', JSON.stringify(reports));

            loadReportsHistory();
            // 不显示保存成功的消息，因为已经在生成报告时显示了
        }

        // 加载报告历史
        function loadReportsHistory() {
            const reports = JSON.parse(localStorage.getItem('saved_reports') || '[]');
            const tbody = document.getElementById('reports-list');

            if (reports.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">暂无报告记录</td></tr>';
                return;
            }

            tbody.innerHTML = reports.map(report => `
                <tr>
                    <td>${report.patient.name}</td>
                    <td>${getTemplateName(report.template)}</td>
                    <td>${formatDateTime(report.saved_at)}</td>
                    <td><span class="badge bg-success">已保存</span></td>
                    <td>
                        <button class="btn btn-sm btn-primary me-1" onclick="viewReport(${report.id})">查看</button>
                        <button class="btn btn-sm btn-danger" onclick="deleteReport(${report.id})">删除</button>
                    </td>
                </tr>
            `).join('');
        }

        // 获取模板名称
        function getTemplateName(template) {
            const names = {
                'standard': '标准报告',
                'detailed': '详细报告',
                'simple': '简化报告'
            };
            return names[template] || template;
        }

        // 查看报告
        function viewReport(reportId) {
            const reports = JSON.parse(localStorage.getItem('saved_reports') || '[]');
            const report = reports.find(r => r.id == reportId);

            if (report) {
                currentReport = report;
                displayReport(report);
                document.getElementById('report-preview').style.display = 'block';
                document.getElementById('report-preview').scrollIntoView({ behavior: 'smooth' });
            }
        }

        // 删除报告
        function deleteReport(reportId) {
            if (!confirm('确定要删除这个报告吗？')) return;

            const reports = JSON.parse(localStorage.getItem('saved_reports') || '[]');
            const filteredReports = reports.filter(r => r.id != reportId);
            localStorage.setItem('saved_reports', JSON.stringify(filteredReports));

            loadReportsHistory();
            showMessage('报告删除成功', 'success');
        }

        // 清空报告
        function clearReport() {
            currentReport = null;
            document.getElementById('report-preview').style.display = 'none';
            document.getElementById('report-content').innerHTML = '';
        }

        // 从设置获取值
        function getSetting(key, defaultValue) {
            // 这里应该从API获取，暂时使用默认值
            const settings = {
                'report_title': '口腔检查报告',
                'hospital_name': '口腔诊所'
            };
            return settings[key] || defaultValue;
        }

        // ==================== 报告预览功能 ====================

        // 预览报告
        function previewReport() {
            if (!currentReport) {
                showMessage('请先生成报告', 'warning');
                return;
            }

            const previewContent = document.getElementById('report-preview-content');
            const reportContent = document.getElementById('report-content').innerHTML;

            // 添加打印样式
            previewContent.innerHTML = `
                <style>
                    @media print {
                        body { background: white !important; }
                        .no-print { display: none !important; }
                        .report-content { max-width: none; margin: 0; padding: 20px; }
                        .card { border: none !important; box-shadow: none !important; }
                    }
                    .report-content { font-family: 'Microsoft YaHei', sans-serif; max-width: 800px; margin: 0 auto; }
                </style>
                <div class="report-content">
                    ${reportContent}
                </div>
            `;

            const modal = new bootstrap.Modal(document.getElementById('reportPreviewModal'));
            modal.show();
        }

        // 确认打印
        function confirmPrint() {
            // 隐藏预览模态框
            bootstrap.Modal.getInstance(document.getElementById('reportPreviewModal')).hide();

            // 直接调用打印报告功能
            setTimeout(() => {
                printReport();
            }, 300); // 给模态框一点时间来完全隐藏
        }

        // ==================== 报告导出功能 ====================

        // 导出报告
        function exportReport() {
            if (!currentReport) {
                showMessage('请先生成报告', 'warning');
                return;
            }

            const format = document.querySelector('input[name="export-format"]:checked').value;
            const reportContent = document.getElementById('report-content').innerHTML;
            const filename = `口腔检查报告_${currentReport.patient.name}_${new Date().toISOString().split('T')[0]}`;

            switch (format) {
                case 'html':
                    exportAsHTML(reportContent, filename);
                    break;
                case 'pdf':
                    exportAsPDF(reportContent, filename);
                    break;
                case 'word':
                    exportAsWord(reportContent, filename);
                    break;
                default:
                    showMessage('不支持的导出格式', 'danger');
            }
        }

        // 导出为HTML
        function exportAsHTML(content, filename) {
            const htmlContent = `
                <!DOCTYPE html>
                <html lang="zh-CN">
                <head>
                    <meta charset="UTF-8">
                    <title>${filename}</title>
                    <link rel="stylesheet" href="assets/css/style.css">
                    <style>
                        body { font-family: 'Microsoft YaHei', sans-serif; margin: 20px; }
                        .report-content { max-width: 800px; margin: 0 auto; }
                    </style>
                </head>
                <body>
                    <div class="report-content">
                        ${content}
                    </div>
                </body>
                </html>
            `;

            const blob = new Blob([htmlContent], { type: 'text/html;charset=utf-8;' });
            downloadBlob(blob, filename + '.html');
        }

        // 导出为PDF（简化实现，实际需要PDF库）
        function exportAsPDF(content, filename) {
            // 这里需要集成PDF生成库，如jsPDF或html2pdf
            // 现在先使用HTML导出，提示用户可以使用浏览器打印功能
            showMessage('PDF导出功能开发中，请使用"打印"功能或HTML导出后手动转换为PDF', 'warning');
            exportAsHTML(content, filename);
        }

        // 导出为Word（简化实现）
        function exportAsWord(content, filename) {
            // Word导出比较复杂，这里提供基础的HTML导出
            // 实际应用中可能需要服务器端处理
            const wordContent = `
                <html xmlns:o="urn:schemas-microsoft-com:office:office"
                      xmlns:w="urn:schemas-microsoft-com:office:word"
                      xmlns="http://www.w3.org/TR/REC-html40">
                <head>
                    <meta charset="utf-8">
                    <title>${filename}</title>
                    <!--[if gte mso 9]>
                    <xml>
                        <w:WordDocument>
                            <w:View>Print</w:View>
                            <w:Zoom>90</w:Zoom>
                        </w:WordDocument>
                    </xml>
                    <![endif]-->
                    <style>
                        body { font-family: 'Microsoft YaHei', sans-serif; }
                        .report-content { max-width: 800px; margin: 0 auto; }
                    </style>
                </head>
                <body>
                    <div class="report-content">
                        ${content}
                    </div>
                </body>
                </html>
            `;

            const blob = new Blob([wordContent], { type: 'application/msword;charset=utf-8;' });
            downloadBlob(blob, filename + '.doc');
        }

        // 下载Blob文件
        function downloadBlob(blob, filename) {
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);

            showMessage(`报告已导出为 ${filename}`, 'success');
        }

        // ==================== 模板管理功能 ====================

        let currentTemplate = null;
        let availableTemplates = [];

        // 管理模板
        function manageTemplates() {
            loadAvailableTemplates();
            const modal = new bootstrap.Modal(document.getElementById('templateManagerModal'));
            modal.show();
        }

        // 加载可用模板
        function loadAvailableTemplates() {
            // 从API获取模板列表（这里使用本地存储作为示例）
            const templates = [
                { id: 'standard', name: '标准报告', type: 'system' },
                { id: 'detailed', name: '详细报告', type: 'system' },
                { id: 'simple', name: '简化报告', type: 'system' }
            ];

            // 添加自定义模板
            const customTemplates = JSON.parse(localStorage.getItem('custom_report_templates') || '[]');
            templates.push(...customTemplates);

            availableTemplates = templates;
            displayTemplateList(templates);
        }

        // 显示模板列表
        function displayTemplateList(templates) {
            const container = document.getElementById('template-list');
            container.innerHTML = '';

            templates.forEach(template => {
                const item = document.createElement('div');
                item.className = 'list-group-item list-group-item-action d-flex justify-content-between align-items-center';
                item.onclick = () => selectTemplate(template);

                item.innerHTML = `
                    <div>
                        <strong>${template.name}</strong>
                        <br><small class="text-muted">${template.type === 'system' ? '系统模板' : '自定义模板'}</small>
                    </div>
                    ${template.type !== 'system' ? '<button class="btn btn-sm btn-outline-danger" onclick="deleteTemplate(event, \'' + template.id + '\')">删除</button>' : ''}
                `;

                container.appendChild(item);
            });
        }

        // 选择模板
        function selectTemplate(template) {
            currentTemplate = template;

            // 移除其他选中状态
            document.querySelectorAll('#template-list .list-group-item').forEach(item => {
                item.classList.remove('active');
            });

            // 添加当前选中状态
            event.currentTarget.classList.add('active');

            // 加载模板编辑器
            loadTemplateEditor(template);
        }

        // 加载模板编辑器
        function loadTemplateEditor(template) {
            const editor = document.getElementById('template-editor');

            if (template.type === 'system') {
                editor.innerHTML = `
                    <div class="alert alert-info">
                        <h6>${template.name}</h6>
                        <p>系统模板不可编辑。如需自定义，请创建新模板。</p>
                        <div class="mt-3">
                            <button class="btn btn-primary" onclick="createNewTemplate()">基于此模板创建</button>
                        </div>
                    </div>
                `;
            } else {
                // 自定义模板编辑器
                editor.innerHTML = `
                    <div class="mb-3">
                        <label class="form-label">模板名称</label>
                        <input type="text" id="template-name" class="form-control" value="${template.name}">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">页眉HTML</label>
                        <textarea id="template-header" class="form-control" rows="3" placeholder="页眉内容HTML">${template.header || ''}</textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">主体布局</label>
                        <textarea id="template-body" class="form-control" rows="8" placeholder="主体内容HTML模板">${template.body || ''}</textarea>
                        <small class="form-text text-muted">
                            可用变量: {{patient_name}}, {{patient_age}}, {{diagnosis}}, {{treatment}}, {{images}}
                        </small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">页脚HTML</label>
                        <textarea id="template-footer" class="form-control" rows="3" placeholder="页脚内容HTML">${template.footer || ''}</textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">CSS样式</label>
                        <textarea id="template-css" class="form-control" rows="4" placeholder="自定义CSS样式">${template.css || ''}</textarea>
                    </div>
                `;
            }
        }

        // 创建新模板
        function createNewTemplate() {
            const templateName = prompt('请输入新模板名称：');
            if (!templateName) return;

            const newTemplate = {
                id: 'custom_' + Date.now(),
                name: templateName,
                type: 'custom',
                header: '',
                body: `
                    <div class="report-header text-center mb-4">
                        <h1>{{hospital_name}}</h1>
                        <h2>口腔检查报告</h2>
                        <p>报告日期: {{report_date}}</p>
                    </div>

                    <div class="patient-info mb-4">
                        <h3>患者信息</h3>
                        <table class="table table-bordered">
                            <tr><td>姓名:</td><td>{{patient_name}}</td><td>年龄:</td><td>{{patient_age}}岁</td></tr>
                            <tr><td>性别:</td><td>{{patient_gender}}</td><td>电话:</td><td>{{patient_phone}}</td></tr>
                        </table>
                    </div>

                    <div class="diagnosis-section mb-4">
                        <h3>诊断结论</h3>
                        <p>{{diagnosis}}</p>
                    </div>

                    <div class="treatment-section mb-4">
                        <h3>治疗建议</h3>
                        <p>{{treatment}}</p>
                    </div>

                    <div class="images-section mb-4">
                        <h3>检查影像</h3>
                        {{images}}
                    </div>
                `,
                footer: '<div class="text-center text-muted"><p>本报告仅供临床参考</p></div>',
                css: '.report-content { font-family: "Microsoft YaHei", sans-serif; }'
            };

            // 保存到本地存储
            const customTemplates = JSON.parse(localStorage.getItem('custom_report_templates') || '[]');
            customTemplates.push(newTemplate);
            localStorage.setItem('custom_report_templates', JSON.stringify(customTemplates));

            // 重新加载模板列表
            loadAvailableTemplates();

            // 选择新创建的模板
            selectTemplate(newTemplate);

            showMessage('新模板已创建', 'success');
        }

        // 保存模板
        function saveTemplate() {
            if (!currentTemplate || currentTemplate.type === 'system') {
                showMessage('请选择自定义模板进行保存', 'warning');
                return;
            }

            // 获取编辑器中的值
            const name = document.getElementById('template-name').value;
            const header = document.getElementById('template-header').value;
            const body = document.getElementById('template-body').value;
            const footer = document.getElementById('template-footer').value;
            const css = document.getElementById('template-css').value;

            // 更新模板
            currentTemplate.name = name;
            currentTemplate.header = header;
            currentTemplate.body = body;
            currentTemplate.footer = footer;
            currentTemplate.css = css;

            // 保存到本地存储
            const customTemplates = JSON.parse(localStorage.getItem('custom_report_templates') || '[]');
            const index = customTemplates.findIndex(t => t.id === currentTemplate.id);
            if (index !== -1) {
                customTemplates[index] = currentTemplate;
                localStorage.setItem('custom_report_templates', JSON.stringify(customTemplates));
            }

            // 重新加载模板列表
            loadAvailableTemplates();

            showMessage('模板保存成功', 'success');
        }

        // 删除模板
        function deleteTemplate(event, templateId) {
            event.stopPropagation();

            if (!confirm('确定要删除这个模板吗？')) return;

            const customTemplates = JSON.parse(localStorage.getItem('custom_report_templates') || '[]');
            const filtered = customTemplates.filter(t => t.id !== templateId);
            localStorage.setItem('custom_report_templates', JSON.stringify(filtered));

            loadAvailableTemplates();
            showMessage('模板已删除', 'success');
        }

        // Dashboard functionality for reports page
        document.addEventListener('DOMContentLoaded', function() {
            initDatabase();

            // Sidebar toggle functionality
            document.getElementById('sidebarToggle').addEventListener('click', function() {
                document.querySelector('.sidebar').classList.toggle('collapsed');
                document.querySelector('.main-content').classList.toggle('expanded');
            });
        });

        // 搜索患者函数
        function searchPatients(query, selectId) {
            const select = document.getElementById(selectId);
            if (!select) return;

            // 清空现有选项，只保留默认选项
            select.innerHTML = '<option value="">请选择患者...</option>';

            if (query.trim().length < 2) {
                // 如果搜索词太短，不进行搜索
                return;
            }

            // 调用搜索API
            apiRequest(`api/patients.php?action=search&q=${encodeURIComponent(query)}`)
                .then(data => {
                    if (data.patients && data.patients.length > 0) {
                        data.patients.forEach(patient => {
                            const option = document.createElement('option');
                            option.value = patient.id;
                            // 格式化显示：姓名(性别,年龄) - 电话 [影像:数量|就诊:数量|预约:数量]
                            const genderText = patient.gender === 'male' ? '男' : '女';
                            const phoneText = patient.phone ? ` - ${patient.phone}` : '';
                            const idCardText = patient.id_card ? ` (${patient.id_card.substring(0, 6)}****)` : '';

                            // 统计信息
                            const stats = patient.stats || {};
                            const statsText = ` [影像:${stats.images || 0}|就诊:${stats.medical_records || 0}|预约:${stats.appointments || 0}]`;

                            option.textContent = `${patient.name}(${genderText},${patient.age}岁)${phoneText}${idCardText}${statsText}`;

                            // 存储统计数据到选项的data属性中
                            option.dataset.stats = JSON.stringify(stats);

                            select.appendChild(option);
                        });
                    }
                })
                .catch(error => {
                    console.error('搜索患者失败:', error);
                });
        }

        // 显示患者统计信息
        function showPatientStats(patientId, selectElement) {
            const selectedOption = selectElement.selectedOptions[0];
            if (!selectedOption) return;

            // 异步获取患者统计数据
            apiRequest(`api/images.php?action=list&patient_id=${patientId}`)
                .then(imageData => {
                    const imageCount = imageData.images ? imageData.images.length : 0;

                    // 更新选项的统计数据
                    const stats = {
                        images: imageCount,
                        medical_records: 0, // 可以后续扩展
                        appointments: 0     // 可以后续扩展
                    };
                    selectedOption.dataset.stats = JSON.stringify(stats);

                    // 显示统计提示
                    let message = `${selectedOption.textContent.split(' (')[0]} - `;
                    if (imageCount > 0) {
                        message += `有${imageCount}个影像，可生成影像分析报告`;
                    } else {
                        message += `暂无影像数据，可生成基础报告`;
                    }
                    showMessage(message, 'info');

                    // 加载并显示患者照片
                    loadPatientPhotos(patientId);
                })
                .catch(error => {
                    console.warn('获取患者统计数据失败:', error);
                    // 即使获取失败也要显示照片选择区域
                    loadPatientPhotos(patientId);
                });
        }

        // 加载患者照片
        function loadPatientPhotos(patientId) {
            if (!patientId) {
                clearPatientStats();
                return;
            }

            const photoContainer = document.getElementById('patient-photos');

            // 显示加载状态
            photoContainer.innerHTML = '<div class="text-center"><div class="spinner-border spinner-border-sm" role="status"></div> 加载中...</div>';
            document.getElementById('photo-selection-area').style.display = 'block';

            // 获取患者照片
            apiRequest(`api/images.php?action=list&patient_id=${patientId}`)
                .then(data => {
                    if (data.images && data.images.length > 0) {
                        displayPatientPhotos(data.images);
                    } else {
                        photoContainer.innerHTML = '<div class="text-center text-muted">该患者暂无照片</div>';
                    }
                })
                .catch(error => {
                    console.error('加载患者照片失败:', error);
                    photoContainer.innerHTML = '<div class="text-center text-danger">加载失败，请重试</div>';
                });
        }

        // 显示患者照片
        function displayPatientPhotos(images) {
            const photoContainer = document.getElementById('patient-photos');

            const html = images.map(image => `
                <div class="photo-item">
                    <div class="photo-checkbox">
                        <input type="checkbox" id="photo-${image.id}" value="${image.id}" onchange="updateSelectedPhotos(${image.id})">
                        <label for="photo-${image.id}" class="photo-label">
                            <img src="${image.file_path}" alt="${image.original_name}" class="photo-thumbnail">
                            <div class="photo-info">
                                <small class="photo-name">${image.original_name}</small>
                                <small class="photo-date">${formatDateTime(image.capture_date)}</small>
                            </div>
                        </label>
                    </div>
                </div>
            `).join('');

            photoContainer.innerHTML = html;
            selectedPhotos = []; // 重置选中状态
            updateSelectedPhotosCount();
        }

        // 更新选中照片
        function updateSelectedPhotos(imageId) {
            const checkbox = document.getElementById(`photo-${imageId}`);
            if (checkbox.checked) {
                if (!selectedPhotos.includes(imageId)) {
                    // 检查是否超过4张照片限制
                    if (selectedPhotos.length >= 4) {
                        checkbox.checked = false;
                        showMessage('AI分析最多只能选择4张照片', 'warning');
                        return;
                    }
                    selectedPhotos.push(imageId);
                }
            } else {
                selectedPhotos = selectedPhotos.filter(id => id != imageId);
            }
            updateSelectedPhotosCount();
        }

        // 更新选中照片计数
        function updateSelectedPhotosCount() {
            const countElement = document.getElementById('selected-photos-count');
            if (countElement) {
                countElement.textContent = selectedPhotos.length;
            }
        }

        // 全选照片（AI分析最多4张）
        function selectAllPhotos() {
            const checkboxes = document.querySelectorAll('#patient-photos input[type="checkbox"]');
            let selectedCount = selectedPhotos.length;

            checkboxes.forEach(checkbox => {
                if (!checkbox.checked && selectedCount < 4) {
                    checkbox.checked = true;
                    updateSelectedPhotos(checkbox.value);
                    selectedCount++;
                }
            });

            if (selectedCount >= 4) {
                showMessage('AI分析最多只能选择4张照片', 'info');
            }
        }

        // 清空照片选择
        function clearPhotoSelection() {
            const checkboxes = document.querySelectorAll('#patient-photos input[type="checkbox"]:checked');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
                updateSelectedPhotos(checkbox.value);
            });
        }

        // 清除患者统计信息
        function clearPatientStats() {
            // 隐藏照片选择区域
            document.getElementById('photo-selection-area').style.display = 'none';
            document.getElementById('patient-photos').innerHTML = '';
            selectedPhotos = [];
            updateSelectedPhotosCount();
        }

        // 获取选中的牙齿病情
        function getSelectedDentalConditions() {
            const conditions = [];
            const checkboxes = document.querySelectorAll('#dental-conditions input[type="checkbox"]:checked');

            checkboxes.forEach(checkbox => {
                if (checkbox.id === 'condition-other') {
                    const otherText = document.getElementById('condition-other-text').value.trim();
                    if (otherText) {
                        conditions.push(otherText);
                    }
                } else {
                    conditions.push(checkbox.value);
                }
            });

            return conditions;
        }

        // 编辑报告时根据病情自动生成诊断结论和治疗建议
        function generateDiagnosisForEdit() {
            const conditions = getSelectedDentalConditions();

            if (conditions.length === 0) {
                showMessage('请先选择牙齿病情', 'warning');
                return;
            }

            const result = generateDiagnosisFromConditions(conditions);
            document.getElementById('edit-diagnosis').value = result.diagnosis;
            document.getElementById('edit-treatment').value = result.treatment;
            showMessage('诊断结论和治疗建议已自动生成', 'success');
        }

        // 根据病情自动生成诊断结论和治疗建议
        function generateDiagnosisFromConditions(conditions) {
            if (!conditions || conditions.length === 0) {
                return { diagnosis: '', treatment: '' };
            }

            let diagnosis = '';
            let treatment = '';

            // 根据不同病情生成相应的诊断描述和治疗建议（从数据库动态获取）
            const conditionData = {};

            // 首先尝试从数据库获取完整的病情数据
            try {
                // 这里我们使用同步的方式获取数据，但实际上应该用异步
                // 为了保持兼容性，我们使用已有的本地存储数据
                const dentalConditions = JSON.parse(localStorage.getItem('dental_conditions') || '[]');

                // 构建条件数据映射
                dentalConditions.forEach(condition => {
                    if (condition.active !== false) {
                        conditionData[condition.name] = {
                            diagnosis: condition.diagnosis_template || `${condition.name}，建议进一步检查治疗。`,
                            treatment: condition.treatment_template || `针对${condition.name}制定相应治疗方案。`
                        };
                    }
                });
            } catch (error) {
                console.warn('无法从本地存储获取病情数据，使用默认数据:', error);
            }

            // 如果没有获取到数据，使用默认的映射
            if (Object.keys(conditionData).length === 0) {
                const defaultConditions = {
                    '龋齿': {
                        diagnosis: '患者存在龋齿病变，建议及时治疗以防止病变进一步发展。',
                        treatment: '建议进行牙齿充填或牙冠修复治疗，改善口腔卫生习惯。'
                    },
                    '牙周炎': {
                        diagnosis: '患者患有牙周炎，牙周组织存在炎症反应，建议进行牙周治疗。',
                        treatment: '建议进行牙周洁治、牙周手术等治疗，定期复查牙周状况。'
                    },
                    '牙齿裂纹': {
                        diagnosis: '牙齿存在裂纹，可能伴随牙本质敏感或牙髓病变。',
                        treatment: '建议进行牙齿修复或牙冠保护，必要时进行牙髓治疗。'
                    },
                    '牙齿脓肿': {
                        diagnosis: '牙齿脓肿形成，可能伴随急性疼痛和肿胀，建议紧急处理。',
                        treatment: '建议立即进行牙齿治疗，包括引流、抗生素治疗和牙齿修复。'
                    },
                    '牙龈炎': {
                        diagnosis: '牙龈组织存在炎症，建议改善口腔卫生习惯。',
                        treatment: '建议进行牙周洁治，指导正确刷牙方法，定期口腔检查。'
                    },
                    '牙齿断裂': {
                        diagnosis: '牙齿断裂，可能需要牙齿修复治疗。',
                        treatment: '建议进行牙齿修复或牙冠治疗以恢复牙齿形态和功能。'
                    },
                    '牙齿着色': {
                        diagnosis: '牙齿存在色素沉着，影响美观。',
                        treatment: '建议进行牙齿美白治疗或牙齿修复以改善牙齿颜色。'
                    },
                    '牙龈退缩': {
                        diagnosis: '牙龈退缩，牙根暴露，可能伴随敏感症状。',
                        treatment: '建议进行牙周治疗和牙根覆盖手术，改善牙龈健康。'
                    },
                    '牙髓炎': {
                        diagnosis: '牙髓组织发炎，可能伴随剧烈疼痛。',
                        treatment: '建议进行牙髓治疗，包括根管治疗以清除感染。'
                    },
                    '根尖周炎': {
                        diagnosis: '牙根尖周围存在炎症，可能伴随肿胀和疼痛。',
                        treatment: '建议进行根管治疗和抗炎治疗。'
                    },
                    '牙齿磨损': {
                        diagnosis: '牙齿出现过度磨损，可能影响美观和功能。',
                        treatment: '建议进行牙齿修复治疗以恢复牙齿形态。'
                    },
                    '牙齿松动': {
                        diagnosis: '牙齿出现松动，可能伴随牙周疾病。',
                        treatment: '建议进行牙周治疗和牙齿固定治疗。'
                    },
                    '口腔溃疡': {
                        diagnosis: '口腔黏膜出现溃疡，可能伴随疼痛。',
                        treatment: '建议使用口腔溃疡药物，促进愈合。'
                    },
                    '智齿冠周炎': {
                        diagnosis: '智齿冠周出现炎症，可能伴随疼痛和肿胀。',
                        treatment: '建议进行智齿手术治疗或暂时抗炎治疗。'
                    },
                    '口腔干燥症': {
                        diagnosis: '口腔干燥，唾液分泌不足。',
                        treatment: '建议改善生活习惯，促进唾液分泌，使用人工唾液替代品。'
                    },
                    '牙齿发育异常': {
                        diagnosis: '牙齿发育存在异常，影响美观和功能。',
                        treatment: '建议进行牙齿修复或正畸治疗以改善牙齿形态。'
                    },
                    '口腔念珠菌病': {
                        diagnosis: '口腔黏膜出现真菌感染，白斑或红斑。',
                        treatment: '建议使用抗真菌药物治疗，改善口腔卫生。'
                    },
                    '口腔白斑': {
                        diagnosis: '口腔黏膜出现白斑，可能为癌前病变。',
                        treatment: '建议进行活检检查，定期随访观察。'
                    },
                    '口腔扁平苔藓': {
                        diagnosis: '口腔黏膜出现扁平苔藓病变。',
                        treatment: '建议使用免疫调节药物治疗，定期复查。'
                    },
                    '错牙合': {
                        diagnosis: '存在错牙合畸形，建议正畸治疗。',
                        treatment: '建议进行正畸治疗以矫正牙齿排列和咬合关系。'
                    },
                    '牙齿敏感': {
                        diagnosis: '牙齿对冷热刺激敏感，可能存在牙本质暴露。',
                        treatment: '建议使用脱敏牙膏，必要时进行牙齿修复治疗。'
                    },
                    '阻生齿': {
                        diagnosis: '存在阻生齿，可能导致周围组织炎症。',
                        treatment: '建议拔除阻生齿或进行手术暴露，预防并发症发生。'
                    }
                };

                Object.assign(conditionData, defaultConditions);
            }

            // 生成诊断结论
            diagnosis = conditions.map(condition => {
                return conditionData[condition]?.diagnosis || `${condition}，建议进一步检查治疗。`;
            }).join('\n\n');

            // 生成治疗建议
            treatment = conditions.map(condition => {
                return conditionData[condition]?.treatment || `针对${condition}制定相应治疗方案。`;
            }).join('\n\n');

            // 如果有多个病情，添加总结性描述
            if (conditions.length > 1) {
                diagnosis += '\n\n综合以上情况，建议制定系统性的治疗计划。';
                treatment += '\n\n建议定期复查，跟踪治疗效果。';
            }

            return { diagnosis, treatment };
        }

        // 填充编辑表单（包括牙齿病情）
        function fillEditForm(report) {
            // 设置基本信息
            const diagnosisElement = document.getElementById('edit-diagnosis');
            const treatmentElement = document.getElementById('edit-treatment');
            const notesElement = document.getElementById('edit-notes');

            if (diagnosisElement) diagnosisElement.value = report.diagnosis || '';
            if (treatmentElement) treatmentElement.value = report.treatment || '';
            if (notesElement) notesElement.value = report.notes || '';

            // 清除之前的选择
            document.querySelectorAll('#dental-conditions input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = false;
            });

            // 清除其他文本框（如果存在）
            const otherTextElement = document.getElementById('condition-other-text');
            if (otherTextElement) {
                otherTextElement.value = '';
            }

            // 设置选中的病情
            if (report.dental_conditions && Array.isArray(report.dental_conditions)) {
                report.dental_conditions.forEach(condition => {
                    const checkbox = document.querySelector(`#dental-conditions input[value="${condition}"]`);
                    if (checkbox) {
                        checkbox.checked = true;
                    } else {
                        // 检查是否是其他类别
                        const otherConditions = ['牙齿敏感', '阻生齿', '牙龈退缩', '牙齿断裂', '牙齿着色'];
                        if (!otherConditions.includes(condition)) {
                            const otherCheckbox = document.getElementById('condition-other');
                            if (otherCheckbox) {
                                otherCheckbox.checked = true;
                                if (otherTextElement) {
                                    otherTextElement.value = condition;
                                }
                            }
                        }
                    }
                });
            }
        }

        // 更新报告（包括牙齿病情和影像）
        function updateReport() {
            if (!currentReport) {
                showMessage('请先选择要编辑的报告', 'warning');
                return;
            }

            const dentalConditions = getSelectedDentalConditions();
            const diagnosis = document.getElementById('edit-diagnosis')?.value || '';
            const treatment = document.getElementById('edit-treatment')?.value || '';
            const notes = document.getElementById('edit-notes')?.value || '';

            // 更新当前报告
            currentReport.dental_conditions = dentalConditions;
            currentReport.diagnosis = diagnosis;
            currentReport.treatment = treatment;
            currentReport.notes = notes;

            // 影像数据已经在updateReportImages中更新，这里不需要重复处理

            // 重新显示报告
            displayReport(currentReport);
            bootstrap.Modal.getInstance(document.getElementById('editReportModal')).hide();

            showMessage('报告更新成功', 'success');
        }

        // 编辑报告
        function editReport() {
            if (!currentReport) {
                showMessage('请先生成报告', 'warning');
                return;
            }

            // 先初始化牙齿病情选择和影像选择，然后填充表单
            Promise.all([
                initEditDentalConditions(),
                initEditImageSelection()
            ]).then(() => {
                fillEditForm(currentReport);
                new bootstrap.Modal(document.getElementById('editReportModal')).show();
            }).catch(error => {
                console.error('初始化数据失败:', error);
                // 即使初始化失败也要显示模态框
                fillEditForm(currentReport);
                new bootstrap.Modal(document.getElementById('editReportModal')).show();
            });
        }

        // 加载排行数据
        function loadRankings() {
            // 加载病情排行
            loadConditionRanking();

            // 加载患者影像排行
            loadPatientImageRanking();

            // 加载就诊频率排行
            loadPatientVisitRanking();
        }

        // 刷新排行数据
        function refreshRankings() {
            showMessage('正在刷新数据...', 'info');
            loadRankings();
        }

        // 加载病情排行
        function loadConditionRanking() {
            const container = document.getElementById('condition-ranking');

            apiRequest('api/patients.php?action=rankings&type=conditions&limit=8')
                .then(data => {
                    if (data.rankings && data.rankings.conditions) {
                        displayRankingList(container, data.rankings.conditions, 'condition', 'count');
                    } else {
                        // 如果没有真实数据，使用模拟数据
                        const mockConditions = [
                            { condition: '龋齿', count: 45 },
                            { condition: '牙周炎', count: 32 },
                            { condition: '牙齿裂纹', count: 28 },
                            { condition: '牙齿敏感', count: 25 },
                            { condition: '牙龈炎', count: 22 },
                            { condition: '错牙合', count: 18 },
                            { condition: '牙齿着色', count: 15 },
                            { condition: '阻生齿', count: 12 }
                        ];
                        displayRankingList(container, mockConditions, 'condition', 'count');
                    }
                })
                .catch(error => {
                    console.error('加载病情排行失败:', error);
                    // 使用模拟数据作为后备
                    const mockConditions = [
                        { condition: '龋齿', count: 45 },
                        { condition: '牙周炎', count: 32 },
                        { condition: '牙齿裂纹', count: 28 },
                        { condition: '牙齿敏感', count: 25 }
                    ];
                    displayRankingList(container, mockConditions, 'condition', 'count');
                });
        }

        // 加载患者影像排行
        function loadPatientImageRanking() {
            const container = document.getElementById('patient-image-ranking');

            apiRequest('api/patients.php?action=rankings&type=images&limit=8')
                .then(data => {
                    if (data.rankings && data.rankings.patient_images) {
                        displayRankingList(container, data.rankings.patient_images, 'name', 'count');
                    } else {
                        // 如果没有真实数据，显示空状态
                        container.innerHTML = '<p class="text-muted text-center">暂无影像数据</p>';
                    }
                })
                .catch(error => {
                    console.error('加载患者影像排行失败:', error);
                    container.innerHTML = '<p class="text-muted text-center">加载失败</p>';
                });
        }

        // 加载就诊频率排行
        function loadPatientVisitRanking() {
            const container = document.getElementById('patient-visit-ranking');

            apiRequest('api/patients.php?action=rankings&type=visits&limit=8')
                .then(data => {
                    if (data.rankings && data.rankings.patient_visits) {
                        displayRankingList(container, data.rankings.patient_visits, 'name', 'count');
                    } else {
                        // 如果没有真实数据，显示空状态
                        container.innerHTML = '<p class="text-muted text-center">暂无就诊记录</p>';
                    }
                })
                .catch(error => {
                    console.error('加载就诊频率排行失败:', error);
                    container.innerHTML = '<p class="text-muted text-center">加载失败</p>';
                });
        }

        // 显示排行列表
        function displayRankingList(container, data, nameField, countField) {
            if (!data || data.length === 0) {
                container.innerHTML = '<p class="text-muted text-center">暂无数据</p>';
                return;
            }

            const html = data.slice(0, 8).map((item, index) => `
                <div class="ranking-item d-flex justify-content-between align-items-center mb-2">
                    <div class="ranking-info">
                        <span class="ranking-number">${index + 1}</span>
                        <span class="ranking-name">${item[nameField]}</span>
                    </div>
                    <div class="ranking-count badge bg-primary">${item[countField]}</div>
                </div>
            `).join('');

            container.innerHTML = html;
        }

    </script>

    <!-- Footer -->
    <footer class="system-footer">
        <div class="footer-content">
            <div class="copyright-info">
                <p>&copy; 2025 义乌市噢欧进出口有限公司 | <a href="http://silubaba.com.cn" target="_blank">silubaba.com.cn</a></p>
                <p>技术支持: 15057908025</p>
            </div>
        </div>
    </footer>

    <script src="assets/js/language-switcher.js"></script>
</body>
</html>
