<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>患者画像系统 - {{ clinic_name }}</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">
    
    <style>
        .hover-effect:hover {
            transform: translateY(-4px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
            transition: all 0.2s ease;
        }
        .highlight {
            background-color: rgba(255, 255, 0, 0.3);
        }
        .priority-diagnosis-tag {
            @apply inline-block bg-red-100 text-red-800 text-xs font-medium px-2.5 py-1 rounded-full;
        }
    </style>
</head>
<body class="bg-gray-50 text-gray-900">
    <header class="bg-blue-700 text-white py-6 mb-8">
        <div class="container mx-auto px-4">
            <h1 class="text-4xl font-bold">患者画像系统 <span class="text-xl font-normal ml-2">Patient Profiles</span></h1>
        </div>
    </header>
    
    <main class="container mx-auto px-4 mb-16">
        <section>
            <div class="flex flex-col md:flex-row justify-between items-center mb-6 gap-4">
                <h2 class="text-2xl font-bold">所有患者 <span class="text-sm text-gray-500 ml-2">({{ patients|length }})</span></h2>
                
                <!-- 搜索框 -->
                <div class="relative w-full md:w-1/3">
                    <input 
                        type="text" 
                        id="searchInput" 
                        placeholder="搜索患者姓名、病历号、诊所..." 
                        class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    >
                    <div class="absolute inset-y-0 right-0 flex items-center pr-3">
                        <i class="fas fa-search text-gray-400"></i>
                    </div>
                </div>
                
                <div class="flex space-x-2">
                    <button id="sortByTime" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">
                        <i class="fas fa-sort-amount-down mr-2"></i>按上次就诊时间排序
                    </button>
                </div>
            </div>
            
            <!-- 筛选控件 -->
            <div class="mb-6 bg-white p-4 rounded-lg shadow">
                <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
                    <!-- 漏诊项筛选 -->
                    <div>
                        <label for="selectedDiagnosisFilter" class="block text-sm font-medium text-gray-700 mb-2">漏诊项</label>
                        <select id="selectedDiagnosisFilter" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">全部漏诊项</option>
                        </select>
                    </div>
                    
                    <!-- 医生筛选 -->
                    <div>
                        <label for="doctorFilter" class="block text-sm font-medium text-gray-700 mb-2">医生</label>
                        <select id="doctorFilter" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">全部医生</option>
                            {% for doctor in doctors %}
                            <option value="{{ doctor }}">{{ doctor }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    
                    <!-- 就诊时间筛选 -->
                    <div>
                        <label for="timeFilter" class="block text-sm font-medium text-gray-700 mb-2">就诊时间</label>
                        <select id="timeFilter" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">全部时间</option>
                            <option value="2025-06">2025年06月</option>
                            <option value="2025-05">2025年05月</option>
                            <option value="2025-04">2025年04月</option>
                            <option value="2025-03">2025年03月</option>
                            <option value="2025-02">2025年02月</option>
                            <option value="2025-01">2025年01月</option>
                        </select>
                    </div>
                    
                    <!-- 回访状态筛选 -->
                    <div>
                        <label for="callbackStatusFilter" class="block text-sm font-medium text-gray-700 mb-2">回访状态</label>
                        <select id="callbackStatusFilter" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">全部状态</option>
                            <option value="已回访">已回访</option>
                            <option value="未回访">未回访</option>
                        </select>
                    </div>
                    
                    <!-- 回访结果筛选 -->
                    <div>
                        <label for="callbackSuccessFilter" class="block text-sm font-medium text-gray-700 mb-2">回访结果</label>
                        <select id="callbackSuccessFilter" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">全部结果</option>
                            <option value="未回访">未回访</option>
                            <option value="成功">成功</option>
                            <option value="不成功">不成功</option>
                            <option value="放弃回访">放弃回访</option>
                        </select>
                    </div>
                </div>
                
                <div class="mt-4 flex justify-between items-center">
                    <button id="clearFilters" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">
                        <i class="fas fa-times mr-2"></i>清除筛选
                    </button>
                    <span id="matchCount" class="text-sm text-gray-600">显示 {{ patients|length }} 个患者</span>
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6" id="patientsGrid">
                {% for patient in patients %}
                <a href="{{ url_for('patient.patient_detail', clinic_id=clinic_id, patient_id=patient.病历号) }}" class="block patient-card"
                   data-name="{{ patient.姓名 }}" 
                   data-id="{{ patient.病历号 }}" 
                   data-clinic="{{ patient.最后一次就诊诊所 or clinic_name }}" 
                   data-doctor="{{ patient.最后一次就诊医生 or '' }}" 
                   data-selected-diagnosis="{{ patient.漏诊项 or '' }}" 
                   data-visit-time="{{ patient.最后一次就诊时间 or '' }}" 
                   data-callback-status="未回访"
                   data-callback-success="未回访">
                    <div class="bg-white rounded-xl shadow hover-effect p-6 border-l-4 border-blue-500">
                        <div class="flex justify-between items-start">
                            <div>
                                <h3 class="text-xl font-bold patient-name">{{ patient.姓名 }}</h3>
                                <p class="text-gray-600">{{ patient.性别 }} | {{ patient.年龄 }}岁 | <span class="patient-id">{{ patient.病历号 }}</span></p>
                            </div>
                            {% if patient.漏诊项 and patient.漏诊项 != '' %}
                                <span class="diagnosis-tag bg-red-50 text-red-800 text-xs font-medium px-2.5 py-1 rounded border border-red-200"
                                      data-full-diagnosis="{{ patient.漏诊项 }}">
                                    有漏诊项
                                </span>
                            {% else %}
                                <span class="bg-gray-100 text-gray-800 text-xs font-medium px-2.5 py-1 rounded-full">
                                    无优先诊断
                                </span>
                            {% endif %}
                        </div>
                        <div class="mt-4 pt-4 border-t border-gray-100">
                            <p class="flex items-center text-gray-700">
                                <i class="fas fa-hospital mr-2 text-blue-500"></i> 
                                <span class="patient-clinic">{{ patient.最后一次就诊诊所 or clinic_name }}</span>
                            </p>
                            <p class="flex items-center text-gray-700 mt-1">
                                <i class="fas fa-user-md mr-2 text-blue-500"></i> 
                                <span class="patient-doctor">{{ patient.最后一次就诊医生 or '未知医生' }}</span>
                            </p>
                            <p class="flex items-center text-gray-700 mt-1">
                                <i class="fas fa-calendar mr-2 text-blue-500"></i>
                                {% if patient.最后一次就诊时间 %}
                                    {{ patient.最后一次就诊时间.split(' ')[0] if ' ' in (patient.最后一次就诊时间 or '') else (patient.最后一次就诊时间 or '未知时间') }}
                                {% else %}
                                    未知时间
                                {% endif %}
                            </p>
                            <div class="flex items-center mt-2 space-x-2">
                                <span class="bg-gray-100 text-gray-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
                                    <i class="fas fa-phone mr-1"></i>未回访
                                </span>
                            </div>
                        </div>
                        <div class="mt-3 text-right">
                            {% set fee_value = patient.上次就诊收费 %}
                            {% if fee_value and fee_value != 0 and fee_value|string != 'nan' and fee_value|string != 'None' %}
                                <span class="text-green-600 font-semibold">¥{{ "%.2f"|format(fee_value|float) }} 元</span>
                            {% else %}
                                <span class="text-gray-500 font-semibold">免费</span>
                            {% endif %}
                        </div>
                    </div>
                </a>
                {% endfor %}
            </div>
        </section>
    </main>

    <script>
        // 全局变量
        let allPatients = [];
        let filteredPatients = [];
        let callbackStatusData = {};

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializePatients();
            loadCallbackStatus();
            setupEventListeners();
            populateFilters();
            updateDiagnosisTags();
        });

        function initializePatients() {
            // 获取所有患者卡片
            const patientCards = document.querySelectorAll('.patient-card');
            allPatients = Array.from(patientCards).map(card => ({
                element: card,
                name: card.dataset.name,
                id: card.dataset.id,
                clinic: card.dataset.clinic,
                doctor: card.dataset.doctor,
                selectedDiagnosis: card.dataset.selectedDiagnosis,
                visitTime: card.dataset.visitTime,
                callbackStatus: card.dataset.callbackStatus,
                callbackSuccess: card.dataset.callbackSuccess
            }));
            filteredPatients = [...allPatients];
        }

        function loadCallbackStatus() {
            // 加载回访状态数据
            fetch(`/api/callback-status/{{ clinic_id }}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        callbackStatusData = data.data;
                        updatePatientCallbackStatus();
                    }
                })
                .catch(error => {
                    console.error('加载回访状态失败:', error);
                });
        }

        function updatePatientCallbackStatus() {
            // 更新患者卡片的回访状态
            allPatients.forEach(patient => {
                const statusInfo = callbackStatusData[patient.id];
                if (statusInfo) {
                    patient.callbackStatus = statusInfo.callback_status;
                    patient.callbackSuccess = statusInfo.callback_result;
                } else {
                    // 没有回访记录的患者
                    patient.callbackStatus = '未回访';
                    patient.callbackSuccess = '未回访';
                }

                // 更新DOM元素
                const statusContainer = patient.element.querySelector('.flex.items-center.mt-2.space-x-2');
                if (statusContainer) {
                    updateStatusDisplay(statusContainer, statusInfo || {
                        callback_status: patient.callbackStatus,
                        callback_result: patient.callbackSuccess
                    });
                }
            });
        }

        function updateStatusDisplay(container, statusInfo) {
            container.innerHTML = '';

            // 回访状态标签
            const statusSpan = document.createElement('span');
            if (statusInfo.callback_status === '已回访') {
                statusSpan.className = 'bg-green-100 text-green-800 text-xs font-medium px-2.5 py-0.5 rounded-full';
                statusSpan.innerHTML = '<i class="fas fa-phone mr-1"></i>已回访';
            } else {
                statusSpan.className = 'bg-gray-100 text-gray-800 text-xs font-medium px-2.5 py-0.5 rounded-full';
                statusSpan.innerHTML = '<i class="fas fa-phone mr-1"></i>未回访';
            }
            container.appendChild(statusSpan);

            // 回访结果标签 - 始终显示
            const resultSpan = document.createElement('span');
            if (statusInfo.callback_result === '成功') {
                resultSpan.className = 'bg-green-100 text-green-800 text-xs font-medium px-2.5 py-0.5 rounded-full';
                resultSpan.innerHTML = '<i class="fas fa-check mr-1"></i>成功';
            } else if (statusInfo.callback_result === '不成功') {
                resultSpan.className = 'bg-red-100 text-red-800 text-xs font-medium px-2.5 py-0.5 rounded-full';
                resultSpan.innerHTML = '<i class="fas fa-times mr-1"></i>不成功';
            } else if (statusInfo.callback_result === '放弃回访') {
                resultSpan.className = 'bg-orange-100 text-orange-800 text-xs font-medium px-2.5 py-0.5 rounded-full';
                resultSpan.innerHTML = '<i class="fas fa-ban mr-1"></i>放弃回访';
            } else {
                // 未回访状态
                resultSpan.className = 'bg-gray-100 text-gray-800 text-xs font-medium px-2.5 py-0.5 rounded-full';
                resultSpan.innerHTML = '<i class="fas fa-clock mr-1"></i>未回访';
            }
            container.appendChild(resultSpan);
        }

        function setupEventListeners() {
            // 搜索功能
            document.getElementById('searchInput').addEventListener('input', filterPatients);

            // 筛选器
            document.getElementById('selectedDiagnosisFilter').addEventListener('change', filterPatients);
            document.getElementById('doctorFilter').addEventListener('change', filterPatients);
            document.getElementById('timeFilter').addEventListener('change', filterPatients);
            document.getElementById('callbackStatusFilter').addEventListener('change', filterPatients);
            document.getElementById('callbackSuccessFilter').addEventListener('change', filterPatients);

            // 清除筛选
            document.getElementById('clearFilters').addEventListener('click', clearFilters);

            // 排序
            document.getElementById('sortByTime').addEventListener('click', sortByTime);
        }

        function populateFilters() {
            // 填充漏诊项筛选器
            const diagnosisSet = new Set();
            allPatients.forEach(patient => {
                if (patient.selectedDiagnosis && patient.selectedDiagnosis.trim()) {
                    // 提取简洁的漏诊项名称
                    let diagnosisName = patient.selectedDiagnosis;

                    // 如果是完整格式 "漏诊项: xxx，牙位: []"，提取漏诊项名称
                    if (diagnosisName.includes('漏诊项')) {
                        // 支持中文冒号和英文冒号，中文逗号和英文逗号
                        const match = diagnosisName.match(/漏诊项[：:]\s*([^，,]+)/);
                        if (match) {
                            diagnosisName = match[1].trim();
                        }
                    }

                    diagnosisSet.add(diagnosisName);
                }
            });

            const diagnosisFilter = document.getElementById('selectedDiagnosisFilter');
            // 清空现有选项（除了默认选项）
            while (diagnosisFilter.children.length > 1) {
                diagnosisFilter.removeChild(diagnosisFilter.lastChild);
            }

            diagnosisSet.forEach(diagnosis => {
                const option = document.createElement('option');
                option.value = diagnosis;
                option.textContent = diagnosis;
                diagnosisFilter.appendChild(option);
                console.log('添加选项:', diagnosis); // 调试信息
            });
        }

        function updateDiagnosisTags() {
            // 更新患者卡片右上角的漏诊项标签
            const diagnosisTags = document.querySelectorAll('.diagnosis-tag');
            diagnosisTags.forEach(tag => {
                const fullDiagnosis = tag.dataset.fullDiagnosis;
                if (fullDiagnosis && fullDiagnosis.trim()) {
                    let diagnosisName = fullDiagnosis;

                    // 如果是完整格式 "漏诊项: xxx，牙位: []"，提取漏诊项名称
                    if (diagnosisName.includes('漏诊项')) {
                        // 支持中文冒号和英文冒号，中文逗号和英文逗号
                        const match = diagnosisName.match(/漏诊项[：:]\s*([^，,]+)/);
                        if (match) {
                            diagnosisName = match[1].trim();
                        }
                    }

                    tag.textContent = diagnosisName;
                }
            });
        }

        function filterPatients() {
            const searchTerm = document.getElementById('searchInput').value.toLowerCase();
            const selectedDiagnosis = document.getElementById('selectedDiagnosisFilter').value;
            const selectedDoctor = document.getElementById('doctorFilter').value;
            const selectedTime = document.getElementById('timeFilter').value;
            const selectedCallbackStatus = document.getElementById('callbackStatusFilter').value;
            const selectedCallbackSuccess = document.getElementById('callbackSuccessFilter').value;

            filteredPatients = allPatients.filter(patient => {
                // 搜索过滤
                const matchesSearch = !searchTerm ||
                    patient.name.toLowerCase().includes(searchTerm) ||
                    patient.id.toLowerCase().includes(searchTerm) ||
                    patient.clinic.toLowerCase().includes(searchTerm);

                // 漏诊项过滤
                let matchesDiagnosis = !selectedDiagnosis;
                if (selectedDiagnosis && patient.selectedDiagnosis) {
                    // 提取患者的简洁漏诊项名称进行比较
                    let patientDiagnosisName = patient.selectedDiagnosis;
                    if (patientDiagnosisName.includes('漏诊项')) {
                        // 支持中文冒号和英文冒号，中文逗号和英文逗号
                        const match = patientDiagnosisName.match(/漏诊项[：:]\s*([^，,]+)/);
                        if (match) {
                            patientDiagnosisName = match[1].trim();
                        }
                    }
                    matchesDiagnosis = patientDiagnosisName === selectedDiagnosis;
                }

                // 医生过滤
                const matchesDoctor = !selectedDoctor || patient.doctor === selectedDoctor;

                // 回访状态过滤
                const matchesCallbackStatus = !selectedCallbackStatus || patient.callbackStatus === selectedCallbackStatus;

                // 回访结果过滤
                const matchesCallbackSuccess = !selectedCallbackSuccess || patient.callbackSuccess === selectedCallbackSuccess;

                return matchesSearch && matchesDiagnosis && matchesDoctor && matchesCallbackStatus && matchesCallbackSuccess;
            });

            updateDisplay();
        }

        function clearFilters() {
            document.getElementById('searchInput').value = '';
            document.getElementById('selectedDiagnosisFilter').value = '';
            document.getElementById('doctorFilter').value = '';
            document.getElementById('timeFilter').value = '';
            document.getElementById('callbackStatusFilter').value = '';
            document.getElementById('callbackSuccessFilter').value = '';

            filteredPatients = [...allPatients];
            updateDisplay();
        }

        function sortByTime() {
            filteredPatients.sort((a, b) => {
                const timeA = new Date(a.visitTime || '1970-01-01');
                const timeB = new Date(b.visitTime || '1970-01-01');
                return timeB - timeA; // 降序排列
            });
            updateDisplay();
        }

        function updateDisplay() {
            const grid = document.getElementById('patientsGrid');
            const matchCount = document.getElementById('matchCount');

            // 隐藏所有患者卡片
            allPatients.forEach(patient => {
                patient.element.style.display = 'none';
            });

            // 显示筛选后的患者卡片
            filteredPatients.forEach(patient => {
                patient.element.style.display = 'block';
            });

            // 更新匹配计数
            matchCount.textContent = `显示 ${filteredPatients.length} 个患者`;
        }
    </script>
</body>
</html>
