#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
回访服务层
处理回访记录相关的业务逻辑
"""

from datetime import datetime
from database.models import db, CallbackRecord

# 内存存储最新的回访结果，用于状态API
callback_results_cache = {}

def save_callback_record(data, current_user):
    """保存回访记录"""
    try:
        # 构建回访记录内容
        callback_record = f"""
回访时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
回访方式: {', '.join(data['callbackMethods'])}
回访结果: {data['callbackResult']}
操作员: {current_user}
"""
        
        # 如果有下次预约时间，添加到记录中
        if data.get('nextAppointmentTime'):
            callback_record += f"\n下次预约时间: {data['nextAppointmentTime']}"
        
        # 如果有失败原因，添加到记录中
        if data.get('failureReason'):
            callback_record += f"\n失败原因: {data['failureReason']}"
        
        # 如果有放弃原因，添加到记录中
        if data.get('abandonReason'):
            callback_record += f"\n放弃原因: {data['abandonReason']}"
        
        # 如果有AI反馈，添加到记录中
        if data.get('aiFeedbackType'):
            callback_record += f"\nAI反馈类型: {data['aiFeedbackType']}"
        
        result = data['callbackResult']
        
        # 使用SQLAlchemy ORM保存记录
        record = CallbackRecord(
            case_number=data['caseNumber'],
            callback_methods=data['callbackMethods'],
            callback_record=callback_record,  # 使用构建好的回访记录内容
            callback_result=result,  # 传递回访结果
            next_appointment_time=data.get('nextAppointmentTime'),
            failure_reason=data.get('failureReason'),
            abandon_reason=data.get('abandonReason'),
            ai_feedback_type=data.get('aiFeedbackType'),
            failure_reason_note=data.get('failureReasonNote'),
            abandon_reason_note=data.get('abandonReasonNote'),
            ai_feedback_note=data.get('aiFeedbackNote'),
            callback_status=data.get('callbackStatus', '已回访'),
            operator=current_user  # 使用从session获取的真实用户名
        )
        
        db.session.add(record)
        db.session.commit()
        record_id = record.record_id
        
        # 更新内存缓存
        callback_results_cache[data['caseNumber']] = {
            'callback_result': result,
            'create_time': datetime.now()
        }
        
        return {
            'success': True,
            'id': record_id,
            'message': '保存成功',
            'timestamp': datetime.now().isoformat(),
            'storage': 'database',
            'operator': current_user
        }
        
    except Exception as e:
        db.session.rollback()
        print(f"❌ 保存回访记录失败: {e}")
        return {
            'success': False,
            'message': f'保存失败: {str(e)}'
        }

def get_callback_records(case_number):
    """获取患者的回访记录"""
    try:
        # 使用SQLAlchemy ORM查询
        records = CallbackRecord.query.filter_by(case_number=case_number).order_by(CallbackRecord.create_time.desc()).all()
        return [record.to_dict() for record in records]
    except Exception as e:
        print(f"❌ 获取回访记录失败: {e}")
        return []

def get_clinic_callback_status(clinic_id):
    """获取指定门诊所有患者的回访状态"""
    try:
        # 使用SQLAlchemy ORM查询所有回访记录
        all_records = CallbackRecord.query.order_by(CallbackRecord.create_time.desc()).all()
        
        # 按病历号分组，获取最新的回访状态
        status_map = {}
        for record in all_records:
            case_number = record.case_number
            # 如果该病历号还没有记录，或者当前记录更新，则更新状态
            if case_number not in status_map:
                status_map[case_number] = {
                    'case_number': case_number,
                    'callback_status': '已回访',
                    'callback_result': record.callback_result,  # 直接使用存储的结果
                    'create_time': record.create_time.isoformat() if record.create_time else None
                }
            else:
                # 比较时间，保留最新的记录
                current_time = record.create_time
                existing_time = status_map[case_number]['create_time']
                if current_time and existing_time:
                    try:
                        if isinstance(existing_time, str):
                            existing_time = datetime.fromisoformat(existing_time.replace('Z', '+00:00'))
                        if current_time > existing_time:
                            status_map[case_number] = {
                                'case_number': case_number,
                                'callback_status': '已回访',
                                'callback_result': record.callback_result,  # 直接使用存储的结果
                                'create_time': current_time.isoformat() if current_time else None
                            }
                    except Exception as e:
                        print(f"时间比较错误: {e}")
        
        # 转换为以病历号为键的字典格式，方便前端查找
        status_dict = {}
        for status in status_map.values():
            status_dict[status['case_number']] = status

        return status_dict
        
    except Exception as e:
        print(f"❌ 获取回访状态失败: {e}")
        return {}
