#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
回访记录数据库管理工具
功能：查看、搜索、导出、统计回访记录
"""

import sqlite3
import json
import csv
from datetime import datetime
import os

class CallbackRecordViewer:
    def __init__(self, db_path="callback_records.db"):
        self.db_path = db_path
        self.ensure_database_exists()
    
    def ensure_database_exists(self):
        """确保数据库文件存在"""
        if not os.path.exists(self.db_path):
            print(f"❌ 数据库文件不存在: {self.db_path}")
            return False
        return True
    
    def get_all_records(self):
        """获取所有回访记录"""
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                cursor.execute('''
                    SELECT record_id, case_number, callback_methods, callback_record, 
                           operator, create_time
                    FROM callback_records
                    ORDER BY create_time DESC
                ''')
                return cursor.fetchall()
        except Exception as e:
            print(f"❌ 获取记录失败: {e}")
            return []
    
    def search_records(self, keyword="", case_number="", operator=""):
        """搜索回访记录"""
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                
                conditions = []
                params = []
                
                if keyword:
                    conditions.append("callback_record LIKE ?")
                    params.append(f"%{keyword}%")
                
                if case_number:
                    conditions.append("case_number LIKE ?")
                    params.append(f"%{case_number}%")
                
                if operator:
                    conditions.append("operator LIKE ?")
                    params.append(f"%{operator}%")
                
                where_clause = " AND ".join(conditions) if conditions else "1=1"
                
                sql = f'''
                    SELECT record_id, case_number, callback_methods, callback_record, 
                           operator, create_time
                    FROM callback_records
                    WHERE {where_clause}
                    ORDER BY create_time DESC
                '''
                
                cursor.execute(sql, params)
                return cursor.fetchall()
        except Exception as e:
            print(f"❌ 搜索失败: {e}")
            return []
    
    def get_statistics(self):
        """获取统计信息"""
        try:
            with sqlite3.connect(self.db_path) as conn:
                cursor = conn.cursor()
                
                stats = {}
                
                # 总记录数
                cursor.execute("SELECT COUNT(*) FROM callback_records")
                stats['total_records'] = cursor.fetchone()[0]
                
                # 今日记录数
                cursor.execute('''
                    SELECT COUNT(*) FROM callback_records 
                    WHERE DATE(create_time) = DATE('now')
                ''')
                stats['today_records'] = cursor.fetchone()[0]
                
                # 本周记录数
                cursor.execute('''
                    SELECT COUNT(*) FROM callback_records 
                    WHERE DATE(create_time) >= DATE('now', '-7 days')
                ''')
                stats['week_records'] = cursor.fetchone()[0]
                
                # 按病历号统计
                cursor.execute('''
                    SELECT case_number, COUNT(*) as count
                    FROM callback_records
                    GROUP BY case_number
                    ORDER BY count DESC
                ''')
                stats['case_stats'] = cursor.fetchall()
                
                # 按操作员统计
                cursor.execute('''
                    SELECT operator, COUNT(*) as count
                    FROM callback_records
                    GROUP BY operator
                    ORDER BY count DESC
                ''')
                stats['operator_stats'] = cursor.fetchall()
                
                # 按回访方式统计
                method_stats = {}
                cursor.execute("SELECT callback_methods FROM callback_records")
                for row in cursor.fetchall():
                    try:
                        methods = json.loads(row[0])
                        for method in methods:
                            method_stats[method] = method_stats.get(method, 0) + 1
                    except:
                        pass
                stats['method_stats'] = method_stats
                
                return stats
        except Exception as e:
            print(f"❌ 获取统计信息失败: {e}")
            return {}
    
    def format_record(self, record):
        """格式化单条记录显示"""
        record_id, case_number, callback_methods_json, callback_record, operator, create_time = record
        
        # 解析回访方式
        try:
            callback_methods = json.loads(callback_methods_json)
            methods_str = ", ".join(callback_methods)
        except:
            methods_str = callback_methods_json
        
        # 格式化时间
        try:
            if create_time:
                create_time_obj = datetime.fromisoformat(create_time.replace('Z', '+00:00'))
                time_str = create_time_obj.strftime('%Y-%m-%d %H:%M:%S')
            else:
                time_str = "未知时间"
        except:
            time_str = str(create_time)
        
        return {
            'id': record_id,
            'case_number': case_number,
            'methods': methods_str,
            'operator': operator,
            'time': time_str,
            'content': callback_record
        }
    
    def display_records(self, records, title="回访记录"):
        """显示记录列表"""
        if not records:
            print("📝 没有找到匹配的记录")
            return
        
        print(f"📊 {title} (共 {len(records)} 条)")
        print("=" * 80)
        
        for i, record in enumerate(records, 1):
            formatted = self.format_record(record)
            
            print(f"📋 记录 #{i} (ID: {formatted['id']})")
            print(f"   病历号: {formatted['case_number']}")
            print(f"   回访方式: {formatted['methods']}")
            print(f"   操作员: {formatted['operator']}")
            print(f"   创建时间: {formatted['time']}")
            print(f"   回访内容:")
            
            # 格式化显示回访内容
            content_lines = formatted['content'].split('\n')
            for line in content_lines:
                if line.strip():
                    print(f"     {line}")
            
            print("-" * 60)
    
    def display_statistics(self):
        """显示统计信息"""
        stats = self.get_statistics()
        if not stats:
            return
        
        print("\n📈 数据库统计信息")
        print("=" * 50)
        
        print(f"📊 总体统计:")
        print(f"   总记录数: {stats['total_records']}")
        print(f"   今日记录: {stats['today_records']}")
        print(f"   本周记录: {stats['week_records']}")
        print(f"   涉及患者: {len(stats['case_stats'])} 人")
        
        if stats['case_stats']:
            print(f"\n👥 患者记录统计 (前10名):")
            for case_number, count in stats['case_stats'][:10]:
                print(f"   {case_number}: {count} 条")
        
        if stats['operator_stats']:
            print(f"\n👨‍💼 操作员统计:")
            for operator, count in stats['operator_stats']:
                print(f"   {operator}: {count} 条")
        
        if stats['method_stats']:
            print(f"\n📞 回访方式统计:")
            for method, count in stats['method_stats'].items():
                print(f"   {method}: {count} 次")
    
    def export_to_csv(self, filename="callback_records_export.csv"):
        """导出记录到CSV文件"""
        records = self.get_all_records()
        if not records:
            print("❌ 没有数据可导出")
            return
        
        try:
            with open(filename, 'w', newline='', encoding='utf-8-sig') as csvfile:
                writer = csv.writer(csvfile)
                
                # 写入表头
                writer.writerow(['记录ID', '病历号', '回访方式', '回访内容', '操作员', '创建时间'])
                
                # 写入数据
                for record in records:
                    formatted = self.format_record(record)
                    writer.writerow([
                        formatted['id'],
                        formatted['case_number'],
                        formatted['methods'],
                        formatted['content'].replace('\n', ' | '),  # 将换行符替换为分隔符
                        formatted['operator'],
                        formatted['time']
                    ])
            
            print(f"✅ 数据已导出到: {filename}")
            print(f"📄 共导出 {len(records)} 条记录")
            
        except Exception as e:
            print(f"❌ 导出失败: {e}")

def find_all_databases():
    """查找所有数据库文件"""
    db_files = []
    
    # 当前目录
    for file in os.listdir('.'):
        if file.endswith('.db'):
            db_files.append(f"./{file}")
    
    # patient_profiles目录
    if os.path.exists('patient_profiles'):
        for file in os.listdir('patient_profiles'):
            if file.endswith('.db'):
                db_files.append(f"./patient_profiles/{file}")
    
    return db_files

def main():
    """主函数 - 交互式菜单"""
    print("🗄️  回访记录数据库管理工具")
    print("=" * 50)
    
    # 查找数据库文件
    db_files = find_all_databases()
    
    if not db_files:
        print("❌ 未找到任何数据库文件")
        return
    
    # 选择数据库
    if len(db_files) == 1:
        selected_db = db_files[0]
        print(f"📖 使用数据库: {selected_db}")
    else:
        print(f"📁 找到 {len(db_files)} 个数据库文件:")
        for i, db_file in enumerate(db_files, 1):
            file_size = os.path.getsize(db_file)
            print(f"   {i}. {db_file} ({file_size} bytes)")
        
        try:
            choice = input(f"\n请选择数据库 (1-{len(db_files)}): ").strip()
            if choice.isdigit():
                index = int(choice) - 1
                if 0 <= index < len(db_files):
                    selected_db = db_files[index]
                else:
                    print("❌ 无效的选择")
                    return
            else:
                print("❌ 请输入数字")
                return
        except KeyboardInterrupt:
            print("\n👋 已取消")
            return
    
    # 初始化查看器
    viewer = CallbackRecordViewer(selected_db)
    
    # 交互式菜单
    while True:
        print(f"\n📋 数据库管理菜单 ({selected_db})")
        print("-" * 40)
        print("1. 查看所有记录")
        print("2. 搜索记录")
        print("3. 查看统计信息")
        print("4. 导出到CSV")
        print("5. 按病历号查看")
        print("6. 按操作员查看")
        print("0. 退出")
        
        try:
            choice = input("\n请选择操作 (0-6): ").strip()
            
            if choice == '0':
                print("👋 再见！")
                break
            elif choice == '1':
                records = viewer.get_all_records()
                viewer.display_records(records, "所有回访记录")
            elif choice == '2':
                print("\n🔍 搜索条件 (直接回车跳过):")
                keyword = input("关键词 (搜索回访内容): ").strip()
                case_number = input("病历号: ").strip()
                operator = input("操作员: ").strip()
                
                records = viewer.search_records(keyword, case_number, operator)
                viewer.display_records(records, "搜索结果")
            elif choice == '3':
                viewer.display_statistics()
            elif choice == '4':
                filename = input("导出文件名 (默认: callback_records_export.csv): ").strip()
                if not filename:
                    filename = "callback_records_export.csv"
                viewer.export_to_csv(filename)
            elif choice == '5':
                case_number = input("请输入病历号: ").strip()
                if case_number:
                    records = viewer.search_records(case_number=case_number)
                    viewer.display_records(records, f"病历号 {case_number} 的记录")
            elif choice == '6':
                operator = input("请输入操作员名称: ").strip()
                if operator:
                    records = viewer.search_records(operator=operator)
                    viewer.display_records(records, f"操作员 {operator} 的记录")
            else:
                print("❌ 无效的选择，请重新输入")
                
        except KeyboardInterrupt:
            print("\n👋 已退出")
            break
        except Exception as e:
            print(f"❌ 操作失败: {e}")

if __name__ == "__main__":
    main() 