#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
回访相关路由
"""

from flask import Blueprint, render_template, session, redirect, url_for, flash, request, jsonify
from services.auth_service import check_clinic_access
from services.callback_service import save_callback_record, get_callback_records, get_clinic_callback_status
from services.patient_service import get_patient_by_id, load_callback_script
from config import get_clinic_info
import os
import json

callback_bp = Blueprint('callback', __name__)

def require_login(f):
    """登录装饰器"""
    from functools import wraps
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user' not in session:
            flash('请先登录', 'error')
            return redirect(url_for('auth.login'))
        return f(*args, **kwargs)
    return decorated_function

@callback_bp.route('/callback/<clinic_id>/<patient_id>')
@require_login
def callback_form(clinic_id, patient_id):
    """回访表单页面"""
    user = session['user']
    
    # 检查权限
    if not check_clinic_access(user, clinic_id):
        flash('您没有权限访问该门诊', 'error')
        return redirect(url_for('auth.login'))
    
    # 获取患者信息
    patient = get_patient_by_id(clinic_id, patient_id)
    if not patient:
        flash('未找到该患者信息', 'error')
        return redirect(url_for('patient.clinic_patients', clinic_id=clinic_id))
    
    # 加载回访话术
    callback_script = load_callback_script(clinic_id, patient_id)
    
    # 加载历史回访记录
    callback_records = get_callback_records(patient_id)
    
    return render_template('patient_detail.html',
                         patient=patient,
                         clinic_id=clinic_id,
                         clinic_name=get_clinic_info(clinic_id)['clinic_name'],
                         callback_script=callback_script,
                         callback_records=callback_records,
                         user=user)

@callback_bp.route('/api/save-callback', methods=['POST'])
@require_login
def api_save_callback():
    """保存回访记录API"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({'success': False, 'message': '无效的请求数据'}), 400
        
        # 获取当前用户
        current_user = session.get('real_name', session.get('username', '未知用户'))
        
        # 保存回访记录
        result = save_callback_record(data, current_user)
        
        if result['success']:
            return jsonify(result)
        else:
            return jsonify(result), 500
            
    except Exception as e:
        print(f"❌ 保存回访记录API失败: {e}")
        return jsonify({
            'success': False,
            'message': f'保存失败: {str(e)}'
        }), 500

@callback_bp.route('/api/callback-records/<case_number>')
@require_login
def api_get_callback_records(case_number):
    """获取回访记录API"""
    try:
        records = get_callback_records(case_number)
        return jsonify({
            'success': True,
            'data': records,
            'count': len(records),
            'storage': 'database'
        })
    except Exception as e:
        print(f"❌ 获取回访记录失败: {e}")
        return jsonify({
            'success': False,
            'message': f'获取失败: {str(e)}'
        }), 500

@callback_bp.route('/api/callback-status/<clinic_id>')
@require_login
def api_get_callback_status(clinic_id):
    """获取门诊回访状态API"""
    user = session['user']
    
    # 检查权限
    if not check_clinic_access(user, clinic_id):
        return jsonify({'success': False, 'message': '权限不足'}), 403
    
    try:
        status_dict = get_clinic_callback_status(clinic_id)
        return jsonify({
            'success': True,
            'data': status_dict
        })
    except Exception as e:
        print(f"❌ 获取回访状态失败: {e}")
        return jsonify({
            'success': False,
            'message': f'获取失败: {str(e)}'
        }), 500

@callback_bp.route('/api/generate-callback-script', methods=['POST'])
@require_login
def api_generate_callback_script():
    """生成AI回访话术API"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({'success': False, 'message': '无效的请求数据'}), 400

        clinic_id = data.get('clinic_id')
        patient_id = data.get('patient_id')

        if not clinic_id or not patient_id:
            return jsonify({'success': False, 'message': '缺少必要参数'}), 400

        user = session['user']

        # 检查权限
        if not check_clinic_access(user, clinic_id):
            return jsonify({'success': False, 'message': '权限不足'}), 403

        # 获取患者信息
        patient = get_patient_by_id(clinic_id, patient_id)
        if not patient:
            return jsonify({'success': False, 'message': '患者不存在'}), 404

        # 这里可以调用Dify API生成回访话术
        # 目前先返回一个模拟的话术
        mock_script = f"""
        <div class="mb-6 p-4 bg-blue-50 border-l-4 border-blue-500 rounded-lg">
            <h4 class="font-bold text-blue-700 mb-3 flex items-center">
                <i class="fas fa-comment mr-2"></i>问候语
            </h4>
            <div class="text-gray-700 leading-relaxed">
                <div class="mb-1">• 您好，{patient.get('姓名', '患者')}，我是{get_clinic_info(clinic_id)['clinic_name']}的回访专员。</div>
                <div class="mb-1">• 今天给您打电话是想了解一下您的恢复情况。</div>
            </div>
        </div>

        <div class="mb-6 p-4 bg-green-50 border-l-4 border-green-500 rounded-lg">
            <h4 class="font-bold text-green-700 mb-3 flex items-center">
                <i class="fas fa-comment mr-2"></i>治疗效果询问
            </h4>
            <div class="text-gray-700 leading-relaxed">
                <div class="mb-1">• 您现在感觉怎么样？有没有什么不适的地方？</div>
                <div class="mb-1">• 治疗后的效果如何？是否达到了您的预期？</div>
            </div>
        </div>

        <div class="mb-6 p-4 bg-yellow-50 border-l-4 border-yellow-500 rounded-lg">
            <h4 class="font-bold text-yellow-700 mb-3 flex items-center">
                <i class="fas fa-comment mr-2"></i>护理建议
            </h4>
            <div class="text-gray-700 leading-relaxed">
                <div class="mb-1">• 请注意保持口腔清洁，按时刷牙漱口。</div>
                <div class="mb-1">• 如有任何不适，请及时联系我们。</div>
            </div>
        </div>

        <div class="mb-6 p-4 bg-purple-50 border-l-4 border-purple-500 rounded-lg">
            <h4 class="font-bold text-purple-700 mb-3 flex items-center">
                <i class="fas fa-comment mr-2"></i>结束语
            </h4>
            <div class="text-gray-700 leading-relaxed">
                <div class="mb-1">• 感谢您选择我们的服务，祝您身体健康！</div>
                <div class="mb-1">• 如有任何问题，随时可以联系我们。</div>
            </div>
        </div>
        """

        # 保存生成的话术到文件（模拟）
        # 实际应用中应该保存到数据库或调用真实的AI API

        return jsonify({
            'success': True,
            'message': '回访话术生成成功',
            'script': mock_script.strip()
        })

    except Exception as e:
        print(f"❌ 生成回访话术失败: {e}")
        return jsonify({
            'success': False,
            'message': f'生成失败: {str(e)}'
        }), 500
