#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API路由
通用API接口
"""

from flask import Blueprint, jsonify, session, request, send_file, Response
from datetime import datetime
import os
import io

api_bp = Blueprint('api', __name__)

def require_login(f):
    """登录装饰器"""
    from functools import wraps
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user' not in session:
            return jsonify({'success': False, 'message': '未登录'}), 401
        return f(*args, **kwargs)
    return decorated_function

@api_bp.route('/health', methods=['GET'])
def health_check():
    """健康检查API"""
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat(),
        'version': '1.0.0'
    })

@api_bp.route('/export-data', methods=['GET'])
@require_login
def export_data():
    """数据导出API"""
    try:
        user = session['user']

        # 检查管理员权限
        if user.get('role') != 'admin':
            return jsonify({
                'success': False,
                'message': '权限不足，只有管理员可以导出数据'
            }), 403

        # 导入导出模块
        try:
            from database.scripts.export_data import DataExporter
        except ImportError:
            return jsonify({
                'success': False,
                'message': '导出模块未找到'
            }), 500

        # 生成Excel文件到内存
        exporter = DataExporter()
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_filename = f"回访记录导出_{timestamp}.xlsx"

        print(f"开始生成Excel文件: {output_filename}")

        # 导出数据到内存缓冲区
        try:
            excel_buffer = exporter.export_to_memory()
            print(f"Excel文件生成完成，大小: {len(excel_buffer)} 字节")
        except Exception as export_error:
            print(f"导出过程中出错: {export_error}")
            import traceback
            traceback.print_exc()
            return jsonify({'success': False, 'message': f'导出过程出错: {str(export_error)}'}), 500

        # 处理中文文件名编码问题
        # 使用 RFC 5987 标准的编码方式
        import urllib.parse
        encoded_filename = urllib.parse.quote(output_filename.encode('utf-8'))

        # 直接返回二进制文件流
        return Response(
            excel_buffer,
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            headers={
                'Content-Disposition': f'attachment; filename*=UTF-8\'\'{encoded_filename}',
                'Content-Length': str(len(excel_buffer))
            }
        )

    except Exception as e:
        print(f"❌ 数据导出失败: {e}")
        return jsonify({
            'success': False,
            'message': f'导出失败: {str(e)}'
        }), 500

@api_bp.route('/system-info', methods=['GET'])
@require_login
def system_info():
    """系统信息API"""
    try:
        user = session['user']
        
        # 检查管理员权限
        if user.get('role') != 'admin':
            return jsonify({
                'success': False,
                'message': '权限不足'
            }), 403
        
        # 获取系统信息
        from database.models import CallbackRecord, Patient, Clinic
        
        # 统计数据
        total_records = CallbackRecord.query.count()
        total_patients = Patient.query.count()
        total_clinics = Clinic.query.count()
        
        return jsonify({
            'success': True,
            'data': {
                'total_callback_records': total_records,
                'total_patients': total_patients,
                'total_clinics': total_clinics,
                'system_time': datetime.now().isoformat(),
                'database_status': 'connected'
            }
        })
        
    except Exception as e:
        print(f"❌ 获取系统信息失败: {e}")
        return jsonify({
            'success': False,
            'message': f'获取系统信息失败: {str(e)}'
        }), 500


