<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>患者画像 - {{ patient.姓名 }}</title>
    
    <!-- TailwindCSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <script>
        // 设置API基础URL - 根据当前页面动态配置，避免跨域问题
        const currentHost = window.location.hostname;
        const currentPort = window.location.port || (window.location.protocol === 'https:' ? '443' : '80');
        // 使用当前页面的端口，支持5003（当前）、5001（旧版本）、4002（Docker）
        const apiPort = currentPort;
        window.API_BASE_URL = `${window.location.protocol}//${currentHost}:${apiPort}`;
        
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: {
                            50: '#f0f9ff',
                            100: '#e0f2fe',
                            200: '#bae6fd',
                            300: '#7dd3fc',
                            400: '#38bdf8',
                            500: '#0ea5e9',
                            600: '#0284c7',
                            700: '#0369a1',
                            800: '#075985',
                            900: '#0c4a6e',
                        },
                    }
                }
            }
        }
    </script>
    
    <style>
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .animate-fade-in-up {
            animation: fadeInUp 0.5s ease-out forwards;
        }
        
        .bento-grid {
            display: grid;
            grid-template-columns: repeat(12, 1fr);
            grid-auto-rows: minmax(100px, auto);
            gap: 16px;
        }
        
        .opacity-gradient {
            background: linear-gradient(45deg, rgba(14, 165, 233, 0.8), rgba(14, 165, 233, 0.2));
        }
        
        .scroll-trigger {
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.8s ease-out;
        }
        
        .scroll-visible {
            opacity: 1;
            transform: translateY(0);
        }
        
        /* 调整字体大小和间距 */
        body {
            font-size: 0.9rem;
        }
        
        h1 {
            font-size: 1.5rem !important;
        }
        
        h2 {
            font-size: 1.2rem !important;
        }
        
        h3 {
            font-size: 1rem !important;
        }
        
        p {
            margin-bottom: 0.3rem;
            line-height: 1.3;
        }
        
        .text-xl {
            font-size: 1.1rem !important;
        }
        
        .text-lg {
            font-size: 1rem !important;
        }
        
        .py-6 {
            padding-top: 1rem !important;
            padding-bottom: 1rem !important;
        }
        
        .py-4 {
            padding-top: 0.75rem !important;
            padding-bottom: 0.75rem !important;
        }
        
        .py-3 {
            padding-top: 0.5rem !important;
            padding-bottom: 0.5rem !important;
        }
        
        /* 左侧导航样式 */
        .nav-sidebar {
            position: fixed;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            z-index: 1000;
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            padding: 16px 8px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            cursor: move;
            user-select: none;
            transition: box-shadow 0.3s ease, transform 0.1s ease;
        }

        .nav-sidebar:hover {
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
        }

        .nav-sidebar.dragging {
            box-shadow: 0 16px 48px rgba(0, 0, 0, 0.2);
            scale: 1.02;
            transition: none;
        }
        
        .nav-drag-handle {
            position: absolute;
            top: -8px;
            left: 50%;
            transform: translateX(-50%);
            width: 30px;
            height: 6px;
            background: #d1d5db;
            border-radius: 3px;
            cursor: grab;
            transition: background-color 0.2s ease;
        }

        .nav-drag-handle:hover {
            background: #9ca3af;
        }

        .nav-drag-handle:active,
        .nav-sidebar.dragging .nav-drag-handle {
            cursor: grabbing;
            background: #6b7280;
        }

        .nav-sidebar.dragging {
            cursor: grabbing;
        }
        
        .nav-sidebar::before {
            content: '';
            position: absolute;
            top: 8px;
            right: 8px;
            width: 4px;
            height: 4px;
            background: #10b981;
            border-radius: 50%;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .nav-item {
            display: block;
            padding: 12px 16px;
            margin: 4px 0;
            border-radius: 8px;
            text-decoration: none;
            color: #374151;
            font-size: 0.875rem;
            font-weight: 500;
            transition: all 0.2s ease;
            border: 1px solid transparent;
        }
        
        .nav-item:hover {
            background: rgba(14, 165, 233, 0.1);
            color: #0ea5e9;
            border-color: rgba(14, 165, 233, 0.2);
            transform: translateX(2px);
        }
        
        .nav-item.active {
            background: #0ea5e9;
            color: white;
            box-shadow: 0 4px 12px rgba(14, 165, 233, 0.3);
        }
        
        .nav-item i {
            width: 16px;
            text-align: center;
        }


        
        /* 主内容区域样式 */
        .main-content {
            margin-left: 0;
            transition: margin-left 0.3s ease;
        }
        
        @media (min-width: 1024px) {
            .main-content {
                margin-left: 0;
            }
        }
        
        /* 平滑滚动 */
        html {
            scroll-behavior: smooth;
        }
        
        /* 回访话术样式 */
        .callback-content {
            line-height: 1.6;
        }
        
        .callback-content h1,
        .callback-content h2,
        .callback-content h3 {
            margin-top: 1.5rem;
            margin-bottom: 0.75rem;
        }
        
        .callback-content li {
            margin-bottom: 0.5rem;
        }
        
        .callback-content blockquote {
            margin: 1rem 0;
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-900">

    <!-- 左侧快捷导航 -->
    <nav class="nav-sidebar" id="navSidebar">
        <div class="nav-drag-handle" id="dragHandle" title="拖拽移动导航栏"></div>
        <a href="#patient-profile" class="nav-item" title="患者画像">
            <i class="fas fa-user-circle mr-2"></i>
            患者画像
        </a>
        <a href="#callback-content" class="nav-item" title="口腔回访话术">
            <i class="fas fa-phone mr-2"></i>
            口腔回访话术
        </a>
        <a href="#callback-records" class="nav-item" title="回访记录">
            <i class="fas fa-clipboard-list mr-2"></i>
            回访记录
        </a>
    </nav>

    <header class="bg-primary-700 text-white py-4 mb-6">
        <div class="container mx-auto px-4">
            <h1 class="text-3xl font-bold">患者画像 <span class="text-xl font-normal ml-2">Patient Profile</span></h1>
        </div>
    </header>
    
    <main class="main-content container mx-auto px-4 mb-10">
        <!-- 患者画像模块 -->
        <div id="patient-profile">
            <!-- 基本信息和漏诊信息水平并列布局 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
                <!-- 基本信息模块 - 占左侧列100%宽度 -->
                <section class="scroll-trigger">
                    <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                        <div class="bg-primary-600 px-6 py-3 text-white">
                            <h2 class="text-xl font-bold flex items-center">
                                <i class="fas fa-user-circle mr-3"></i>
                                基本信息 <span class="text-sm ml-2 font-normal">Basic Information</span>
                            </h2>
                        </div>
                        <div class="p-5 grid grid-cols-1 md:grid-cols-2 gap-5">
                            <div>
                                <h3 class="text-lg font-semibold mb-2 text-primary-800">患者信息</h3>
                                <div class="space-y-1">
                                    <p><span class="font-medium text-gray-500 w-16 inline-block">姓名：</span><span class="text-black">{{ patient.姓名 }}</span></p>
                                    <p><span class="font-medium text-gray-500 w-16 inline-block">性别：</span><span class="text-black">{{ patient.性别 }}</span></p>
                                    <p><span class="font-medium text-gray-500 w-16 inline-block">年龄：</span><span class="text-black">{{ patient.年龄 }}</span></p>
                                    <p><span class="font-medium text-gray-500 w-16 inline-block">病历号：</span><span class="text-black">{{ patient.病历号 }}</span></p>
                                    <p><span class="font-medium text-gray-500 w-16 inline-block">数据日期：</span><span class="text-black">{{ (patient.日期 or patient.最后一次就诊时间).split(' ')[0] if (patient.日期 or patient.最后一次就诊时间) else '未知' }}</span></p>
                                </div>
                            </div>
                            <div>
                                <h3 class="text-lg font-semibold mb-2 text-primary-800">诊所信息</h3>
                                <div class="space-y-1">
                                    <p><span class="font-medium text-gray-500">所属诊所：</span><span class="text-black">{{ clinic_name }}</span></p>
                                    <p><span class="font-medium text-gray-500">最后一次就诊时间：</span><span class="text-black">{{ patient.最后一次就诊时间.split(' ')[0] if patient.最后一次就诊时间 else '未知' }}</span></p>
                                    <p><span class="font-medium text-gray-500">最后一次就诊诊所：</span><span class="text-black">{{ patient.最后一次就诊诊所 or clinic_name }}</span></p>
                                    <p><span class="font-medium text-gray-500">最后一次就诊医生：</span><span class="text-black">{{ patient.最后一次就诊医生 or '未知医生' }}</span></p> 
                                </div>
                            </div>
                        </div>
                        <div class="px-5 pb-4 border-t border-gray-100 pt-3">
                            <h3 class="text-sm font-medium text-gray-600 mb-2">特殊诊断信息</h3>
                            <div class="flex flex-wrap">
                                <!-- 处理牙槽骨吸收信息 -->
                                {% if patient.牙槽骨吸收 and patient.牙槽骨吸收 == '是' %}
                                    <span class="inline-block bg-red-100 text-red-700 rounded px-2 py-1 mr-2 mb-2 text-sm font-medium">牙槽骨吸收</span>
                                {% endif %}

                                <!-- 处理缺失牙信息 -->
                                {% if patient.缺失牙 and patient.缺失牙 != '[]' and patient.缺失牙|string != 'nan' %}
                                    {% set missing_teeth = patient.缺失牙 %}
                                    {% if missing_teeth.startswith('[') and missing_teeth.endswith(']') %}
                                        {% set teeth_list = missing_teeth[1:-1].replace('"', '').split(',') %}
                                        {% if teeth_list and teeth_list[0].strip() != '' %}
                                            <span class="inline-block bg-orange-100 text-orange-700 rounded px-2 py-1 mr-2 mb-2 text-sm font-medium">缺失牙: {{ teeth_list|join(', ') }}</span>
                                        {% endif %}
                                    {% else %}
                                        <span class="inline-block bg-orange-100 text-orange-700 rounded px-2 py-1 mr-2 mb-2 text-sm font-medium">缺失牙: {{ missing_teeth }}</span>
                                    {% endif %}
                                {% endif %}

                                <!-- 处理恒牙萌出空间不足 -->
                                {% if patient.恒牙萌出空间不足 and patient.恒牙萌出空间不足 == '是' %}
                                    <span class="inline-block bg-yellow-100 text-yellow-700 rounded px-2 py-1 mr-2 mb-2 text-sm font-medium">恒牙萌出空间不足</span>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </section>

                <!-- 漏诊信息模块 - 占右侧列100%宽度 -->
                <section class="scroll-trigger">
                    <div class="bg-white rounded-xl shadow-lg overflow-hidden border-l-4 border-red-500">
                        <div class="bg-red-600 px-6 py-3 text-white">
                            <h2 class="text-xl font-bold flex items-center">
                                <i class="fas fa-exclamation-circle mr-3"></i>
                                漏诊信息 <span class="text-sm ml-2 font-normal">Missed Diagnosis</span>
                            </h2>
                        </div>
                        <div class="p-5">
                            {% if patient.漏诊项 and patient.漏诊项 != '' and patient.漏诊项|string != 'nan' %}
                                {% set missed_diagnosis = patient.漏诊项 %}
                                {% set missed_items = missed_diagnosis.split('\n') %}
                                {% set valid_items = [] %}

                                <!-- 解析漏诊项目 -->
                                {% for item_text in missed_items %}
                                    {% if item_text.strip() and '漏诊项：' in item_text %}
                                        {% set item_parts = item_text.replace('漏诊项：', '').split('，牙位：') %}
                                        {% if item_parts|length >= 2 %}
                                            {% set item_name = item_parts[0].strip() %}
                                            {% set tooth_positions = item_parts[1].strip() %}
                                            {% set _ = valid_items.append({'name': item_name, 'positions': tooth_positions}) %}
                                        {% else %}
                                            {% set item_name = item_text.replace('漏诊项：', '').strip() %}
                                            {% set _ = valid_items.append({'name': item_name, 'positions': ''}) %}
                                        {% endif %}
                                    {% endif %}
                                {% endfor %}

                                <!-- 如果没有找到标准格式，尝试简单解析 -->
                                {% if valid_items|length == 0 %}
                                    {% if '漏诊项：' in missed_diagnosis %}
                                        {% set diagnosis_name = missed_diagnosis.split('漏诊项：')[1].split('，')[0] %}
                                        {% set _ = valid_items.append({'name': diagnosis_name, 'positions': ''}) %}
                                    {% else %}
                                        {% set _ = valid_items.append({'name': missed_diagnosis, 'positions': ''}) %}
                                    {% endif %}
                                {% endif %}

                                <div class="bg-red-50 p-4 rounded-lg mb-4">
                                    <h3 class="font-semibold text-red-700 mb-2">漏诊统计</h3>
                                    <div class="space-y-2">
                                        <p class="text-sm"><span class="font-medium">漏诊总数：</span><span class="text-red-600 font-bold">{{ valid_items|length }}项</span></p>
                                        <p class="text-sm"><span class="font-medium">原始数据：</span><span class="text-gray-600 text-xs">{{ missed_diagnosis[:50] }}...</span></p>
                                    </div>
                                </div>
                                <div>
                                    <h3 class="font-semibold text-red-700 mb-3">漏诊项目详情</h3>
                                    <div class="space-y-2">
                                        {% for item in valid_items %}
                                            <div class="bg-red-50 border border-red-200 rounded-lg p-3 mb-2">
                                                <div class="flex items-center">
                                                    <i class="fas fa-exclamation-triangle text-red-500 mr-2"></i>
                                                    <span class="font-medium text-red-700">{{ item.name }}</span>
                                                </div>
                                                {% if item.positions and item.positions != '[]' %}
                                                    <div class="text-sm text-red-600 mt-1">牙位: {{ item.positions }}</div>
                                                {% endif %}
                                            </div>
                                        {% endfor %}
                                    </div>
                                </div>
                            {% else %}
                                <div class="text-center py-8">
                                    <i class="fas fa-check-circle text-4xl text-green-400 mb-3"></i>
                                    <h3 class="text-lg font-medium text-gray-600 mb-2">无漏诊项目</h3>
                                    <p class="text-gray-500">该患者暂无发现漏诊项目</p>
                                </div>
                            {% endif %}
                        </div>
                    </div>
                </section>
            </div>

            <!-- 上次就诊记录 -->
            <section class="scroll-trigger">
                <div class="bg-white rounded-xl shadow-lg overflow-hidden border-l-4 border-blue-500">
                    <div class="bg-gradient-to-r from-blue-600 to-blue-700 px-6 py-4 text-white">
                        <h2 class="text-xl font-bold flex items-center">
                            <i class="fas fa-notes-medical mr-3"></i>
                            上次就诊记录 <span class="text-sm ml-2 font-normal opacity-90">Last Visit Records</span>
                        </h2>
                    </div>
                    <div class="p-6 bg-gray-50">
                        <div class="space-y-6">
                            <div class="bg-white rounded-lg border border-gray-200 shadow-sm mb-6 overflow-hidden hover:shadow-md transition-shadow duration-200">
                                <div class="bg-gradient-to-r from-blue-50 to-blue-100 px-6 py-4 border-b border-blue-200">
                                    <div class="flex justify-between items-center">
                                        <div class="flex items-center space-x-4">
                                            <div>
                                                <h3 class="text-lg font-bold text-blue-700 flex items-center">
                                                    <i class="fas fa-calendar-day mr-3 text-blue-500"></i>{{ patient.最后一次就诊时间.split(' ')[0] if patient.最后一次就诊时间 else '未知日期' }}
                                                </h3>
                                                <p class="text-sm text-blue-600 mt-1 flex items-center">
                                                    <i class="fas fa-user-md mr-2"></i>主治医生：{{ patient.最后一次就诊医生 or '未知医生' }}
                                                </p>
                                            </div>
                                        </div>
                                        <div class="text-right">
                                            <div class="bg-blue-600 text-white text-xs font-medium px-3 py-1 rounded-full shadow-sm mb-1">
                                                收费金额
                                            </div>
                                            <div class="text-sm text-blue-700 font-semibold">
                                                {% set fee_value = patient.上次就诊收费 %}
                                                {% if fee_value and fee_value != 0 and fee_value|string != 'nan' and fee_value|string != 'None' %}
                                                    ¥{{ "%.2f"|format(fee_value|float) }}
                                                {% else %}
                                                    免费
                                                {% endif %}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="p-6 bg-gray-50">
                                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                        <div class="mb-4 col-span-full">
                                            <p class="font-semibold mb-2 text-sm text-red-600 flex items-center">
                                                <i class="fas fa-comment-medical mr-2"></i>上次就诊主诉：
                                            </p>
                                            <p class="text-sm bg-red-50 p-3 rounded border-l-4 border-red-400 leading-relaxed font-medium">{{ patient.上次就诊主诉 or '无记录' }}</p>
                                        </div>
                                        <div class="mb-4">
                                            <p class="font-semibold mb-2 text-sm text-green-600 flex items-center">
                                                <i class="fas fa-diagnoses mr-2"></i>上次就诊诊断：
                                            </p>
                                            <p class="text-sm bg-green-50 p-3 rounded border-l-4 border-green-300 leading-relaxed">{{ patient.上次就诊诊断 or '无记录' }}</p>
                                        </div>
                                        <div class="mb-4">
                                            <p class="font-semibold mb-2 text-sm text-purple-600 flex items-center">
                                                <i class="fas fa-tools mr-2"></i>上次处置：
                                            </p>
                                            <p class="text-sm bg-purple-50 p-3 rounded border-l-4 border-purple-300 leading-relaxed">{{ patient.上次处置 or '无记录' }}</p>
                                        </div>
                                        <div class="mb-4">
                                            <p class="font-semibold mb-2 text-sm text-indigo-600 flex items-center">
                                                <i class="fas fa-stethoscope mr-2"></i>医生诊断：
                                            </p>
                                            <p class="text-sm bg-indigo-50 p-3 rounded border-l-4 border-indigo-300 leading-relaxed">{{ patient.医生诊断 or '无记录' }}</p>
                                        </div>
                                        {% if patient.上次就诊收费项 and patient.上次就诊收费项 != 'null' %}
                                        <div class="mb-4 col-span-full">
                                            <div class="bg-green-50 p-4 rounded-lg border border-green-200">
                                                <div class="flex justify-between items-start mb-2">
                                                    <h4 class="font-semibold text-green-700 flex items-center">
                                                        <i class="fas fa-money-bill-wave mr-2"></i>收费信息
                                                    </h4>
                                                    <span class="text-xl font-bold text-green-600">
                                                        {% if fee_value and fee_value != 0 and fee_value|string != 'nan' and fee_value|string != 'None' %}
                                                            ¥{{ "%.2f"|format(fee_value|float) }}
                                                        {% else %}
                                                            免费
                                                        {% endif %}
                                                    </span>
                                                </div>
                                                <p class="text-sm text-green-600"><strong>收费项目：</strong>{{ patient.上次就诊收费项 }}</p>
                                            </div>
                                        </div>
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
            </div>

            <!-- 回访话术模块 -->
            <div id="callback-content" class="mt-8">
                <section class="scroll-trigger">
                    <div class="bg-white rounded-xl shadow-lg overflow-hidden border-l-4 border-green-500">
                        <div class="bg-green-600 px-6 py-4 text-white">
                            <h2 class="text-xl font-bold flex items-center">
                                <i class="fas fa-phone mr-3"></i>
                                口腔回访话术 <span class="text-sm ml-2 font-normal">Oral Callback Script</span>
                            </h2>
                        </div>
                        <div class="p-6">
                            <!-- 患者信息概览 - 红框 -->
                            <div class="mb-6 grid grid-cols-1 md:grid-cols-2 gap-4 bg-red-50 p-4 rounded-lg border-2 border-red-200">
                                <div>
                                    <span class="font-medium text-gray-600">患者姓名：</span>
                                    <span class="text-gray-800">{{ patient.姓名 }}</span>
                                </div>
                                <div>
                                    <span class="font-medium text-gray-600">年龄性别：</span>
                                    <span class="text-gray-800">{{ patient.年龄 }}岁 {{ patient.性别 }} ({{ patient.病历号 }})</span>
                                </div>
                                <div>
                                    <span class="font-medium text-gray-600">就诊医生：</span>
                                    <span class="text-gray-800">{{ patient.最后一次就诊医生 or '未知' }}</span>
                                </div>
                                <div>
                                    <span class="font-medium text-gray-600">生成时间：</span>
                                    <span class="text-gray-800">{{ patient.最后一次就诊时间.split(' ')[0] if patient.最后一次就诊时间 else '未知' }}</span>
                                </div>
                            </div>

                            <div class="callback-content">
                                {% if callback_script %}
                                    {{ callback_script | safe }}

                                    <!-- 使用提醒 -->
                                    <div class="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                                        <p class="text-sm text-blue-700">
                                            <i class="fas fa-info-circle mr-2"></i>
                                            <strong>使用提示：</strong>此话术为Dify AI智能生成，请根据实际情况灵活调整使用。建议按照四个模块的顺序进行回访。
                                        </p>
                                    </div>
                                {% else %}
                                    <div class="text-center py-8">
                                        <i class="fas fa-robot text-4xl text-gray-400 mb-4"></i>
                                        <p class="text-gray-500 mb-4">暂无回访话术，点击下方按钮生成AI话术</p>
                                        <button onclick="generateCallbackScript()" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition-colors">
                                            <i class="fas fa-magic mr-2"></i>生成AI回访话术
                                        </button>
                                    </div>
                                {% endif %}
                            </div>
                        </div>
                    </div>
                </section>
            </div>
        </div>

        <!-- 回访记录模块 -->
        <div id="callback-records" class="mt-8">
            <section class="scroll-trigger">
                <div id="callback-records-container" class="bg-white rounded-xl shadow-lg overflow-hidden border-l-4 border-orange-500">
                    <div id="callback-records-header" class="bg-orange-600 px-6 py-4 text-white">
                        <h2 class="text-xl font-bold flex items-center">
                            <i class="fas fa-clipboard-list mr-3"></i>
                            <span id="callback-records-title">回访记录</span>
                            <span id="callback-records-count" class="text-sm ml-2 font-normal">Callback Records ({{ callback_records|length }})</span>
                        </h2>
                    </div>
                    <div class="p-6">
                        <div class="mb-6 p-4 bg-orange-50 border border-orange-200 rounded-lg">
                            <p class="text-sm text-orange-700">
                                <i class="fas fa-info-circle mr-2"></i>
                                <strong>历史记录：</strong>以下是该患者的历史回访记录，按时间倒序排列。
                            </p>
                        </div>

                        <div id="callback-records-list" class="mb-6">
                            {% for record in callback_records %}
                            <div class="callback-record-item bg-white border border-gray-200 rounded-lg p-6 mb-4 shadow-sm hover:shadow-md transition-shadow">
                                <div class="flex justify-between items-start mb-4">
                                    <div class="flex items-center space-x-4">
                                        <div class="bg-blue-100 p-2 rounded-full">
                                            <i class="fas fa-phone text-blue-600"></i>
                                        </div>
                                        <div>
                                            <h4 class="font-semibold text-gray-900">回访记录 #{{ loop.index }}</h4>
                                            <p class="text-sm text-gray-600">回访时间：{{ record.create_time }}</p>
                                            <p class="text-sm text-gray-600">状态：已回访</p>
                                        </div>
                                    </div>
                                    <div class="text-right">
                                        <div class="flex items-center gap-2 mb-2">
                                            {% for method in record.callback_methods %}
                                            <span class="bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
                                                {{ method }}
                                            </span>
                                            {% endfor %}
                                            {% if record.callback_result %}
                                            <span class="{% if record.callback_result == '成功' %}bg-green-100 text-green-800{% elif record.callback_result == '放弃回访' %}bg-orange-100 text-orange-800{% else %}bg-red-100 text-red-800{% endif %} text-xs font-medium px-2.5 py-0.5 rounded-full">
                                                {{ record.callback_result }}
                                            </span>
                                            {% endif %}
                                        </div>
                                        <p class="text-xs text-gray-500">操作员：{{ record.operator_name }}</p>
                                    </div>
                                </div>
                            </div>
                            {% endfor %}
                        </div>

                        <!-- 新建回访记录表单 -->
                        <div id="new-callback-form" class="bg-gray-50 p-6 rounded-lg">
                            <h4 class="font-medium text-gray-800 mb-4 text-left">新建回访记录</h4>

                            <!-- 回访方式选择 -->
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2 text-left">回访方式：</label>
                                <div class="flex flex-wrap gap-2">
                                    <label class="inline-flex items-center">
                                        <input type="checkbox" name="callback-method-{{ patient.病历号 }}" value="打电话" class="form-checkbox h-4 w-4 text-blue-600 rounded" checked>
                                        <span class="ml-2 text-sm">打电话</span>
                                    </label>
                                    <label class="inline-flex items-center">
                                        <input type="checkbox" name="callback-method-{{ patient.病历号 }}" value="发微信" class="form-checkbox h-4 w-4 text-blue-600 rounded">
                                        <span class="ml-2 text-sm">发微信</span>
                                    </label>
                                    <label class="inline-flex items-center">
                                        <input type="checkbox" name="callback-method-{{ patient.病历号 }}" value="发短信" class="form-checkbox h-4 w-4 text-blue-600 rounded">
                                        <span class="ml-2 text-sm">发短信</span>
                                    </label>
                                    <label class="inline-flex items-center">
                                        <input type="checkbox" name="callback-method-{{ patient.病历号 }}" value="视频通话" class="form-checkbox h-4 w-4 text-blue-600 rounded">
                                        <span class="ml-2 text-sm">视频通话</span>
                                    </label>
                                    <label class="inline-flex items-center">
                                        <input type="checkbox" name="callback-method-{{ patient.病历号 }}" value="面谈" class="form-checkbox h-4 w-4 text-blue-600 rounded">
                                        <span class="ml-2 text-sm">面谈</span>
                                    </label>
                                </div>
                            </div>

                            <!-- 回访结果选择 -->
                            <div class="mb-4">
                                <label class="block text-sm font-medium text-gray-700 mb-2 text-left">回访结果：</label>
                                <div class="flex gap-4">
                                    <label class="inline-flex items-center">
                                        <input type="radio" name="callback-result-{{ patient.病历号 }}" value="成功" class="form-radio h-4 w-4 text-blue-600" onchange="toggleCallbackResult('{{ patient.病历号 }}', '成功')">
                                        <span class="ml-2 text-sm">成功</span>
                                    </label>
                                    <label class="inline-flex items-center">
                                        <input type="radio" name="callback-result-{{ patient.病历号 }}" value="不成功" class="form-radio h-4 w-4 text-blue-600" onchange="toggleCallbackResult('{{ patient.病历号 }}', '不成功')">
                                        <span class="ml-2 text-sm">不成功</span>
                                    </label>
                                    <label class="inline-flex items-center">
                                        <input type="radio" name="callback-result-{{ patient.病历号 }}" value="放弃回访" class="form-radio h-4 w-4 text-orange-600" onchange="toggleCallbackResult('{{ patient.病历号 }}', '放弃回访')">
                                        <span class="ml-2 text-sm">放弃回访</span>
                                    </label>
                                </div>
                            </div>

                            <!-- 成功时显示：下次预约时间 -->
                            <div id="success-fields-{{ patient.病历号 }}" class="mb-4 hidden">
                                <label class="block text-sm font-medium text-gray-700 mb-2 text-left">下次预约日期：</label>
                                <div class="relative">
                                    <input
                                        type="date"
                                        id="next-appointment-{{ patient.病历号 }}"
                                        name="next-appointment"
                                        class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                        placeholder="选择预约日期"
                                    />
                                    <div class="absolute inset-0 cursor-pointer" onclick="document.getElementById('next-appointment-{{ patient.病历号 }}').showPicker()"></div>
                                </div>
                            </div>

                            <!-- 不成功时显示：原因选择 -->
                            <div id="failure-fields-{{ patient.病历号 }}" class="mb-4 hidden">
                                <label class="block text-sm font-medium text-gray-700 mb-2 text-left">不成功的原因：</label>
                                <select
                                    id="failure-reason-{{ patient.病历号 }}"
                                    name="failure-reason"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                >
                                    <option value="">请选择不成功的原因</option>
                                    <option value="患者电话无人接听或关机">患者电话无人接听或关机</option>
                                    <option value="患者表示暂时没有时间">患者表示暂时没有时间</option>
                                    <option value="患者需要考虑或与家人商量">患者需要考虑或与家人商量</option>
                                    <option value="患者对治疗方案有疑虑">患者对治疗方案有疑虑</option>
                                    <option value="患者经济条件不允许或费用问题">患者经济条件不允许或费用问题</option>
                                    <option value="患者对诊断结果有疑虑或不信任">患者对诊断结果有疑虑或不信任</option>
                                    <option value="其他特殊情况">其他特殊情况</option>
                                </select>

                                <!-- 不成功备注 -->
                                <div class="mt-3">
                                    <label class="block text-sm font-medium text-gray-700 mb-2 text-left">不成功备注（可选）：</label>
                                    <textarea
                                        id="failure-reason-note-{{ patient.病历号 }}"
                                        name="failure-reason-note"
                                        rows="2"
                                        placeholder="请输入详细备注信息..."
                                        class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"
                                    ></textarea>
                                </div>
                            </div>

                            <!-- 放弃回访时显示：原因选择 -->
                            <div id="abandon-fields-{{ patient.病历号 }}" class="mb-4 hidden">
                                <label class="block text-sm font-medium text-gray-700 mb-2 text-left">放弃回访的原因：</label>
                                <select
                                    id="abandon-reason-{{ patient.病历号 }}"
                                    name="abandon-reason"
                                    class="w-full px-3 py-2 border border-orange-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-orange-500"
                                >
                                    <option value="">请选择放弃回访的原因</option>
                                    <option value="有下次预约">有下次预约</option>
                                    <option value="漏诊项不存在">漏诊项不存在</option>
                                    <option value="漏诊项已治疗">漏诊项已治疗</option>
                                    <option value="患者已由专属客服近期回访过">患者已由专属客服近期回访过</option>
                                    <option value="患者已做活动义齿修复">患者已做活动义齿修复</option>
                                    <option value="正畸拔牙患者（缺失牙为治疗设计，不需回访）">正畸拔牙患者（缺失牙为治疗设计，不需回访）</option>
                                    <option value="患者缺失牙但无修复空间（无法种植）">患者缺失牙但无修复空间（无法种植）</option>
                                    <option value="患者正在持续复诊/治疗中">患者正在持续复诊/治疗中</option>
                                    <option value="牙槽骨吸收提示轻微或无明显临床意义（无需回访）">牙槽骨吸收提示轻微或无明显临床意义（无需回访）</option>
                                    <option value="正畸患者出现牙槽骨吸收提示（一般无需回访）">正畸患者出现牙槽骨吸收提示（一般无需回访）</option>
                                    <option value="其他">其他</option>
                                </select>

                                <!-- 放弃回访备注 -->
                                <div class="mt-3">
                                    <label class="block text-sm font-medium text-gray-700 mb-2 text-left">放弃回访备注（可选）：</label>
                                    <textarea
                                        id="abandon-reason-note-{{ patient.病历号 }}"
                                        name="abandon-reason-note"
                                        rows="2"
                                        placeholder="请输入详细备注信息..."
                                        class="w-full px-3 py-2 border border-orange-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-orange-500 focus:border-orange-500 resize-none"
                                    ></textarea>
                                </div>
                            </div>

                            <!-- AI执行反馈模块 -->
                            <div class="mb-4 bg-yellow-50 p-4 rounded-lg border border-yellow-200">
                                <label class="block text-sm font-medium text-gray-700 mb-2 text-left">
                                    <i class="fas fa-robot mr-1"></i>AI执行反馈（可选）：
                                </label>

                                <!-- 一级选项 -->
                                <select
                                    id="ai-feedback-level1-{{ patient.病历号 }}"
                                    name="ai-feedback-level1"
                                    class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    onchange="toggleAIFeedbackLevel2('{{ patient.病历号 }}', this.value)"
                                >
                                    <option value="">无问题</option>
                                    <option value="AI漏诊检测错误（检测不准确或遗漏）">AI漏诊检测错误（检测不准确或遗漏）</option>
                                    <option value="AI话术内容不合适（过于专业或过于简单）">AI话术内容不合适（过于专业或过于简单）</option>
                                    <option value="AI语言表达不自然或用词不当">AI语言表达不自然或用词不当</option>
                                    <option value="AI内容缺乏个性化或与患者情况不符">AI内容缺乏个性化或与患者情况不符</option>
                                    <option value="AI治疗方案或复查时间建议不合理">AI治疗方案或复查时间建议不合理</option>
                                    <option value="AI对患者年龄/性别/病史分析错误">AI对患者年龄/性别/病史分析错误</option>
                                    <option value="AI生成内容格式错误或信息缺失">AI生成内容格式错误或信息缺失</option>
                                    <option value="AI未能正确解析患者数据或病历">AI未能正确解析患者数据或病历</option>
                                    <option value="AI功能不稳定或响应速度慢">AI功能不稳定或响应速度慢</option>
                                    <option value="其他AI相关问题">其他AI相关问题</option>
                                </select>

                                <!-- 二级选项（仅在选择"AI漏诊检测错误"时显示） -->
                                <div id="ai-feedback-level2-{{ patient.病历号 }}" class="mt-3 hidden">
                                    <label class="block text-sm font-medium text-gray-700 mb-2 text-left">具体错误类型：</label>
                                    <select
                                        id="ai-feedback-{{ patient.病历号 }}"
                                        name="ai-feedback"
                                        class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                                    >
                                        <option value="">请选择具体错误类型</option>
                                        <option value="CT影像只截取部分，AI识别不完整，误判缺失牙">CT影像只截取部分，AI识别不完整，误判缺失牙</option>
                                        <option value="AI误识别缺失牙，实际存在">AI误识别缺失牙，实际存在</option>
                                        <option value="AI误将正畸拔牙识别为缺失牙">AI误将正畸拔牙识别为缺失牙</option>
                                        <option value="AI缺失牙标注牙位错误">AI缺失牙标注牙位错误</option>
                                        <option value="AI误识别牙槽骨吸收（年轻患者轻微情况）">AI误识别牙槽骨吸收（年轻患者轻微情况）</option>
                                    </select>
                                </div>

                                <!-- AI反馈备注 -->
                                <div class="mt-3">
                                    <label class="block text-sm font-medium text-gray-700 mb-2 text-left">AI反馈备注（可选）：</label>
                                    <textarea
                                        id="ai-feedback-note-{{ patient.病历号 }}"
                                        name="ai-feedback-note"
                                        rows="2"
                                        placeholder="请输入详细备注信息..."
                                        class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"
                                    ></textarea>
                                </div>
                            </div>

                            <!-- 操作按钮 -->
                            <div class="flex justify-between items-center">
                                <div class="flex gap-2">
                                    <button type="button" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-md transition-colors" onclick="saveCallbackRecord('{{ patient.病历号 }}')">
                                        <i class="fas fa-save mr-1"></i>
                                        保存
                                    </button>
                                    <button type="button" class="px-4 py-2 bg-gray-500 hover:bg-gray-600 text-white text-sm font-medium rounded-md transition-colors" onclick="clearCallbackForm('{{ patient.病历号 }}')">
                                        <i class="fas fa-eraser mr-1"></i>
                                        清空
                                    </button>
                                </div>
                                <div class="text-xs text-gray-500">
                                    病历号：{{ patient.病历号 }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </main>

    <script>
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeScrollTriggers();
            initializeNavigation();
            loadCallbackRecords();
            initializeDragAndDrop();
        });

        // 初始化滚动触发器
        function initializeScrollTriggers() {
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('scroll-visible');
                    }
                });
            }, { threshold: 0.1 });

            document.querySelectorAll('.scroll-trigger').forEach(el => {
                observer.observe(el);
            });
        }

        // 初始化导航
        function initializeNavigation() {
            const navItems = document.querySelectorAll('.nav-item');
            navItems.forEach(item => {
                item.addEventListener('click', function(e) {
                    navItems.forEach(nav => nav.classList.remove('active'));
                    this.classList.add('active');
                });
            });
        }

        // 初始化拖拽功能
        function initializeDragAndDrop() {
            const navSidebar = document.getElementById('navSidebar');
            const dragHandle = document.getElementById('dragHandle');

            if (!navSidebar || !dragHandle) return;

            let isDragging = false;
            let startX, startY;
            let initialX, initialY;
            let currentX = 0, currentY = 0;

            // 将变量存储到全局对象中，以便重置函数访问
            window.navSidebarDragData = {
                currentX: 0,
                currentY: 0,
                updatePosition: updateSidebarPosition
            };

            // 从localStorage恢复位置
            const savedPosition = localStorage.getItem('navSidebarPosition');
            if (savedPosition) {
                const position = JSON.parse(savedPosition);
                currentX = position.x;
                currentY = position.y;
                window.navSidebarDragData.currentX = currentX;
                window.navSidebarDragData.currentY = currentY;
                updateSidebarPosition();
            }

            // 鼠标事件
            dragHandle.addEventListener('mousedown', startDrag);
            navSidebar.addEventListener('mousedown', startDrag);
            document.addEventListener('mousemove', drag);
            document.addEventListener('mouseup', endDrag);

            // 触摸事件（移动端支持）
            dragHandle.addEventListener('touchstart', startDragTouch, { passive: false });
            navSidebar.addEventListener('touchstart', startDragTouch, { passive: false });
            document.addEventListener('touchmove', dragTouch, { passive: false });
            document.addEventListener('touchend', endDrag);

            function startDrag(e) {
                if (e.target.classList.contains('nav-item') || e.target.closest('.nav-item')) {
                    return; // 不拖拽导航项
                }

                isDragging = true;
                navSidebar.classList.add('dragging');

                startX = e.clientX - currentX;
                startY = e.clientY - currentY;

                e.preventDefault();
            }

            function startDragTouch(e) {
                if (e.target.classList.contains('nav-item') || e.target.closest('.nav-item')) {
                    return; // 不拖拽导航项
                }

                isDragging = true;
                navSidebar.classList.add('dragging');

                const touch = e.touches[0];
                startX = touch.clientX - currentX;
                startY = touch.clientY - currentY;

                e.preventDefault();
            }

            function drag(e) {
                if (!isDragging) return;

                e.preventDefault();

                currentX = e.clientX - startX;
                currentY = e.clientY - startY;

                updateSidebarPosition();
            }

            function dragTouch(e) {
                if (!isDragging) return;

                e.preventDefault();

                const touch = e.touches[0];
                currentX = touch.clientX - startX;
                currentY = touch.clientY - startY;

                updateSidebarPosition();
            }

            function endDrag() {
                if (!isDragging) return;

                isDragging = false;
                navSidebar.classList.remove('dragging');

                // 边界检查
                const rect = navSidebar.getBoundingClientRect();
                const windowWidth = window.innerWidth;
                const windowHeight = window.innerHeight;

                // 确保侧边栏不会完全移出视窗
                const minX = -rect.width + 50; // 至少保留50px可见
                const maxX = windowWidth - 50;
                const minY = -rect.height + 50;
                const maxY = windowHeight - 50;

                currentX = Math.max(minX, Math.min(maxX, currentX));
                currentY = Math.max(minY, Math.min(maxY, currentY));

                // 更新全局变量
                window.navSidebarDragData.currentX = currentX;
                window.navSidebarDragData.currentY = currentY;

                updateSidebarPosition();

                // 保存位置到localStorage
                localStorage.setItem('navSidebarPosition', JSON.stringify({
                    x: currentX,
                    y: currentY
                }));
            }

            function updateSidebarPosition() {
                navSidebar.style.transform = `translate(${currentX}px, calc(-50% + ${currentY}px))`;
            }

            // 窗口大小改变时重新检查位置
            window.addEventListener('resize', function() {
                const rect = navSidebar.getBoundingClientRect();
                const windowWidth = window.innerWidth;
                const windowHeight = window.innerHeight;

                const minX = -rect.width + 50;
                const maxX = windowWidth - 50;
                const minY = -rect.height + 50;
                const maxY = windowHeight - 50;

                currentX = Math.max(minX, Math.min(maxX, currentX));
                currentY = Math.max(minY, Math.min(maxY, currentY));

                // 更新全局变量
                window.navSidebarDragData.currentX = currentX;
                window.navSidebarDragData.currentY = currentY;

                updateSidebarPosition();

                localStorage.setItem('navSidebarPosition', JSON.stringify({
                    x: currentX,
                    y: currentY
                }));
            });
        }

        // 加载回访记录
        function loadCallbackRecords() {
            const caseNumber = '{{ patient.病历号 }}';
            updateCallbackRecords(caseNumber);
        }



        // 更新回访记录显示
        function updateCallbackRecordsDisplay(records) {
            const countElement = document.getElementById('callback-records-count');
            if (countElement) {
                countElement.textContent = `Callback Records (${records.length})`;
            }
        }

        // 切换回访结果显示
        function toggleCallbackResult(patientId, result) {
            const successFields = document.getElementById(`success-fields-${patientId}`);
            const failureFields = document.getElementById(`failure-fields-${patientId}`);
            const abandonFields = document.getElementById(`abandon-fields-${patientId}`);

            // 隐藏所有条件字段
            if (successFields) successFields.classList.add('hidden');
            if (failureFields) failureFields.classList.add('hidden');
            if (abandonFields) abandonFields.classList.add('hidden');

            // 清空所有字段
            const appointmentInput = document.getElementById(`next-appointment-${patientId}`);
            const failureSelect = document.getElementById(`failure-reason-${patientId}`);
            const abandonSelect = document.getElementById(`abandon-reason-${patientId}`);

            if (appointmentInput) appointmentInput.value = '';
            if (failureSelect) failureSelect.value = '';
            if (abandonSelect) abandonSelect.value = '';

            // 根据选择显示对应字段
            if (result === '成功') {
                if (successFields) successFields.classList.remove('hidden');
            } else if (result === '不成功') {
                if (failureFields) failureFields.classList.remove('hidden');
            } else if (result === '放弃回访') {
                if (abandonFields) abandonFields.classList.remove('hidden');
            }

            console.log(`患者 ${patientId} 选择回访结果: ${result}`);
        }

        // 切换AI反馈二级选项显示
        function toggleAIFeedbackLevel2(patientId, level1Value) {
            const level2Container = document.getElementById(`ai-feedback-level2-${patientId}`);
            const level2Select = document.getElementById(`ai-feedback-${patientId}`);

            if (level1Value === 'AI漏诊检测错误（检测不准确或遗漏）') {
                // 显示二级选项
                if (level2Container) level2Container.classList.remove('hidden');
            } else {
                // 隐藏二级选项并清空选择
                if (level2Container) level2Container.classList.add('hidden');
                if (level2Select) level2Select.value = '';
            }

            console.log(`患者 ${patientId} AI反馈一级选项: ${level1Value}`);
        }

        // 保存回访记录
        function saveCallbackRecord(patientId) {
            const checkboxes = document.querySelectorAll(`input[name="callback-method-${patientId}"]:checked`);
            const resultRadio = document.querySelector(`input[name="callback-result-${patientId}"]:checked`);
            const appointmentInput = document.getElementById(`next-appointment-${patientId}`);
            const failureSelect = document.getElementById(`failure-reason-${patientId}`);
            const abandonSelect = document.getElementById(`abandon-reason-${patientId}`);
            const aiFeedbackLevel1Select = document.getElementById(`ai-feedback-level1-${patientId}`);
            const aiFeedbackSelect = document.getElementById(`ai-feedback-${patientId}`);
            const failureReasonNote = document.getElementById(`failure-reason-note-${patientId}`);
            const abandonReasonNote = document.getElementById(`abandon-reason-note-${patientId}`);
            const aiFeedbackNote = document.getElementById(`ai-feedback-note-${patientId}`);

            // 验证回访方式
            const methods = Array.from(checkboxes).map(cb => cb.value);
            if (methods.length === 0) {
                alert('请选择至少一种回访方式');
                return;
            }

            console.log('发送的数据:', {
                caseNumber: patientId,
                callbackMethods: methods,
                callbackResult: resultRadio ? resultRadio.value : null
            });

            // 验证回访结果
            if (!resultRadio) {
                alert('请选择回访结果');
                return;
            }

            const callbackResult = resultRadio.value;
            let nextAppointmentTime = null;
            let failureReason = null;
            let abandonReason = null;
            let failureReasonNoteValue = null;
            let abandonReasonNoteValue = null;

            if (callbackResult === '成功') {
                // 回访成功时，预约时间可选
                nextAppointmentTime = appointmentInput ? appointmentInput.value : null;
            } else if (callbackResult === '不成功') {
                // 回访不成功时，必须选择原因
                if (!failureSelect || !failureSelect.value) {
                    alert('回访不成功时，请选择具体原因');
                    if (failureSelect) failureSelect.focus();
                    return;
                }
                failureReason = failureSelect.value;
                failureReasonNoteValue = failureReasonNote ? failureReasonNote.value : null;
            } else if (callbackResult === '放弃回访') {
                // 放弃回访时，必须选择原因
                if (!abandonSelect || !abandonSelect.value) {
                    alert('放弃回访时，请选择具体原因');
                    if (abandonSelect) abandonSelect.focus();
                    return;
                }
                abandonReason = abandonSelect.value;
                abandonReasonNoteValue = abandonReasonNote ? abandonReasonNote.value : null;
            }

            // AI反馈信息（可选）
            let aiFeedback = null;
            const aiFeedbackLevel1 = aiFeedbackLevel1Select ? aiFeedbackLevel1Select.value : null;

            if (aiFeedbackLevel1 === 'AI漏诊检测错误（检测不准确或遗漏）') {
                // 如果选择了漏诊检测错误，使用二级选项的值
                aiFeedback = aiFeedbackSelect ? aiFeedbackSelect.value : null;
                // 如果二级选项未选择，提示用户
                if (!aiFeedback) {
                    alert('请选择具体的AI漏诊检测错误类型');
                    if (aiFeedbackSelect) aiFeedbackSelect.focus();
                    // 恢复按钮状态
                    const saveBtn = document.querySelector(`button[onclick="saveCallbackRecord('${patientId}')"]`);
                    saveBtn.innerHTML = '<i class="fas fa-save mr-1"></i>保存回访记录';
                    saveBtn.disabled = false;
                    return;
                }
            } else if (aiFeedbackLevel1) {
                // 其他一级选项直接使用一级选项的值
                aiFeedback = aiFeedbackLevel1;
            }

            // 显示保存中状态
            const saveBtn = document.querySelector(`button[onclick="saveCallbackRecord('${patientId}')"]`);
            const originalText = saveBtn.innerHTML;
            saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>保存中...';
            saveBtn.disabled = true;

            const saveData = {
                caseNumber: patientId,
                callbackMethods: methods,
                callbackResult: callbackResult,
                nextAppointmentTime: nextAppointmentTime,
                failureReason: failureReason,
                abandonReason: abandonReason,
                aiFeedbackType: aiFeedback,
                failureReasonNote: failureReasonNote ? failureReasonNote.value : null,
                abandonReasonNote: abandonReasonNote ? abandonReasonNote.value : null,
                aiFeedbackNote: aiFeedbackNote ? aiFeedbackNote.value : null,
                callbackStatus: '已回访',
                operator: '系统用户',
                timestamp: new Date().toISOString()
            };

            const apiBase = window.API_BASE_URL || '';
            fetch(`${apiBase}/api/save-callback`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(saveData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showSuccessToast('回访记录保存成功！');
                    clearCallbackForm(patientId);
                    // 实时更新回访记录显示
                    updateCallbackRecords(patientId);
                } else {
                    showErrorToast(`保存失败：${data.message}`);
                }
            })
            .catch(error => {
                console.error('保存失败:', error);
                alert('网络错误，保存失败。请检查网络连接或联系管理员。');
            })
            .finally(() => {
                saveBtn.innerHTML = originalText;
                saveBtn.disabled = false;
            });
        }

        // 清空回访表单
        function clearCallbackForm(patientId) {
            const checkboxes = document.querySelectorAll(`input[name="callback-method-${patientId}"]`);
            const resultRadios = document.querySelectorAll(`input[name="callback-result-${patientId}"]`);
            const appointmentInput = document.getElementById(`next-appointment-${patientId}`);
            const failureSelect = document.getElementById(`failure-reason-${patientId}`);
            const abandonSelect = document.getElementById(`abandon-reason-${patientId}`);
            const aiFeedbackLevel1Select = document.getElementById(`ai-feedback-level1-${patientId}`);
            const aiFeedbackSelect = document.getElementById(`ai-feedback-${patientId}`);
            const aiFeedbackLevel2Container = document.getElementById(`ai-feedback-level2-${patientId}`);
            const failureReasonNote = document.getElementById(`failure-reason-note-${patientId}`);
            const abandonReasonNote = document.getElementById(`abandon-reason-note-${patientId}`);
            const aiFeedbackNote = document.getElementById(`ai-feedback-note-${patientId}`);
            const successFields = document.getElementById(`success-fields-${patientId}`);
            const failureFields = document.getElementById(`failure-fields-${patientId}`);
            const abandonFields = document.getElementById(`abandon-fields-${patientId}`);

            // 重置回访方式
            checkboxes.forEach(cb => {
                cb.checked = cb.value === '打电话'; // 只保留打电话选中
            });

            // 重置回访结果
            resultRadios.forEach(radio => {
                radio.checked = false;
            });

            // 隐藏条件字段
            if (successFields) successFields.classList.add('hidden');
            if (failureFields) failureFields.classList.add('hidden');
            if (abandonFields) abandonFields.classList.add('hidden');
            if (aiFeedbackLevel2Container) aiFeedbackLevel2Container.classList.add('hidden');

            // 清空表单值
            if (appointmentInput) appointmentInput.value = '';
            if (failureSelect) failureSelect.value = '';
            if (abandonSelect) abandonSelect.value = '';
            if (aiFeedbackLevel1Select) aiFeedbackLevel1Select.value = '';
            if (aiFeedbackSelect) aiFeedbackSelect.value = '';
            if (failureReasonNote) failureReasonNote.value = '';
            if (abandonReasonNote) abandonReasonNote.value = '';
            if (aiFeedbackNote) aiFeedbackNote.value = '';
        }

        // 显示成功提示
        function showSuccessToast(message) {
            const toast = document.createElement('div');
            toast.className = 'fixed top-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
            toast.textContent = message;
            document.body.appendChild(toast);
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 3000);
        }

        // 显示错误提示
        function showErrorToast(message) {
            const toast = document.createElement('div');
            toast.className = 'fixed top-4 right-4 bg-red-500 text-white px-6 py-3 rounded-lg shadow-lg z-50';
            toast.textContent = message;
            document.body.appendChild(toast);
            setTimeout(() => {
                document.body.removeChild(toast);
            }, 3000);
        }

        // 实时更新回访记录显示
        async function updateCallbackRecords(patientId) {
            try {
                // 获取最新的回访记录
                const response = await fetch(`${window.API_BASE_URL}/api/callback-records/${patientId}`);
                const data = await response.json();

                if (data.success) {
                    const records = data.data;
                    console.log('获取到的回访记录:', records);

                    // 更新记录计数
                    updateRecordCount(records.length);

                    // 更新主题色（从灰色切换到橙色）
                    updateThemeColor(records.length > 0);

                    // 更新历史记录列表
                    updateRecordsList(records);

                } else {
                    console.error('获取回访记录失败:', data.message);
                }
            } catch (error) {
                console.error('更新回访记录失败:', error);
            }
        }

        // 更新记录计数
        function updateRecordCount(count) {
            const countElement = document.getElementById('callback-records-count');
            if (countElement) {
                countElement.textContent = `Callback Records (${count})`;
            }
        }

        // 更新主题色
        function updateThemeColor(hasRecords) {
            const container = document.getElementById('callback-records-container');
            const header = document.getElementById('callback-records-header');

            if (hasRecords) {
                // 有记录时使用橙色主题
                container.className = container.className.replace('border-gray-500', 'border-orange-500');
                header.className = header.className.replace('bg-gray-600', 'bg-orange-600');
            } else {
                // 无记录时使用灰色主题
                container.className = container.className.replace('border-orange-500', 'border-gray-500');
                header.className = header.className.replace('bg-orange-600', 'bg-gray-600');
            }
        }

        // 更新记录列表
        function updateRecordsList(records) {
            const listContainer = document.getElementById('callback-records-list');
            if (!listContainer) return;

            if (records.length === 0) {
                // 显示空状态
                listContainer.innerHTML = `
                    <div class="text-center py-8">
                        <i class="fas fa-phone-slash text-4xl text-gray-300 mb-3"></i>
                        <h3 class="text-lg font-medium text-gray-600 mb-2">暂无回访记录</h3>
                        <p class="text-gray-500 mb-4">该患者尚未进行过回访，请填写首次回访记录。</p>
                    </div>`;
            } else {
                // 生成历史记录HTML
                let recordsHtml = records.map(record => generateRecordHTML(record)).join('');
                listContainer.innerHTML = recordsHtml;
            }
        }

        // 生成单个记录的HTML
        function generateRecordHTML(record) {
            const methodsDisplay = record.callback_methods ? record.callback_methods.join(', ') : '未知';
            const resultDisplay = record.callback_result || (record.callback_success ? '成功' : '不成功');

            // 根据回访结果确定颜色
            let resultColor = 'gray';
            if (resultDisplay === '成功') {
                resultColor = 'green';
            } else if (resultDisplay === '不成功') {
                resultColor = 'red';
            } else if (resultDisplay === '放弃回访') {
                resultColor = 'orange';
            }

            const createTime = new Date(record.create_time).toLocaleString('zh-CN');

            let detailsHtml = '';
            if (resultDisplay === '成功' && record.next_appointment_time) {
                detailsHtml += `<p class="text-sm text-gray-600"><i class="fas fa-calendar mr-1"></i>预约日期：${record.next_appointment_time}</p>`;
            } else if (resultDisplay === '不成功' && record.failure_reason) {
                detailsHtml += `<p class="text-sm text-gray-600"><i class="fas fa-exclamation-triangle mr-1"></i>失败原因：${record.failure_reason}</p>`;
                if (record.failure_reason_note) {
                    detailsHtml += `<p class="text-sm text-gray-500 ml-4"><i class="fas fa-comment mr-1"></i>备注：${record.failure_reason_note}</p>`;
                }
            } else if (resultDisplay === '放弃回访' && record.abandon_reason) {
                detailsHtml += `<p class="text-sm text-gray-600"><i class="fas fa-ban mr-1"></i>放弃原因：${record.abandon_reason}</p>`;
                if (record.abandon_reason_note) {
                    detailsHtml += `<p class="text-sm text-gray-500 ml-4"><i class="fas fa-comment mr-1"></i>备注：${record.abandon_reason_note}</p>`;
                }
            }

            if (record.ai_feedback_type) {
                detailsHtml += `<p class="text-sm text-yellow-600 mt-1"><i class="fas fa-robot mr-1"></i>AI反馈：${record.ai_feedback_type}</p>`;
                if (record.ai_feedback_note) {
                    detailsHtml += `<p class="text-sm text-yellow-500 ml-4"><i class="fas fa-comment mr-1"></i>备注：${record.ai_feedback_note}</p>`;
                }
            }

            return `
                <div class="callback-record-item bg-white border border-gray-200 rounded-lg p-6 mb-4 shadow-sm hover:shadow-md transition-shadow">
                    <div class="flex justify-between items-start mb-4">
                        <div class="flex items-center space-x-4">
                            <div class="bg-blue-100 p-2 rounded-full">
                                <i class="fas fa-phone text-blue-600"></i>
                            </div>
                            <div>
                                <h4 class="font-semibold text-gray-900">回访记录 #${record.record_id}</h4>
                                <p class="text-sm text-gray-600">回访时间：${createTime}</p>
                                <p class="text-sm text-gray-600">状态：${record.callback_status}</p>
                            </div>
                        </div>
                        <div class="text-right">
                            <div class="flex items-center gap-2 mb-2">
                                <span class="bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
                                    ${methodsDisplay}
                                </span>
                                <span class="bg-${resultColor}-100 text-${resultColor}-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
                                    ${resultDisplay}
                                </span>
                            </div>
                            <p class="text-xs text-gray-500">操作员：${record.operator_name || '未知'}</p>
                        </div>
                    </div>
                    ${detailsHtml ? `<div class="bg-gray-50 p-4 rounded-lg">${detailsHtml}</div>` : ''}
                </div>`;
        }

        // 生成AI回访话术
        async function generateCallbackScript() {
            const button = event.target;
            const originalText = button.innerHTML;

            try {
                // 显示加载状态
                button.disabled = true;
                button.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>生成中...';

                // 获取患者信息
                const patientId = '{{ patient.病历号 }}';
                const clinicId = '{{ clinic_id }}';

                // 调用生成API
                const response = await fetch(`${window.API_BASE_URL}/api/generate-callback-script`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        clinic_id: clinicId,
                        patient_id: patientId
                    })
                });

                const data = await response.json();

                if (data.success) {
                    // 刷新页面以显示新生成的话术
                    window.location.reload();
                } else {
                    alert('生成失败：' + (data.message || '未知错误'));
                }

            } catch (error) {
                console.error('生成回访话术失败:', error);
                alert('生成失败：网络错误或服务器错误');
            } finally {
                // 恢复按钮状态
                button.disabled = false;
                button.innerHTML = originalText;
            }
        }
    </script>
</body>
</html>
