#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
安全的患者数据导入脚本
不删除现有数据，只添加或更新缺失的数据
确保生产环境数据安全
"""

import os
import json
import pymysql
from datetime import datetime

# 数据库配置 - 修复为Docker容器内的正确配置
DB_CONFIG = {
    'host': 'mysql',  # 使用Docker服务名
    'port': 3306,     # 使用标准MySQL端口
    'user': 'root',   # 使用root用户
    'password': 'dev_password_123',  # 使用正确的root密码
    'database': 'callback_system',
    'charset': 'utf8mb4'
}

def connect_database():
    """连接数据库"""
    try:
        connection = pymysql.connect(**DB_CONFIG)
        print("✅ 数据库连接成功")
        return connection
    except Exception as e:
        print(f"❌ 数据库连接失败: {e}")
        return None

def backup_existing_data(connection):
    """备份现有患者数据"""
    try:
        with connection.cursor() as cursor:
            # 检查现有数据
            cursor.execute("SELECT COUNT(*) FROM patients")
            existing_count = cursor.fetchone()[0]
            print(f"📊 现有患者数据: {existing_count} 条")
            
            if existing_count > 0:
                # 备份现有数据到临时表
                backup_table = f"patients_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
                cursor.execute(f"CREATE TABLE {backup_table} AS SELECT * FROM patients")
                connection.commit()
                print(f"✅ 现有数据已备份到表: {backup_table}")
                
                # 显示现有数据的诊所分布
                cursor.execute("SELECT clinic_name, COUNT(*) as count FROM patients GROUP BY clinic_name ORDER BY count DESC")
                clinic_distribution = cursor.fetchall()
                print("📋 现有数据诊所分布:")
                for clinic_name, count in clinic_distribution:
                    print(f"  {clinic_name}: {count} 人")
            
            return existing_count
            
    except Exception as e:
        print(f"❌ 备份数据失败: {e}")
        connection.rollback()
        return 0

def ensure_patients_table(connection):
    """确保patients表存在，如果不存在则创建"""
    try:
        with connection.cursor() as cursor:
            # 检查表是否存在
            cursor.execute("SHOW TABLES LIKE 'patients'")
            table_exists = cursor.fetchone()
            
            if not table_exists:
                print("📝 patients表不存在，正在创建...")
                create_table_sql = """
                CREATE TABLE patients (
                    patient_id INT AUTO_INCREMENT PRIMARY KEY,
                    case_number VARCHAR(50) UNIQUE NOT NULL,
                    patient_name VARCHAR(100),
                    patient_phone VARCHAR(20),
                    gender VARCHAR(10),
                    age INT,
                    clinic_name VARCHAR(100) NOT NULL,
                    diagnosis JSON,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    INDEX idx_case_number (case_number),
                    INDEX idx_clinic_name (clinic_name),
                    INDEX idx_patient_name (patient_name)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
                """
                cursor.execute(create_table_sql)
                connection.commit()
                print("✅ patients表创建成功")
            else:
                print("✅ patients表已存在")
                
    except Exception as e:
        print(f"❌ 创建patients表失败: {e}")
        connection.rollback()

def safe_import_clinic_patients(connection, clinic_name, json_file_path):
    """安全导入单个门诊的患者数据"""
    try:
        if not os.path.exists(json_file_path):
            print(f"⚠️  JSON文件不存在: {json_file_path}")
            return 0, 0, 0
        
        with open(json_file_path, 'r', encoding='utf-8') as f:
            patients_data = json.load(f)
        
        if not isinstance(patients_data, list):
            print(f"⚠️  JSON文件格式错误: {json_file_path}")
            return 0, 0, 0
        
        added_count = 0
        updated_count = 0
        skipped_count = 0
        
        with connection.cursor() as cursor:
            for patient in patients_data:
                try:
                    # 提取患者信息（使用中文字段名）
                    case_number = patient.get('病历号', '')
                    patient_name = patient.get('姓名', '')
                    patient_phone = ''  # JSON中没有电话字段
                    gender = patient.get('性别', '')
                    age = patient.get('年龄')
                    diagnosis = {
                        '医生诊断': patient.get('医生诊断', ''),
                        '上次就诊诊断': patient.get('上次就诊诊断', ''),
                        '漏诊项': patient.get('漏诊项', ''),
                        '缺失牙': patient.get('缺失牙', []),
                        '牙槽骨吸收': patient.get('牙槽骨吸收', ''),
                        '恒牙萌出空间不足': patient.get('恒牙萌出空间不足', '')
                    }
                    
                    if not case_number:
                        skipped_count += 1
                        continue
                    
                    # 检查患者是否已存在
                    cursor.execute("SELECT patient_id FROM patients WHERE case_number = %s", (case_number,))
                    existing_patient = cursor.fetchone()
                    
                    if existing_patient:
                        # 患者已存在，更新信息（保留created_at）
                        update_sql = """
                        UPDATE patients SET
                            patient_name = %s,
                            patient_phone = %s,
                            gender = %s,
                            age = %s,
                            clinic_name = %s,
                            diagnosis = %s,
                            updated_at = CURRENT_TIMESTAMP
                        WHERE case_number = %s
                        """
                        
                        cursor.execute(update_sql, (
                            patient_name,
                            patient_phone,
                            gender,
                            age,
                            clinic_name,
                            json.dumps(diagnosis, ensure_ascii=False),
                            case_number
                        ))
                        updated_count += 1
                        
                    else:
                        # 患者不存在，插入新记录
                        insert_sql = """
                        INSERT INTO patients (case_number, patient_name, patient_phone, gender, age, clinic_name, diagnosis)
                        VALUES (%s, %s, %s, %s, %s, %s, %s)
                        """
                        
                        cursor.execute(insert_sql, (
                            case_number,
                            patient_name,
                            patient_phone,
                            gender,
                            age,
                            clinic_name,
                            json.dumps(diagnosis, ensure_ascii=False)
                        ))
                        added_count += 1
                    
                except Exception as e:
                    print(f"⚠️  处理患者 {case_number} 失败: {e}")
                    skipped_count += 1
                    continue
        
        connection.commit()
        print(f"✅ {clinic_name}: 新增 {added_count} 个患者，更新 {updated_count} 个患者，跳过 {skipped_count} 个患者")
        return added_count, updated_count, skipped_count
        
    except Exception as e:
        print(f"❌ 导入 {clinic_name} 患者数据失败: {e}")
        connection.rollback()
        return 0, 0, 0

def verify_import_results(connection):
    """验证导入结果"""
    try:
        with connection.cursor() as cursor:
            # 统计总患者数
            cursor.execute("SELECT COUNT(*) as total FROM patients")
            total_patients = cursor.fetchone()[0]
            
            # 统计各诊所患者分布
            cursor.execute("SELECT clinic_name, COUNT(*) as count FROM patients GROUP BY clinic_name ORDER BY count DESC")
            clinic_counts = cursor.fetchall()
            
            # 检查是否有重复的病历号
            cursor.execute("SELECT case_number, COUNT(*) as count FROM patients GROUP BY case_number HAVING count > 1")
            duplicates = cursor.fetchall()
            
            print(f"\n🎉 导入完成！")
            print(f"📊 总患者数: {total_patients}")
            print(f"📋 各门诊患者分布:")
            for clinic_name, count in clinic_counts:
                print(f"   {clinic_name}: {count} 人")
            
            if duplicates:
                print(f"⚠️  发现重复病历号: {len(duplicates)} 个")
                for case_number, count in duplicates:
                    print(f"   {case_number}: {count} 次")
            else:
                print("✅ 无重复病历号")
                
    except Exception as e:
        print(f"❌ 验证结果失败: {e}")

def main():
    """主函数"""
    print("🚀 开始安全导入患者数据...")
    print("⚠️  注意：此脚本不会删除任何现有数据！")
    
    # 连接数据库
    connection = connect_database()
    if not connection:
        return
    
    try:
        # 备份现有数据
        existing_count = backup_existing_data(connection)
        
        # 确保patients表存在
        ensure_patients_table(connection)
        
        # 定义门诊和对应的JSON文件
        clinics = [
            ('学前街门诊', 'data/patients/clinics/学前街门诊.json'),
            ('大丰门诊', 'data/patients/clinics/大丰门诊.json'),
            ('东亭门诊', 'data/patients/clinics/东亭门诊.json'),
            ('河埒门诊', 'data/patients/clinics/河埒门诊.json'),
            ('红豆门诊', 'data/patients/clinics/红豆门诊.json'),
            ('惠山门诊', 'data/patients/clinics/惠山门诊.json'),
            ('马山门诊', 'data/patients/clinics/马山门诊.json'),
            ('通善口腔医院', 'data/patients/clinics/通善口腔医院.json'),
            ('新吴门诊', 'data/patients/clinics/新吴门诊.json')
        ]
        
        total_added = 0
        total_updated = 0
        total_skipped = 0
        
        # 导入每个门诊的患者数据
        for clinic_name, json_file in clinics:
            print(f"\n📋 正在处理 {clinic_name}...")
            added, updated, skipped = safe_import_clinic_patients(connection, clinic_name, json_file)
            total_added += added
            total_updated += updated
            total_skipped += skipped
        
        # 验证导入结果
        verify_import_results(connection)
        
        print(f"\n📈 导入统计:")
        print(f"  新增患者: {total_added}")
        print(f"  更新患者: {total_updated}")
        print(f"  跳过患者: {total_skipped}")
        print(f"  原有患者: {existing_count}")
        
        if existing_count > 0:
            print(f"\n✅ 所有原有数据已保留！")
            print(f"📋 数据已备份到临时表中")
        
    except Exception as e:
        print(f"❌ 导入过程出错: {e}")
        connection.rollback()
    
    finally:
        connection.close()
        print("\n✅ 数据库连接已关闭")

if __name__ == "__main__":
    main() 
