<?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 data-i18n="patients_management_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">
    <style>
        /* Pagination Styles */
        .pagination-container {
            margin-top: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }

        .pagination-wrapper {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            flex-wrap: wrap;
            gap: 15px;
        }

        .pagination-info {
            font-size: 14px;
            color: #6c757d;
        }

        .pagination-info span {
            margin: 0 2px;
        }

        .pagination-info .current-page-info,
        .pagination-info .total-entries,
        .pagination-info .total-pages {
            font-weight: 600;
            color: #495057;
        }

        .pagination {
            margin: 0;
        }

        .pagination .page-link {
            color: #007bff;
            border-color: #dee2e6;
            padding: 8px 12px;
            margin: 0 2px;
            border-radius: 4px !important;
            font-size: 14px;
            text-decoration: none;
            transition: all 0.2s ease;
        }

        .pagination .page-link:hover {
            color: #0056b3;
            background-color: #e9ecef;
            border-color: #adb5bd;
        }

        .pagination .page-item.active .page-link {
            background-color: #007bff;
            border-color: #007bff;
            color: white;
        }

        .pagination .page-item.disabled .page-link {
            color: #6c757d;
            pointer-events: none;
            cursor: not-allowed;
            background-color: #fff;
            border-color: #dee2e6;
        }

        /* Responsive pagination */
        @media (max-width: 768px) {
            .pagination-wrapper {
                flex-direction: column;
                align-items: stretch;
            }

            .pagination-info {
                text-align: center;
                order: 2;
            }

            .pagination {
                order: 1;
                justify-content: center;
            }

            .pagination .page-link {
                padding: 6px 8px;
                font-size: 12px;
            }
        }

        /* Loading overlay for pagination */
        .pagination-container.loading {
            opacity: 0.6;
            pointer-events: none;
        }

        /* Dental Photos Styles */
        .dental-photos-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
            gap: 15px;
            margin-bottom: 10px;
        }

        .dental-photo-item {
            text-align: center;
        }

        .dental-photo-container {
            position: relative;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .dental-photo-container:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }

        .dental-photo-thumbnail {
            width: 100%;
            height: 90px;
            object-fit: cover;
            border-radius: 8px;
            cursor: pointer;
            transition: opacity 0.2s ease;
        }

        .dental-photo-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.6);
            display: flex;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.2s ease;
        }

        .dental-photo-container:hover .dental-photo-overlay {
            opacity: 1;
        }

        .dental-photo-info {
            margin-top: 5px;
            font-size: 11px;
            line-height: 1.3;
        }

        /* 批量删除样式 */
        .checkbox-column {
            width: 40px;
            text-align: center;
        }

        .checkbox-column input[type="checkbox"] {
            transform: scale(1.2);
            cursor: pointer;
        }

        .batch-actions {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .batch-delete-btn {
            background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: none;
        }

        .batch-delete-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
        }

        .batch-delete-btn i {
            margin-right: 5px;
        }

        .selected-count {
            background: #f8f9fa;
            color: #495057;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 600;
            display: none;
        }
    </style>
    <script src="assets/js/vendor/bootstrap.bundle.min.js"></script>
    <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 data-i18n="dashboard">仪表板</span>
                    </a>
                </li>
                <li class="menu-item active">
                    <a href="patients.php" class="menu-link">
                        <i class="fas fa-users"></i>
                        <span data-i18n="patients">患者管理</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="capture.php" class="menu-link">
                        <i class="fas fa-camera"></i>
                        <span data-i18n="capture">影像采集</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="comparison.php" class="menu-link">
                        <i class="fas fa-exchange-alt"></i>
                        <span data-i18n="comparison">影像对比</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="edit.php" class="menu-link">
                        <i class="fas fa-edit"></i>
                        <span data-i18n="edit">影像编辑</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="reports.php" class="menu-link">
                        <i class="fas fa-file-medical"></i>
                        <span data-i18n="reports">报告管理</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="settings.php" class="menu-link">
                        <i class="fas fa-cog"></i>
                        <span data-i18n="settings">系统设置</span>
                    </a>
                </li>
                <li class="menu-item">
                    <a href="help.php" class="menu-link">
                        <i class="fas fa-question-circle"></i>
                        <span data-i18n="help">帮助中心</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" data-i18n="patients_management">患者管理</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>
                    <?php echo getUserDisplayHtml(); ?>
                </div>
            </header>

            <!-- Patients Content -->
            <div class="content-wrapper">
                <!-- Action Bar -->
                <div class="action-bar">
                    <div class="action-bar-left">
                        <div class="search-box">
                            <i class="fas fa-search"></i>
                            <input type="text" id="patient-search" data-i18n="placeholder_search_patient" placeholder="搜索患者姓名、电话或身份证号...">
                        </div>
                    </div>
                    <div class="action-bar-right">
                        <div class="batch-actions">
                            <span class="selected-count" id="selected-count">已选择 0 项</span>
                            <button class="batch-delete-btn" id="batch-delete-btn" onclick="batchDeletePatients()">
                                <i class="fas fa-trash"></i>
                                批量删除
                            </button>
                        </div>
                        <button class="btn btn-outline-primary" onclick="exportPatients()" data-i18n="export">
                            <i class="fas fa-download"></i>
                            导出
                        </button>
                        <button class="btn btn-outline-success" onclick="showImportModal()" data-i18n="import_patients">
                            <i class="fas fa-upload"></i>
                            导入
                        </button>
                        <button class="btn btn-primary" onclick="showAddPatientModal()" data-i18n="add_patient">
                            <i class="fas fa-plus"></i>
                            添加患者
                        </button>
                    </div>
                </div>

                <!-- Patient Stats -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="stat-content">
                            <h3 id="total-patients">0</h3>
                            <p data-i18n="total_patients">总患者数</p>
                        </div>
                    </div>

                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-user-plus"></i>
                        </div>
                        <div class="stat-content">
                            <h3 id="new-patients-month">0</h3>
                            <p data-i18n="new_patients_this_month">本月新增</p>
                        </div>
                    </div>

                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-calendar-check"></i>
                        </div>
                        <div class="stat-content">
                            <h3 id="active-appointments">0</h3>
                            <p data-i18n="active_appointments">活跃预约</p>
                        </div>
                    </div>

                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-file-medical"></i>
                        </div>
                        <div class="stat-content">
                            <h3 id="total-records">0</h3>
                            <p data-i18n="medical_records">健康档案</p>
                        </div>
                    </div>
                </div>

                <!-- Patient Management Tabs -->
                <div class="patient-tabs">
                    <div class="tabs-header">
                        <button class="tab-btn active" data-tab="patients">
                            <i class="fas fa-users"></i>
                            <span data-i18n="patient_list">患者列表</span>
                        </button>
                        <button class="tab-btn" data-tab="medical-records">
                            <i class="fas fa-file-medical"></i>
                            <span data-i18n="medical_records">健康档案</span>
                        </button>
                        <button class="tab-btn" data-tab="appointments">
                            <i class="fas fa-calendar-alt"></i>
                            <span data-i18n="appointment_management">预约管理</span>
                        </button>
                    </div>

                    <div class="tabs-content">
                        <!-- Patients List Tab -->
                        <div class="tab-panel active" id="patients-panel">
                            <div class="data-table-container">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th class="checkbox-column">
                                                <input type="checkbox" id="select-all-checkbox" onclick="toggleAllCheckboxes()">
                                            </th>
                                            <th data-i18n="name">姓名</th>
                                            <th data-i18n="gender">性别</th>
                                            <th data-i18n="age">年龄</th>
                                            <th data-i18n="phone">联系电话</th>
                                            <th data-i18n="id_card">身份证号</th>
                                            <th data-i18n="registration_time">注册时间</th>
                                            <th data-i18n="actions">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="patients-list">
                                        <!-- 患者列表将通过JavaScript加载 -->
                                    </tbody>
                                </table>
                            </div>

                            <!-- Pagination for Patients List -->
                            <div class="pagination-container" id="patients-pagination">
                                <!-- Pagination controls will be inserted here by JavaScript -->
                            </div>
                        </div>

                        <!-- Medical Records Tab -->
                        <div class="tab-panel" id="medical-records-panel">
                            <div class="tab-header">
                                <button class="btn btn-primary" onclick="showAddMedicalRecordModal()" data-i18n="add_medical_record">
                                    <i class="fas fa-plus"></i>
                                    添加就诊记录
                                </button>
                            </div>
                            <div class="data-table-container">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th data-i18n="patient_name">患者姓名</th>
                                            <th data-i18n="visit_date">就诊日期</th>
                                            <th data-i18n="visit_type">就诊类型</th>
                                            <th data-i18n="chief_complaint">主诉</th>
                                            <th data-i18n="diagnosis">诊断结果</th>
                                            <th data-i18n="doctor">医生</th>
                                            <th data-i18n="actions">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="medical-records-list">
                                        <!-- 健康档案列表将通过JavaScript加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>

                        <!-- Appointments Tab -->
                        <div class="tab-panel" id="appointments-panel">
                            <div class="tab-header">
                                <button class="btn btn-success" onclick="showAddAppointmentModal()" data-i18n="add_appointment">
                                    <i class="fas fa-plus"></i>
                                    添加预约
                                </button>
                            </div>
                            <div class="data-table-container">
                                <table class="data-table">
                                    <thead>
                                        <tr>
                                            <th data-i18n="patient_name">患者姓名</th>
                                            <th data-i18n="appointment_time">预约时间</th>
                                            <th data-i18n="appointment_type">预约类型</th>
                                            <th data-i18n="status">状态</th>
                                            <th data-i18n="doctor">医生</th>
                                            <th data-i18n="notes">备注</th>
                                            <th data-i18n="actions">操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="appointments-list">
                                        <!-- 预约列表将通过JavaScript加载 -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- 添加患者模态框 -->
    <div class="modal fade" id="addPatientModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" data-i18n="add_patient">添加患者</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="add-patient-form">
                        <div class="mb-3">
                            <label for="patient-name" class="form-label" data-i18n="name_required">姓名 *</label>
                            <input type="text" id="patient-name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label for="patient-gender" class="form-label" data-i18n="gender_required">性别 *</label>
                            <select id="patient-gender" class="form-select" required>
                                <option value="male" data-i18n="male">男</option>
                                <option value="female" data-i18n="female">女</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="patient-age" class="form-label" data-i18n="age_required">年龄 *</label>
                            <input type="number" id="patient-age" class="form-control" required min="1" max="150">
                        </div>
                        <div class="mb-3">
                            <label for="patient-id-card" class="form-label" data-i18n="id_card">身份证号</label>
                            <input type="text" id="patient-id-card" class="form-control" maxlength="18">
                        </div>
                        <div class="mb-3">
                            <label for="patient-phone" class="form-label" data-i18n="phone">联系电话</label>
                            <input type="tel" id="patient-phone" class="form-control" maxlength="20">
                        </div>
                        <div class="mb-3">
                            <label for="patient-address" class="form-label" data-i18n="address">地址</label>
                            <textarea id="patient-address" class="form-control" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-i18n="cancel">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addPatient()" data-i18n="save">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑患者模态框 -->
    <div class="modal fade" id="editPatientModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" data-i18n="edit_patient">编辑患者</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="edit-patient-form">
                        <input type="hidden" id="edit-patient-id">
                        <div class="mb-3">
                            <label for="edit-patient-name" class="form-label" data-i18n="name_required">姓名 *</label>
                            <input type="text" id="edit-patient-name" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label for="edit-patient-gender" class="form-label" data-i18n="gender_required">性别 *</label>
                            <select id="edit-patient-gender" class="form-select" required>
                                <option value="male" data-i18n="male">男</option>
                                <option value="female" data-i18n="female">女</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="edit-patient-age" class="form-label" data-i18n="age_required">年龄 *</label>
                            <input type="number" id="edit-patient-age" class="form-control" required min="1" max="150">
                        </div>
                        <div class="mb-3">
                            <label for="edit-patient-id-card" class="form-label" data-i18n="id_card">身份证号</label>
                            <input type="text" id="edit-patient-id-card" class="form-control" maxlength="18">
                        </div>
                        <div class="mb-3">
                            <label for="edit-patient-phone" class="form-label" data-i18n="phone">联系电话</label>
                            <input type="tel" id="edit-patient-phone" class="form-control" maxlength="20">
                        </div>
                        <div class="mb-3">
                            <label for="edit-patient-address" class="form-label" data-i18n="address">地址</label>
                            <textarea id="edit-patient-address" class="form-control" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-i18n="cancel">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updatePatient()" data-i18n="save">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 患者导入模态框 -->
    <div class="modal fade" id="importPatientsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" data-i18n="import_patients">批量导入患者</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-info">
                        <h6 data-i18n="import_instructions">导入说明：</h6>
                        <ul class="mb-0">
                            <li data-i18n="import_format_support">支持 CSV 或 Excel 格式文件</li>
                            <li data-i18n="import_required_fields">必须包含姓名、性别、年龄字段</li>
                            <li data-i18n="import_optional_fields">可选字段：身份证号、联系电话、地址等</li>
                            <li data-i18n="import_data_format">第一行为表头，第二行开始为数据</li>
                        </ul>
                    </div>
                    <div class="mb-3">
                        <label for="import-file" class="form-label" data-i18n="select_file">选择文件</label>
                        <input type="file" id="import-file" class="form-control" accept=".csv,.xlsx,.xls">
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="skip-duplicates" checked>
                            <label class="form-check-label" for="skip-duplicates" data-i18n="skip_duplicates">
                                跳过重复患者（根据身份证号判断）
                            </label>
                        </div>
                    </div>
                    <div id="import-preview" style="display: none;">
                        <h6 data-i18n="preview_data">预览数据：</h6>
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered" id="import-preview-table"></table>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-i18n="cancel">取消</button>
                    <button type="button" class="btn btn-primary" onclick="processImport()" data-i18n="start_import">开始导入</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加健康档案模态框 -->
    <div class="modal fade" id="addMedicalRecordModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" data-i18n="add_medical_record">添加就诊记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="add-medical-record-form">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="record-patient-select" class="form-label" data-i18n="select_patient_required">选择患者 *</label>
                                    <select id="record-patient-select" class="form-select" required>
                                        <option value="" data-i18n="please_select_patient">请选择患者...</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="visit-date" class="form-label" data-i18n="visit_date_required">就诊日期 *</label>
                                    <input type="datetime-local" id="visit-date" class="form-control" required>
                                </div>
                                <div class="mb-3">
                                    <label for="visit-type" class="form-label" data-i18n="visit_type_required">就诊类型 *</label>
                                    <select id="visit-type" class="form-select" required>
                                        <option value="checkup" data-i18n="checkup">常规检查</option>
                                        <option value="treatment" data-i18n="treatment">治疗</option>
                                        <option value="consultation" data-i18n="consultation">咨询</option>
                                        <option value="emergency" data-i18n="emergency">急诊</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="chief-complaint" class="form-label" data-i18n="chief_complaint">主诉</label>
                                    <textarea id="chief-complaint" class="form-control" rows="3" data-i18n="placeholder_chief_complaint" placeholder="患者主要症状描述..."></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="diagnosis" class="form-label" data-i18n="diagnosis">诊断结论</label>
                                    <textarea id="diagnosis" class="form-control" rows="3" data-i18n="placeholder_diagnosis" placeholder="诊断结果..."></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="examination-findings" class="form-label" data-i18n="examination_findings">检查所见</label>
                                    <textarea id="examination-findings" class="form-control" rows="4" data-i18n="placeholder_examination_findings" placeholder="检查结果描述..."></textarea>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="treatment-plan" class="form-label" data-i18n="treatment_plan">治疗方案</label>
                                    <textarea id="treatment-plan" class="form-control" rows="4" data-i18n="placeholder_treatment_plan" placeholder="治疗计划和方案..."></textarea>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="record-notes" class="form-label" data-i18n="notes">备注</label>
                            <textarea id="record-notes" class="form-control" rows="2" data-i18n="placeholder_notes" placeholder="其他备注信息..."></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-i18n="cancel">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addMedicalRecord()" data-i18n="save_record">保存记录</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加预约模态框 -->
    <div class="modal fade" id="addAppointmentModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" data-i18n="add_appointment">添加预约</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="add-appointment-form">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-patient-select" class="form-label" data-i18n="select_patient_required">选择患者 *</label>
                                    <select id="appointment-patient-select" class="form-select" required>
                                        <option value="" data-i18n="please_select_patient">请选择患者...</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label for="appointment-date" class="form-label" data-i18n="appointment_datetime_required">预约日期时间 *</label>
                                    <input type="datetime-local" id="appointment-date" class="form-control" required>
                                </div>
                                <div class="mb-3">
                                    <label for="appointment-type" class="form-label" data-i18n="appointment_type_required">预约类型 *</label>
                                    <select id="appointment-type" class="form-select" required>
                                        <option value="checkup" data-i18n="checkup">常规检查</option>
                                        <option value="treatment" data-i18n="treatment">治疗</option>
                                        <option value="consultation" data-i18n="consultation">咨询</option>
                                        <option value="emergency" data-i18n="emergency">急诊</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="service-type" class="form-label" data-i18n="service_type">服务项目</label>
                                    <input type="text" id="service-type" class="form-control" data-i18n="placeholder_service_type" placeholder="如：牙齿检查、补牙等">
                                </div>
                                <div class="mb-3">
                                    <label for="duration" class="form-label" data-i18n="duration_minutes">预计时长（分钟）</label>
                                    <input type="number" id="duration" class="form-control" value="30" min="15" max="240">
                                </div>
                                <div class="mb-3">
                                    <label for="priority" class="form-label" data-i18n="priority">优先级</label>
                                    <select id="priority" class="form-select">
                                        <option value="low" data-i18n="low">普通</option>
                                        <option value="normal" selected data-i18n="normal">正常</option>
                                        <option value="high" data-i18n="high">重要</option>
                                        <option value="urgent" data-i18n="urgent">紧急</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="appointment-notes" class="form-label" data-i18n="appointment_notes">预约备注</label>
                            <textarea id="appointment-notes" class="form-control" rows="2" data-i18n="placeholder_appointment_notes" placeholder="特殊要求或注意事项..."></textarea>
                        </div>
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="send-reminder">
                                <label class="form-check-label" for="send-reminder" data-i18n="send_reminder">
                                    发送预约提醒
                                </label>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-i18n="cancel">取消</button>
                    <button type="button" class="btn btn-success" onclick="addAppointment()" data-i18n="create_appointment">创建预约</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查看患者详情模态框 -->
    <div class="modal fade" id="viewPatientModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" data-i18n="patient_details">患者详细信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="patient-detail-info" id="patientDetailContent">
                        <!-- 患者详细信息将在这里显示 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal" data-i18n="close">关闭</button>
                    <button type="button" class="btn btn-primary" onclick="editPatientFromView()" data-i18n="edit_patient">编辑患者</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 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/main.js"></script>
    <script src="assets/js/patient.js"></script>
    <script>
        // Dashboard functionality for patients 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');
            });

            // Tab switching functionality
            const tabButtons = document.querySelectorAll('.tab-btn');
            tabButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const tabName = this.dataset.tab;

                    // Remove active class from all buttons and panels
                    document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
                    document.querySelectorAll('.tab-panel').forEach(panel => panel.classList.remove('active'));

                    // Add active class to clicked button and corresponding panel
                    this.classList.add('active');
                    document.getElementById(tabName + '-panel').classList.add('active');

                    // Load data based on selected tab
                    switch(tabName) {
                        case 'patients':
                            loadPatients();
                            break;
                        case 'medical-records':
                            loadMedicalRecords();
                            break;
                        case 'appointments':
                            loadAppointments();
                            break;
                    }
                });
            });

            // Search functionality
            document.getElementById('patient-search').addEventListener('input', function() {
                const activeTab = document.querySelector('.tab-btn.active').dataset.tab;
                const searchTerm = this.value;

                switch(activeTab) {
                    case 'patients':
                        loadPatients(1, 30, searchTerm);
                        break;
                    case 'medical-records':
                        loadMedicalRecords(1, 10, searchTerm);
                        break;
                    case 'appointments':
                        loadAppointments(1, 10, searchTerm);
                        break;
                }
            });

            // Load initial data
            loadPatients();
            loadPatientStats();

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

            // 初始化批量删除功能
            initBatchDelete();
        });

        // Load patient statistics
        function loadPatientStats() {
            // Load patient count
            fetch('api/patients.php?action=list&limit=1')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        document.getElementById('total-patients').textContent = data.data.total;
                        // Mock additional stats for now
                        document.getElementById('new-patients-month').textContent = Math.floor(data.data.total * 0.15);
                        document.getElementById('active-appointments').textContent = Math.floor(Math.random() * 20) + 5;
                        document.getElementById('total-records').textContent = Math.floor(data.data.total * 2.5);
                    }
                })
                .catch(error => console.error('加载患者统计失败:', error));
        }

        // Enhanced loadPatients function to work with new table structure
        function loadPatients(page = 1, limit = 50, search = '') {
            console.log(`loadPatients called: page=${page}, limit=${limit}, search="${search}", searchLength=${search.length}`);
            showLoading();

            let url = `api/patients.php?action=list&page=${page}&limit=${limit}`;
            if (search && search.trim()) {  // 确保搜索字符串不为空或只含空白字符
                url += `&search=${encodeURIComponent(search.trim())}`;
                console.log(`Added search parameter: "${search.trim()}"`);
            } else {
                console.log('No search parameter added (empty or whitespace only)');
            }
            console.log(`Final API URL: ${url}`);

            fetch(url)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    return response.json();
                })
                .then(data => {
                    hideLoading();
                    if (data.success && data.data) {
                        displayPatients(data.data.patients || []);
                        console.log('分页数据:', {
                            total: data.data.total,
                            page: data.data.page,
                            limit: data.data.limit,
                            total_pages: data.data.total_pages,
                            patients_count: data.data.patients.length
                        });
                        updatePagination(data.data.total_pages, data.data.page, 'loadPatients');
                    } else {
                        showMessage('加载患者列表失败: ' + (data.message || '未知错误'), 'danger');
                        displayEmptyPatients();
                    }
                })
                .catch(error => {
                    hideLoading();
                    console.error('加载患者列表错误:', error);
                    showMessage('网络错误，请检查连接后重试', 'danger');
                    displayErrorPatients();
                });
        }

        // Enhanced displayPatients function for new table structure
        function displayPatients(patients) {
            const tbody = document.getElementById('patients-list');

            if (patients.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="8" class="text-center py-5">
                            <div class="empty-state">
                                <i class="fas fa-users fa-3x text-muted mb-3"></i>
                                <p class="text-muted">暂无患者数据</p>
                                <button class="btn btn-primary" onclick="showAddPatientModal()">
                                    <i class="fas fa-plus"></i> 添加第一个患者
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
                return;
            }

            tbody.innerHTML = patients.map(patient => `
                <tr>
                    <td class="checkbox-column">
                        <input type="checkbox" class="patient-checkbox" value="${patient.id}" onchange="updateBatchDeleteButton()">
                    </td>
                    <td>
                        <div class="d-flex align-items-center">
                            <div class="avatar-circle me-2">
                                ${patient.name.charAt(0).toUpperCase()}
                            </div>
                            <strong>${patient.name}</strong>
                        </div>
                    </td>
                    <td>${patient.gender === 'male' ? '男' : '女'}</td>
                    <td>${patient.age}岁</td>
                    <td>${patient.phone || '-'}</td>
                    <td>${patient.id_card ? patient.id_card.substring(0, 6) + '****' + patient.id_card.substring(14) : '-'}</td>
                    <td>${formatDateTime(patient.created_at)}</td>
                    <td>
                        <button class="action-btn edit" onclick="editPatient(${patient.id})" title="编辑">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="action-btn view" onclick="viewPatient(${patient.id})" title="查看详情">
                            <i class="fas fa-eye"></i> 查看
                        </button>
                        <button class="action-btn" onclick="selectPatientForRecords(${patient.id})" title="管理档案" style="background: #17a2b8; color: white;">
                            <i class="fas fa-folder-open"></i> 档案
                        </button>
                        <button class="action-btn delete" onclick="deletePatient(${patient.id})" title="删除">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 健康档案管理功能
        let currentPatientId = null;

        function loadMedicalRecords(page = 1, limit = 50, search = '') {
            if (!currentPatientId) return;

            showLoading();
            const tbody = document.getElementById('medical-records-list');

            let url = `api/medical_records.php?action=list&patient_id=${currentPatientId}&page=${page}&limit=${limit}`;
            if (search) {
                url += `&search=${encodeURIComponent(search)}`;
            }

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.success) {
                        displayMedicalRecords(data.records, data.total, data.page, data.total_pages);
                    } else {
                        showMessage('加载健康档案失败: ' + data.message, 'danger');
                        displayEmptyMedicalRecords();
                    }
                })
                .catch(error => {
                    hideLoading();
                    console.error('加载健康档案失败:', error);
                    showMessage('网络错误，请稍后重试', 'danger');
                    displayErrorMedicalRecords();
                });
        }

        function displayMedicalRecords(records, total, page, totalPages) {
            const tbody = document.getElementById('medical-records-list');

            if (records.length === 0) {
                displayEmptyMedicalRecords();
                return;
            }

            tbody.innerHTML = records.map(record => `
                <tr>
                    <td>${record.patient_name}</td>
                    <td>${formatDateTime(record.visit_date)}</td>
                    <td>
                        <span class="badge bg-${getVisitTypeColor(record.visit_type)}">
                            ${getVisitTypeName(record.visit_type)}
                        </span>
                    </td>
                    <td class="text-truncate" style="max-width: 200px;" title="${record.chief_complaint || '-'}">
                        ${record.chief_complaint || '-'}
                    </td>
                    <td class="text-truncate" style="max-width: 200px;" title="${record.diagnosis || '-'}">
                        ${record.diagnosis || '-'}
                    </td>
                    <td>${record.doctor_name || '-'}</td>
                    <td>
                        <button class="action-btn view" onclick="viewMedicalRecord(${record.id})" title="查看详情">
                            <i class="fas fa-eye"></i> 查看
                        </button>
                        <button class="action-btn edit" onclick="editMedicalRecord(${record.id})" title="编辑">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="action-btn delete" onclick="deleteMedicalRecord(${record.id})" title="删除">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                </tr>
            `).join('');

            // 更新分页（如果需要）
            updatePagination(totalPages, page, 'loadMedicalRecords');
        }

        function displayEmptyMedicalRecords() {
            const tbody = document.getElementById('medical-records-list');
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-5">
                        <div class="empty-state">
                            <i class="fas fa-file-medical fa-3x text-muted mb-3"></i>
                            <p class="text-muted">暂无健康档案数据</p>
                            <button class="btn btn-primary" onclick="showAddMedicalRecordModal()">
                                <i class="fas fa-plus"></i> 添加就诊记录
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }

        function displayErrorMedicalRecords() {
            const tbody = document.getElementById('medical-records-list');
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-5">
                        <div class="empty-state">
                            <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                            <p class="text-muted">加载数据失败，请稍后重试</p>
                            <button class="btn btn-primary" onclick="loadMedicalRecords()">
                                <i class="fas fa-refresh"></i> 重新加载
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }

        function getVisitTypeName(type) {
            const types = {
                'checkup': '检查',
                'treatment': '治疗',
                'consultation': '咨询',
                'emergency': '急诊'
            };
            return types[type] || type;
        }

        function getVisitTypeColor(type) {
            const colors = {
                'checkup': 'info',
                'treatment': 'primary',
                'consultation': 'secondary',
                'emergency': 'danger'
            };
            return colors[type] || 'secondary';
        }

        // 预约管理功能
        function loadAppointments(page = 1, limit = 50, search = '') {
            if (!currentPatientId) return;

            showLoading();
            const tbody = document.getElementById('appointments-list');

            let url = `api/appointments.php?action=list&patient_id=${currentPatientId}&page=${page}&limit=${limit}`;
            if (search) {
                url += `&search=${encodeURIComponent(search)}`;
            }

            fetch(url)
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.success) {
                        displayAppointments(data.appointments, data.total, data.page, data.total_pages);
                    } else {
                        showMessage('加载预约记录失败: ' + data.message, 'danger');
                        displayEmptyAppointments();
                    }
                })
                .catch(error => {
                    hideLoading();
                    console.error('加载预约记录失败:', error);
                    showMessage('网络错误，请稍后重试', 'danger');
                    displayErrorAppointments();
                });
        }

        function displayAppointments(appointments, total, page, totalPages) {
            const tbody = document.getElementById('appointments-list');

            if (appointments.length === 0) {
                displayEmptyAppointments();
                return;
            }

            tbody.innerHTML = appointments.map(appointment => `
                <tr>
                    <td>${appointment.patient_name}</td>
                    <td>${formatDateTime(appointment.appointment_date)}</td>
                    <td>
                        <span class="badge bg-${getAppointmentTypeColor(appointment.appointment_type)}">
                            ${getAppointmentTypeName(appointment.appointment_type)}
                        </span>
                    </td>
                    <td>
                        <span class="status-badge status-${getAppointmentStatusClass(appointment.status)}">
                            ${getAppointmentStatusName(appointment.status)}
                        </span>
                    </td>
                    <td>${appointment.doctor_name || '-'}</td>
                    <td class="text-truncate" style="max-width: 150px;" title="${appointment.notes || ''}">
                        ${appointment.notes || '-'}
                    </td>
                    <td>
                        <button class="action-btn view" onclick="viewAppointment(${appointment.id})" title="查看详情">
                            <i class="fas fa-eye"></i> 查看
                        </button>
                        <button class="action-btn edit" onclick="editAppointment(${appointment.id})" title="编辑">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="action-btn delete" onclick="deleteAppointment(${appointment.id})" title="删除">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </td>
                </tr>
            `).join('');

            // 更新分页（如果需要）
            updatePagination(totalPages, page, 'loadAppointments');
        }

        function displayEmptyAppointments() {
            const tbody = document.getElementById('appointments-list');
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-5">
                        <div class="empty-state">
                            <i class="fas fa-calendar-alt fa-3x text-muted mb-3"></i>
                            <p class="text-muted">暂无预约数据</p>
                            <button class="btn btn-success" onclick="showAddAppointmentModal()">
                                <i class="fas fa-plus"></i> 添加预约
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }

        function displayErrorAppointments() {
            const tbody = document.getElementById('appointments-list');
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-5">
                        <div class="empty-state">
                            <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                            <p class="text-muted">加载数据失败，请稍后重试</p>
                            <button class="btn btn-primary" onclick="loadAppointments()">
                                <i class="fas fa-refresh"></i> 重新加载
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }

        function getAppointmentTypeName(type) {
            const types = {
                'checkup': '检查',
                'treatment': '治疗',
                'consultation': '咨询',
                'emergency': '急诊'
            };
            return types[type] || type;
        }

        function getAppointmentTypeColor(type) {
            const colors = {
                'checkup': 'info',
                'treatment': 'primary',
                'consultation': 'secondary',
                'emergency': 'danger'
            };
            return colors[type] || 'secondary';
        }

        function getAppointmentStatusName(status) {
            const statuses = {
                'scheduled': '已预约',
                'confirmed': '已确认',
                'completed': '已完成',
                'cancelled': '已取消',
                'no_show': '未到场'
            };
            return statuses[status] || status;
        }

        function getAppointmentStatusClass(status) {
            const classes = {
                'scheduled': 'pending',
                'confirmed': 'completed',
                'completed': 'completed',
                'cancelled': 'cancelled',
                'no_show': 'cancelled'
            };
            return classes[status] || 'pending';
        }

        // 更新标签页切换逻辑
        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');
            });

            // 标签页切换逻辑
            const tabButtons = document.querySelectorAll('.tab-btn');
            tabButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const tabName = this.dataset.tab;

                    // Remove active class from all buttons and panels
                    document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
                    document.querySelectorAll('.tab-panel').forEach(panel => panel.classList.remove('active'));

                    // Add active class to clicked button and corresponding panel
                    this.classList.add('active');
                    document.getElementById(tabName + '-panel').classList.add('active');

                    // 根据标签页加载数据
                    switch(tabName) {
                        case 'patients':
                            loadPatients();
                            break;
                        case 'medical-records':
                            if (currentPatientId) {
                                loadMedicalRecords();
                            } else {
                                showMessage('请先选择患者', 'warning');
                            }
                            break;
                        case 'appointments':
                            if (currentPatientId) {
                                loadAppointments();
                            } else {
                                showMessage('请先选择患者', 'warning');
                            }
                            break;
                    }
                });
            });

            // 初始加载患者列表
            loadPatients();
        });

        // 当选择患者时更新currentPatientId并切换到健康档案标签页
        function selectPatientForRecords(patientId) {
            currentPatientId = patientId;

            // 切换到健康档案标签页
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.tab-panel').forEach(panel => panel.classList.remove('active'));

            const medicalTab = document.querySelector('.tab-btn[data-tab="medical-records"]');
            const medicalPanel = document.getElementById('medical-records-panel');

            if (medicalTab && medicalPanel) {
                medicalTab.classList.add('active');
                medicalPanel.classList.add('active');

                // 加载健康档案数据
                loadMedicalRecords();

                showMessage('已选择患者，正在加载健康档案', 'success');
            }
        }

        // Empty state functions
        function displayEmptyPatients() {
            displayPatients([]);
        }

        function displayErrorPatients() {
            const tbody = document.getElementById('patients-list');
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-5">
                        <div class="empty-state">
                            <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                            <p class="text-muted">加载数据失败，请稍后重试</p>
                            <button class="btn btn-primary" onclick="loadPatients()">
                                <i class="fas fa-refresh"></i> 重新加载
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }

        // Utility functions
        function formatDateTime(dateString) {
            const date = new Date(dateString);
            return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        function showLoading() {
            // Add loading overlay if needed
        }

        function hideLoading() {
            // Remove loading overlay if needed
        }

        // ==================== 健康档案管理功能 ====================

        // 显示添加健康档案模态框
        function showAddMedicalRecordModal() {
            if (!currentPatientId) {
                showMessage('请先选择患者', 'warning');
                return;
            }

            // 清空表单
            document.getElementById('medical-record-form').reset();
            document.getElementById('medical-record-id').value = '';
            document.getElementById('medical-record-patient-id').value = currentPatientId;

            // 设置默认就诊日期为今天
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('visit-date').value = today;

            // 显示模态框
            new bootstrap.Modal(document.getElementById('medicalRecordModal')).show();
        }

        // 查看健康档案详情
        function viewMedicalRecord(id) {
            fetch(`api/medical_records.php?action=get&id=${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMedicalRecordDetails(data.record);
                    } else {
                        showMessage('获取记录详情失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    showMessage('网络错误', 'danger');
                });
        }

        // 编辑健康档案
        function editMedicalRecord(id) {
            fetch(`api/medical_records.php?action=get&id=${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        fillMedicalRecordForm(data.record);
                        new bootstrap.Modal(document.getElementById('medicalRecordModal')).show();
                    } else {
                        showMessage('获取记录失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    showMessage('网络错误', 'danger');
                });
        }

        // 删除健康档案
        function deleteMedicalRecord(id) {
            if (!confirm('确定要删除这条健康档案记录吗？此操作不可恢复。')) {
                return;
            }

            fetch(`api/medical_records.php?action=delete&id=${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage('健康档案删除成功', 'success');
                        loadMedicalRecords();
                    } else {
                        showMessage('删除失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    showMessage('网络错误', 'danger');
                });
        }

        // 填充健康档案表单
        function fillMedicalRecordForm(record) {
            document.getElementById('medical-record-id').value = record.id;
            document.getElementById('medical-record-patient-id').value = record.patient_id;
            document.getElementById('visit-date').value = record.visit_date ? record.visit_date.split(' ')[0] : '';
            document.getElementById('visit-type').value = record.visit_type;
            document.getElementById('chief-complaint').value = record.chief_complaint || '';
            document.getElementById('present-illness').value = record.present_illness || '';
            document.getElementById('past-history').value = record.past_history || '';
            document.getElementById('examination-findings').value = record.examination_findings || '';
            document.getElementById('diagnosis').value = record.diagnosis || '';
            document.getElementById('treatment-plan').value = record.treatment_plan || '';
            document.getElementById('prescriptions').value = record.prescriptions || '';
            document.getElementById('medical-notes').value = record.notes || '';
            document.getElementById('doctor-id').value = record.doctor_id || '';
            document.getElementById('cost').value = record.cost || '';
            document.getElementById('payment-status').value = record.payment_status;
            document.getElementById('follow-up-date').value = record.follow_up_date ? record.follow_up_date.split(' ')[0] : '';
        }

        // 显示健康档案详情
        function showMedicalRecordDetails(record) {
            const modalHtml = `
                <div class="modal fade" id="medicalRecordDetailModal" tabindex="-1">
                    <div class="modal-dialog modal-lg">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">健康档案详情 - ${record.patient_name}</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6>基本信息</h6>
                                        <p><strong>就诊日期:</strong> ${formatDateTime(record.visit_date)}</p>
                                        <p><strong>就诊类型:</strong> ${getVisitTypeName(record.visit_type)}</p>
                                        <p><strong>医生:</strong> ${record.doctor_name || '未指定'}</p>
                                        <p><strong>费用:</strong> ¥${record.cost || 0}</p>
                                        <p><strong>支付状态:</strong> ${record.payment_status === 'paid' ? '已支付' : record.payment_status === 'partially_paid' ? '部分支付' : '未支付'}</p>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>诊断结果</h6>
                                        <p><strong>诊断结论:</strong> ${record.diagnosis || '暂无'}</p>
                                        <p><strong>治疗方案:</strong> ${record.treatment_plan || '暂无'}</p>
                                        ${record.follow_up_date ? `<p><strong>复诊日期:</strong> ${formatDateTime(record.follow_up_date)}</p>` : ''}
                                    </div>
                                </div>
                                <hr>
                                <div class="row">
                                    <div class="col-md-6">
                                        <h6>主诉</h6>
                                        <p>${record.chief_complaint || '暂无'}</p>
                                        <h6>现病史</h6>
                                        <p>${record.present_illness || '暂无'}</p>
                                    </div>
                                    <div class="col-md-6">
                                        <h6>既往史</h6>
                                        <p>${record.past_history || '暂无'}</p>
                                        <h6>检查所见</h6>
                                        <p>${record.examination_findings || '暂无'}</p>
                                    </div>
                                </div>
                                ${record.prescriptions ? `
                                    <hr>
                                    <h6>处方</h6>
                                    <p>${record.prescriptions}</p>
                                ` : ''}
                                ${record.notes ? `
                                    <hr>
                                    <h6>备注</h6>
                                    <p>${record.notes}</p>
                                ` : ''}
                            </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="editMedicalRecord(${record.id})">编辑</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // 移除已存在的模态框
            const existingModal = document.getElementById('medicalRecordDetailModal');
            if (existingModal) {
                existingModal.remove();
            }

            document.body.insertAdjacentHTML('beforeend', modalHtml);
            new bootstrap.Modal(document.getElementById('medicalRecordDetailModal')).show();
        }

        // ==================== 预约管理功能 ====================

        // 显示添加预约模态框
        function showAddAppointmentModal() {
            if (!currentPatientId) {
                showMessage('请先选择患者', 'warning');
                return;
            }

            // 清空表单
            document.getElementById('appointment-form').reset();
            document.getElementById('appointment-id').value = '';
            document.getElementById('appointment-patient-id').value = currentPatientId;

            // 加载医生列表
            loadDoctorsForAppointment();

            // 显示模态框
            new bootstrap.Modal(document.getElementById('appointmentModal')).show();
        }

        // 加载医生列表
        function loadDoctorsForAppointment() {
            fetch('api/appointments.php?action=get_doctors')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('appointment-doctor-id');
                        select.innerHTML = '<option value="">请选择医生...</option>';
                        data.doctors.forEach(doctor => {
                            const option = document.createElement('option');
                            option.value = doctor.id;
                            option.textContent = `${doctor.full_name} (${doctor.department || '未指定科室'})`;
                            select.appendChild(option);
                        });
                    }
                })
                .catch(error => console.error('加载医生列表失败:', error));
        }

        // 查看预约详情
        function viewAppointment(id) {
            fetch(`api/appointments.php?action=get&id=${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showAppointmentDetails(data.appointment);
                    } else {
                        showMessage('获取预约详情失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    showMessage('网络错误', 'danger');
                });
        }

        // 编辑预约
        function editAppointment(id) {
            fetch(`api/appointments.php?action=get&id=${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        fillAppointmentForm(data.appointment);
                        loadDoctorsForAppointment();
                        new bootstrap.Modal(document.getElementById('appointmentModal')).show();
                    } else {
                        showMessage('获取预约失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    showMessage('网络错误', 'danger');
                });
        }

        // 删除预约
        function deleteAppointment(id) {
            if (!confirm('确定要删除这个预约吗？')) {
                return;
            }

            fetch(`api/appointments.php?action=delete&id=${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showMessage('预约删除成功', 'success');
                        loadAppointments();
                    } else {
                        showMessage('删除失败: ' + data.message, 'danger');
                    }
                })
                .catch(error => {
                    showMessage('网络错误', 'danger');
                });
        }

        // 填充预约表单
        function fillAppointmentForm(appointment) {
            document.getElementById('appointment-id').value = appointment.id;
            document.getElementById('appointment-patient-id').value = appointment.patient_id;
            document.getElementById('appointment-date').value = appointment.appointment_date ? appointment.appointment_date.substring(0, 16) : '';
            document.getElementById('appointment-type').value = appointment.appointment_type;
            document.getElementById('service-type').value = appointment.service_type || '';
            document.getElementById('appointment-duration').value = appointment.duration;
            document.getElementById('appointment-status').value = appointment.status;
            document.getElementById('appointment-priority').value = appointment.priority;
            document.getElementById('appointment-notes').value = appointment.notes || '';
            document.getElementById('appointment-doctor-id').value = appointment.doctor_id || '';
            document.getElementById('appointment-room').value = appointment.room || '';
            document.getElementById('appointment-equipment').value = appointment.equipment_needed || '';
        }

        // 显示预约详情
        function showAppointmentDetails(appointment) {
            const modalHtml = `
                <div class="modal fade" id="appointmentDetailModal" tabindex="-1">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">预约详情 - ${appointment.patient_name}</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                            </div>
                            <div class="modal-body">
                                <p><strong>预约时间:</strong> ${formatDateTime(appointment.appointment_date)}</p>
                                <p><strong>预约类型:</strong> ${getAppointmentTypeName(appointment.appointment_type)}</p>
                                <p><strong>服务项目:</strong> ${appointment.service_type || '未指定'}</p>
                                <p><strong>预计时长:</strong> ${appointment.duration}分钟</p>
                                <p><strong>状态:</strong>
                                    <span class="status-badge status-${getAppointmentStatusClass(appointment.status)}">
                                        ${getAppointmentStatusName(appointment.status)}
                                    </span>
                                </p>
                                <p><strong>优先级:</strong>
                                    <span class="badge bg-${appointment.priority === 'high' ? 'danger' : appointment.priority === 'normal' ? 'warning' : 'secondary'}">
                                        ${appointment.priority === 'high' ? '高' : appointment.priority === 'normal' ? '中' : '低'}
                                    </span>
                                </p>
                                <p><strong>医生:</strong> ${appointment.doctor_name || '未指定'}</p>
                                <p><strong>诊室:</strong> ${appointment.room || '未指定'}</p>
                                ${appointment.equipment_needed ? `<p><strong>所需设备:</strong> ${appointment.equipment_needed}</p>` : ''}
                                ${appointment.notes ? `<p><strong>备注:</strong> ${appointment.notes}</p>` : ''}
                            </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="editAppointment(${appointment.id})">编辑</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

            // 移除已存在的模态框
            const existingModal = document.getElementById('appointmentDetailModal');
            if (existingModal) {
                existingModal.remove();
            }

            document.body.insertAdjacentHTML('beforeend', modalHtml);
            new bootstrap.Modal(document.getElementById('appointmentDetailModal')).show();
        }

        // 患者选择功能
        function searchPatients(query) {
            if (!query || query.length < 2) return;

            fetch(`api/medical_records.php?action=search_patients&q=${encodeURIComponent(query)}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.patients.length > 0) {
                        showPatientSearchResults(data.patients);
                    }
                })
                .catch(error => console.error('搜索患者失败:', error));
        }

        function showPatientSearchResults(patients) {
            // 这里可以显示患者搜索结果的dropdown或modal
            console.log('找到患者:', patients);
        }

        // 更新分页功能
        function updatePagination(totalPages, currentPage, loadFunction) {
            console.log('调用updatePagination:', { totalPages, currentPage, loadFunction });

            const containerId = loadFunction === 'loadPatients' ? 'patients-pagination' :
                               loadFunction === 'loadMedicalRecords' ? 'medical-records-pagination' :
                               loadFunction === 'loadAppointments' ? 'appointments-pagination' : '';

            console.log('容器ID:', containerId);

            if (!containerId) return;

            const container = document.getElementById(containerId);
            console.log('容器元素:', container);
            if (!container) return;

            // Clear existing pagination
            container.innerHTML = '';

            if (totalPages <= 1) return;

            // Get current language pack for translations
            const langPack = typeof getGlobalLanguagePack === 'function' ? getGlobalLanguagePack() : {
                first: "首页",
                previous: "上一页",
                next: "下一页",
                last: "末页",
                showing: "显示",
                to: "到",
                of: "共",
                entries: "条记录"
            };

            // Create pagination structure
            const itemsPerPage = loadFunction === 'loadPatients' ? 30 : 10;
            const loadFuncStr = loadFunction;
            const paginationHtml = `
                <div class="pagination-wrapper">
                    <div class="pagination-info">
                        <span data-i18n="showing">${langPack.showing || '显示'}</span>
                        <span class="current-page-info">${(currentPage - 1) * itemsPerPage + 1}</span>
                        <span data-i18n="to">${langPack.to || '到'}</span>
                        <span class="total-entries">${Math.min(currentPage * itemsPerPage, totalPages * itemsPerPage)}</span>
                        <span data-i18n="of">${langPack.of || '共'}</span>
                        <span class="total-pages">${totalPages * itemsPerPage}</span>
                        <span data-i18n="entries">${langPack.entries || '条记录'}</span>
                    </div>
                    <nav aria-label="Patient pagination">
                        <ul class="pagination pagination-sm">
                            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                                <a class="page-link" href="#" onclick="changePage(1, '${loadFuncStr}'); return false;" data-i18n="first">${langPack.first || '首页'}</a>
                            </li>
                            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                                <a class="page-link" href="#" onclick="changePage(${currentPage - 1}, '${loadFuncStr}'); return false;" data-i18n="previous">${langPack.previous || '上一页'}</a>
                            </li>
                            ${generatePageNumbers(totalPages, currentPage, loadFunction)}
                            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                                <a class="page-link" href="#" onclick="changePage(${currentPage + 1}, '${loadFuncStr}'); return false;" data-i18n="next">${langPack.next || '下一页'}</a>
                            </li>
                            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                                <a class="page-link" href="#" onclick="changePage(${totalPages}, '${loadFuncStr}'); return false;" data-i18n="last">${langPack.last || '末页'}</a>
                            </li>
                        </ul>
                    </nav>
                </div>
            `;

            container.innerHTML = paginationHtml;
        }

        // 生成页码按钮
        function generatePageNumbers(totalPages, currentPage, loadFunction) {
            let html = '';
            const maxVisiblePages = 5; // 最多显示5个页码按钮
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

            // 调整起始页，确保显示足够的页码
            if (endPage - startPage + 1 < maxVisiblePages) {
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }

            const loadFuncStr = loadFunction;
            for (let i = startPage; i <= endPage; i++) {
                const activeClass = i === currentPage ? 'active' : '';
                html += `<li class="page-item ${activeClass}"><a class="page-link" href="#" onclick="changePage(${i}, '${loadFuncStr}'); return false;">${i}</a></li>`;
            }

            return html;
        }

        // 换页函数
        function changePage(page, loadFunction) {
            console.log('changePage called:', { page, loadFunction, type: typeof page, type2: typeof loadFunction });

            const searchInput = document.getElementById('patient-search');
            const searchTerm = searchInput ? searchInput.value.trim() : ''; // 使用trim()去除空白字符

            console.log('Search input element:', searchInput);
            console.log('Search term:', `"${searchTerm}"`, 'Length:', searchTerm.length);

            // 防止无效的页码
            if (page < 1) {
                console.log('Invalid page number:', page);
                return;
            }

            // 调用相应的加载函数
            if (loadFunction === 'loadPatients') {
                console.log(`Loading patients page: ${page}, search: "${searchTerm}"`);
                loadPatients(page, 30, searchTerm);
            } else if (loadFunction === 'loadMedicalRecords') {
                loadMedicalRecords(page, 10, searchTerm);
            } else if (loadFunction === 'loadAppointments') {
                loadAppointments(page, 10, searchTerm);
            } else {
                console.error('Unknown loadFunction:', loadFunction);
            }
        }
    </script>

    <!-- 健康档案模态框 -->
    <div class="modal fade" id="medicalRecordModal" 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>
                <form id="medical-record-form" onsubmit="saveMedicalRecord(event)">
                    <div class="modal-body">
                        <input type="hidden" id="medical-record-id" name="id">
                        <input type="hidden" id="medical-record-patient-id" name="patient_id">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="visit-date" class="form-label">就诊日期 *</label>
                                    <input type="date" class="form-control" id="visit-date" name="visit_date" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="visit-type" class="form-label">就诊类型</label>
                                    <select class="form-select" id="visit-type" name="visit_type">
                                        <option value="checkup">检查</option>
                                        <option value="treatment">治疗</option>
                                        <option value="consultation">咨询</option>
                                        <option value="emergency">急诊</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="chief-complaint" class="form-label">主诉</label>
                                    <textarea class="form-control" id="chief-complaint" name="chief_complaint" rows="2"></textarea>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="present-illness" class="form-label">现病史</label>
                                    <textarea class="form-control" id="present-illness" name="present_illness" rows="2"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="past-history" class="form-label">既往史</label>
                                    <textarea class="form-control" id="past-history" name="past_history" rows="2"></textarea>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="examination-findings" class="form-label">检查所见</label>
                                    <textarea class="form-control" id="examination-findings" name="examination_findings" rows="2"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="diagnosis" class="form-label">诊断结论 *</label>
                                    <textarea class="form-control" id="diagnosis" name="diagnosis" rows="2" required></textarea>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="treatment-plan" class="form-label">治疗方案</label>
                                    <textarea class="form-control" id="treatment-plan" name="treatment_plan" rows="2"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="prescriptions" class="form-label">处方</label>
                                    <textarea class="form-control" id="prescriptions" name="prescriptions" rows="2"></textarea>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="medical-notes" class="form-label">备注</label>
                                    <textarea class="form-control" id="medical-notes" name="notes" rows="2"></textarea>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="doctor-id" class="form-label">医生</label>
                                    <input type="number" class="form-control" id="doctor-id" name="doctor_id" placeholder="医生ID">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="cost" class="form-label">费用</label>
                                    <input type="number" class="form-control" id="cost" name="cost" step="0.01" min="0">
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="payment-status" class="form-label">支付状态</label>
                                    <select class="form-select" id="payment-status" name="payment_status">
                                        <option value="unpaid">未支付</option>
                                        <option value="partially_paid">部分支付</option>
                                        <option value="paid">已支付</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="follow-up-date" class="form-label">复诊日期</label>
                                    <input type="date" class="form-control" id="follow-up-date" name="follow_up_date">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 预约模态框 -->
    <div class="modal fade" id="appointmentModal" 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>
                <form id="appointment-form" onsubmit="saveAppointment(event)">
                    <div class="modal-body">
                        <input type="hidden" id="appointment-id" name="id">
                        <input type="hidden" id="appointment-patient-id" name="patient_id">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-date" class="form-label">预约时间 *</label>
                                    <input type="datetime-local" class="form-control" id="appointment-date" name="appointment_date" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-type" class="form-label">预约类型</label>
                                    <select class="form-select" id="appointment-type" name="appointment_type">
                                        <option value="checkup">检查</option>
                                        <option value="treatment">治疗</option>
                                        <option value="consultation">咨询</option>
                                        <option value="emergency">急诊</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="service-type" class="form-label">服务项目</label>
                                    <input type="text" class="form-control" id="service-type" name="service_type">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-duration" class="form-label">预计时长（分钟）</label>
                                    <input type="number" class="form-control" id="appointment-duration" name="duration" value="30" min="15" max="480">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-status" class="form-label">状态</label>
                                    <select class="form-select" id="appointment-status" name="status">
                                        <option value="scheduled">已预约</option>
                                        <option value="confirmed">已确认</option>
                                        <option value="completed">已完成</option>
                                        <option value="cancelled">已取消</option>
                                        <option value="no_show">未到场</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-priority" class="form-label">优先级</label>
                                    <select class="form-select" id="appointment-priority" name="priority">
                                        <option value="low">低</option>
                                        <option value="normal">中</option>
                                        <option value="high">高</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-doctor-id" class="form-label">医生</label>
                                    <select class="form-select" id="appointment-doctor-id" name="doctor_id">
                                        <option value="">请选择医生...</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-room" class="form-label">诊室</label>
                                    <input type="text" class="form-control" id="appointment-room" name="room">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-equipment" class="form-label">所需设备</label>
                                    <input type="text" class="form-control" id="appointment-equipment" name="equipment_needed">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="appointment-notes" class="form-label">备注</label>
                                    <textarea class="form-control" id="appointment-notes" name="notes" rows="2"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 添加保存函数 -->
    <script>
        function saveMedicalRecord(event) {
            event.preventDefault();

            const formData = new FormData(event.target);
            const action = formData.get('id') ? 'update' : 'add';

            fetch(`api/medical_records.php?action=${action}`, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('健康档案保存成功', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('medicalRecordModal')).hide();
                    loadMedicalRecords();
                } else {
                    showMessage('保存失败: ' + data.message, 'danger');
                }
            })
            .catch(error => {
                showMessage('网络错误', 'danger');
            });
        }

        function saveAppointment(event) {
            event.preventDefault();

            const formData = new FormData(event.target);
            const action = formData.get('id') ? 'update' : 'add';

            fetch(`api/appointments.php?action=${action}`, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('预约保存成功', 'success');
                    bootstrap.Modal.getInstance(document.getElementById('appointmentModal')).hide();
                    loadAppointments();
                } else {
                    showMessage('保存失败: ' + data.message, 'danger');
                }
            })
            .catch(error => {
                showMessage('网络错误', 'danger');
            });
        }

        // 查看患者详细信息
        function viewPatient(patientId) {
            // 调用API获取患者详细信息
            apiRequest(`api/patients.php?action=get&id=${patientId}`)
                .then(data => {
                    if (data.success && data.patient) {
                        displayPatientDetails(data.patient);
                        new bootstrap.Modal(document.getElementById('viewPatientModal')).show();
                    } else {
                        showMessage('获取患者信息失败', 'danger');
                    }
                })
                .catch(error => {
                    console.error('查看患者详情失败:', error);
                    showMessage('网络错误，无法获取患者信息', 'danger');
                });
        }

        // 显示患者详细信息
        function displayPatientDetails(patient) {
            const content = document.getElementById('patientDetailContent');

            // 获取患者的统计信息
            Promise.all([
                apiRequest(`api/images.php?action=list&patient_id=${patient.id}`),
                apiRequest(`api/medical_records.php?action=list&patient_id=${patient.id}`)
            ]).then(([imageData, medicalData]) => {
                const images = imageData.success ? imageData.images : [];
                const imageCount = images.length;
                const medicalCount = medicalData.success ? medicalData.medical_records.length : 0;

                // 生成影像库HTML
                const imageGalleryHtml = images.length > 0 ? `
                    <div class="image-gallery">
                        <div class="image-grid">
                            ${images.slice(0, 12).map(image => `
                                <div class="image-card">
                                    <div class="image-container">
                                        <img src="${image.file_path}" alt="${image.notes || '患者影像'}" class="image-thumbnail" onerror="this.src='assets/images/placeholder.png'">
                                        <div class="image-overlay">
                                            <button class="btn btn-sm btn-outline-light me-1" onclick="viewImage(${image.id})" title="查看大图">
                                                <i class="fas fa-eye"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-light" onclick="downloadImage('${image.file_path}')" title="下载">
                                                <i class="fas fa-download"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div class="image-badges">
                                            <span class="badge badge-filetype">${image.file_type.toUpperCase()}</span>
                                            <span class="badge badge-quality">${getImageQualityBadge(image.quality_score)}</span>
                                        </div>
                                        <small class="text-muted">${formatDateTime(image.capture_date)}</small>
                                        ${image.notes ? `<br><small class="text-muted">${image.notes}</small>` : ''}
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                        ${images.length > 12 ? `
                            <div class="text-center mt-3">
                                <button class="btn btn-outline-primary btn-sm" onclick="showFullImageGallery(${patient.id})">
                                    查看全部 ${imageCount} 个影像文件
                                </button>
                            </div>
                        ` : ''}
                    </div>
                ` : `
                    <div class="text-center py-5">
                        <i class="fas fa-camera fa-3x text-muted mb-3"></i>
                        <p class="text-muted">暂无影像文件</p>
                        <button class="btn btn-primary" onclick="window.open('capture.php?patient_id=${patient.id}', '_blank')">
                            <i class="fas fa-plus"></i> 添加影像
                        </button>
                    </div>
                `;

                // 生成患者牙照HTML（显示最新3张照片）
                const langPack = typeof getGlobalLanguagePack === 'function' ? getGlobalLanguagePack() : {};
                const dentalPhotosHtml = images.length > 0 ? `
                    <div class="row mt-3">
                        <div class="col-12">
                            <h6 class="text-primary mb-3"><i class="fas fa-tooth"></i> ${langPack.patient_dental_photos || '患者牙照'}</h6>
                            <div class="dental-photos-grid">
                                ${images.slice(0, 3).map(image => `
                                    <div class="dental-photo-item">
                                        <div class="dental-photo-container">
                                            <img src="${image.file_path}" alt="${image.notes || '患者牙照'}" class="dental-photo-thumbnail"
                                                 onerror="this.src='assets/images/placeholder.png'">
                                            <div class="dental-photo-overlay">
                                                <button class="btn btn-sm btn-outline-light" onclick="viewImage(${image.id})" title="查看大图">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </div>
                                        </div>
                                        <div class="dental-photo-info">
                                            <small class="text-muted">${formatDateTime(image.capture_date)}</small>
                                            ${image.notes ? `<br><small class="text-muted">${image.notes}</small>` : ''}
                                        </div>
                                    </div>
                                `).join('')}
                            </div>
                            ${images.length > 3 ? `
                                <div class="text-center mt-2">
                                    <button class="btn btn-sm btn-outline-primary" onclick="showFullImageGallery(${patient.id})">
                                        ${langPack.view_all_images || '查看全部'} ${imageCount} 个影像文件
                                    </button>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                ` : '';

                content.innerHTML = `
                    <div class="row">
                        <div class="col-lg-8">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="mb-0">基本信息</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>姓名：</strong>${patient.name || '未填写'}</p>
                                            <p><strong>性别：</strong>${patient.gender === 'male' ? '男' : '女'}</p>
                                            <p><strong>年龄：</strong>${patient.age || '未填写'}岁</p>
                                            <p><strong>身份证号：</strong>${patient.id_card || '未填写'}</p>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>联系电话：</strong>${patient.phone || '未填写'}</p>
                                            <p><strong>地址：</strong>${patient.address || '未填写'}</p>
                                            <p><strong>医保信息：</strong>${patient.insurance_info || '未填写'}</p>
                                            <p><strong>VIP等级：</strong>${patient.vip_level || '0'}</p>
                                        </div>
                                    </div>
                                    ${dentalPhotosHtml}
                                </div>
                            </div>

                            <!-- 患者影像库 -->
                            <div class="card mb-4">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="mb-0">患者影像库</h5>
                                    <button class="btn btn-outline-primary btn-sm" onclick="window.open('capture.php?patient_id=${patient.id}', '_blank')" title="进入影像采集页面">
                                        <i class="fas fa-camera"></i> 采集影像
                                    </button>
                                </div>
                                <div class="card-body">
                                    ${imageGalleryHtml}
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-4">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="mb-0">统计信息</h5>
                                </div>
                                <div class="card-body">
                                    <div class="stat-item">
                                        <i class="fas fa-camera text-primary"></i>
                                        <span>影像文件: ${imageCount} 个</span>
                                    </div>
                                    <div class="stat-item">
                                        <i class="fas fa-file-medical text-success"></i>
                                        <span>就诊记录: ${medicalCount} 个</span>
                                    </div>
                                    <div class="stat-item">
                                        <i class="fas fa-calendar-check text-info"></i>
                                        <span>预约记录: 0 个</span>
                                    </div>
                                </div>
                            </div>

                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">其他信息</h5>
                                </div>
                                <div class="card-body">
                                    <p><strong>转诊来源：</strong>${patient.referral_source || '未填写'}</p>
                                    <p><strong>注册时间：</strong>${formatDateTime(patient.created_at)}</p>
                                    <p><strong>最后更新：</strong>${formatDateTime(patient.updated_at)}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }).catch(error => {
                console.error('获取统计信息失败:', error);
                // 显示基本信息，即使统计信息获取失败
                content.innerHTML = `
                    <div class="row">
                        <div class="col-md-8">
                            <div class="card mb-4">
                                <div class="card-header">
                                    <h5 class="mb-0">基本信息</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <p><strong>姓名：</strong>${patient.name || '未填写'}</p>
                                            <p><strong>性别：</strong>${patient.gender === 'male' ? '男' : '女'}</p>
                                            <p><strong>年龄：</strong>${patient.age || '未填写'}岁</p>
                                            <p><strong>身份证号：</strong>${patient.id_card || '未填写'}</p>
                                        </div>
                                        <div class="col-md-6">
                                            <p><strong>联系电话：</strong>${patient.phone || '未填写'}</p>
                                            <p><strong>地址：</strong>${patient.address || '未填写'}</p>
                                            <p><strong>医保信息：</strong>${patient.insurance_info || '未填写'}</p>
                                            <p><strong>VIP等级：</strong>${patient.vip_level || '0'}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">其他信息</h5>
                                </div>
                                <div class="card-body">
                                    <p><strong>转诊来源：</strong>${patient.referral_source || '未填写'}</p>
                                    <p><strong>注册时间：</strong>${formatDateTime(patient.created_at)}</p>
                                    <p><strong>最后更新：</strong>${formatDateTime(patient.updated_at)}</p>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
        }

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

        // ==================== 批量删除功能 ====================

        // 初始化批量删除功能
        function initBatchDelete() {
            updateBatchDeleteButton();
        }

        // 全选/取消全选复选框
        function toggleAllCheckboxes() {
            const selectAllCheckbox = document.getElementById('select-all-checkbox');
            const checkboxes = document.querySelectorAll('.patient-checkbox');

            checkboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });

            updateBatchDeleteButton();
        }

        // 更新批量删除按钮状态
        function updateBatchDeleteButton() {
            const checkboxes = document.querySelectorAll('.patient-checkbox:checked');
            const selectedCount = checkboxes.length;
            const batchDeleteBtn = document.getElementById('batch-delete-btn');
            const selectedCountSpan = document.getElementById('selected-count');

            if (selectedCount > 0) {
                batchDeleteBtn.style.display = 'inline-block';
                selectedCountSpan.style.display = 'inline-block';
                selectedCountSpan.textContent = `已选择 ${selectedCount} 项`;
            } else {
                batchDeleteBtn.style.display = 'none';
                selectedCountSpan.style.display = 'none';
            }

            // 更新全选复选框状态
            const allCheckboxes = document.querySelectorAll('.patient-checkbox');
            const selectAllCheckbox = document.getElementById('select-all-checkbox');

            if (allCheckboxes.length > 0) {
                const checkedCount = document.querySelectorAll('.patient-checkbox:checked').length;
                selectAllCheckbox.checked = checkedCount === allCheckboxes.length;
                selectAllCheckbox.indeterminate = checkedCount > 0 && checkedCount < allCheckboxes.length;
            }
        }

        // 批量删除患者
        function batchDeletePatients() {
            const selectedCheckboxes = document.querySelectorAll('.patient-checkbox:checked');
            const selectedIds = Array.from(selectedCheckboxes).map(checkbox => parseInt(checkbox.value));

            if (selectedIds.length === 0) {
                showMessage('请先选择要删除的患者', 'warning');
                return;
            }

            const confirmMessage = `确定要删除选中的 ${selectedIds.length} 个患者吗？\n\n此操作将同时删除患者的健康档案、预约记录和影像文件，且不可恢复！`;

            if (!confirm(confirmMessage)) {
                return;
            }

            // 显示加载状态
            const batchDeleteBtn = document.getElementById('batch-delete-btn');
            const originalText = batchDeleteBtn.innerHTML;
            batchDeleteBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 删除中...';
            batchDeleteBtn.disabled = true;

            // 发送批量删除请求
            fetch('api/patients.php?action=batch_delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ ids: selectedIds })
            })
            .then(response => response.json())
            .then(data => {
                // 恢复按钮状态
                batchDeleteBtn.innerHTML = originalText;
                batchDeleteBtn.disabled = false;

                if (data.success) {
                    showMessage(`成功删除 ${selectedIds.length} 个患者及其相关数据`, 'success');

                    // 刷新患者列表
                    loadPatients();

                    // 刷新统计数据
                    loadPatientStats();

                    // 隐藏批量删除按钮
                    updateBatchDeleteButton();
                } else {
                    showMessage('批量删除失败: ' + (data.message || '未知错误'), 'danger');
                }
            })
            .catch(error => {
                console.error('批量删除失败:', error);

                // 恢复按钮状态
                batchDeleteBtn.innerHTML = originalText;
                batchDeleteBtn.disabled = false;

                showMessage('网络错误，请稍后重试', 'danger');
            });
        }

        // 从查看页面跳转到编辑页面
        function editPatientFromView() {
            // 关闭查看modal
            bootstrap.Modal.getInstance(document.getElementById('viewPatientModal')).hide();

            // 这里可以添加逻辑来获取当前查看的患者ID并打开编辑modal
            // 暂时只是关闭当前modal
        }
    </script>
    <script src="assets/js/language-switcher.js"></script>
</body>
</html>
