#!/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.patient_service import load_clinic_patients, get_patient_by_id, load_callback_script, get_clinic_info
from services.callback_service import get_callback_records
from config import get_clinic_info

patient_bp = Blueprint('patient', __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

@patient_bp.route('/admin/dashboard')
@require_login
def admin_dashboard():
    """管理员仪表板 - 门诊索引页"""
    user = session['user']

    # 检查管理员权限
    if user.get('role') != 'admin':
        flash('权限不足', 'error')
        return redirect(url_for('auth.login'))

    return render_template('admin_dashboard.html', session_data=user, user=user)





@patient_bp.route('/clinic/<clinic_id>/patients')
@require_login
def clinic_patients(clinic_id):
    """门诊患者列表页面"""
    user = session['user']

    # 检查权限
    if not check_clinic_access(user, clinic_id):
        flash('您没有权限访问该门诊', 'error')
        if user.get('role') == 'admin':
            return redirect(url_for('patient.admin_dashboard'))
        else:
            return redirect(url_for('auth.login'))

    # 获取门诊信息
    clinic_info = get_clinic_info(clinic_id)
    clinic_name = clinic_info['clinic_name']

    # 加载患者数据
    patients, doctors = load_clinic_patients(clinic_id)

    # 所有用户都使用原版的患者列表模板
    return render_template('patient_list.html',
                         session_data=user,
                         clinic_id=clinic_id,
                         clinic_name=clinic_name,
                         patients=patients,
                         doctors=doctors)

@patient_bp.route('/patient_profiles/<clinic_id>/index.html')
@require_login
def patient_list_original(clinic_id):
    """患者列表页面（原版路由，普通用户登录后的首页）"""
    user = session['user']

    # 检查权限
    if not check_clinic_access(user, clinic_id):
        flash('您没有权限访问该门诊', 'error')
        if user.get('role') == 'admin':
            return redirect(url_for('patient.admin_dashboard'))
        else:
            return redirect(url_for('auth.login'))

    # 获取门诊信息
    clinic_info = get_clinic_info(clinic_id)
    clinic_name = clinic_info['clinic_name']

    # 加载患者数据
    patients, doctors = load_clinic_patients(clinic_id)

    # 所有用户都使用原版的患者列表模板
    return render_template('patient_list.html',
                         session_data=user,
                         clinic_id=clinic_id,
                         clinic_name=clinic_name,
                         patients=patients,
                         doctors=doctors)

@patient_bp.route('/clinic/<clinic_id>/patient/<patient_id>')
@require_login
def patient_detail(clinic_id, patient_id):
    """患者详情页面"""
    user = session['user']
    
    # 检查权限
    if not check_clinic_access(user, clinic_id):
        flash('您没有权限访问该门诊', 'error')
        return redirect(url_for('patient.clinic_patients', clinic_id=clinic_id))
    
    # 获取患者信息
    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))
    
    # 获取门诊信息
    clinic_info = get_clinic_info(clinic_id)
    clinic_name = clinic_info['clinic_name']
    
    # 加载回访话术
    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=clinic_name,
                         callback_script=callback_script,
                         callback_records=callback_records,
                         user=user)

@patient_bp.route('/api/patients/<clinic_id>')
@require_login
def api_get_patients(clinic_id):
    """获取门诊患者列表API"""
    user = session['user']
    
    # 检查权限
    if not check_clinic_access(user, clinic_id):
        return jsonify({'success': False, 'message': '权限不足'}), 403
    
    try:
        patients, _ = load_clinic_patients(clinic_id)
        return jsonify({
            'success': True,
            'data': patients,
            'count': len(patients)
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取患者列表失败: {str(e)}'
        }), 500

@patient_bp.route('/api/patient/<clinic_id>/<patient_id>')
@require_login
def api_get_patient(clinic_id, patient_id):
    """获取患者详情API"""
    user = session['user']
    
    # 检查权限
    if not check_clinic_access(user, clinic_id):
        return jsonify({'success': False, 'message': '权限不足'}), 403
    
    try:
        patient = get_patient_by_id(clinic_id, patient_id)
        if not patient:
            return jsonify({'success': False, 'message': '患者不存在'}), 404
        
        return jsonify({
            'success': True,
            'data': patient
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'获取患者信息失败: {str(e)}'
        }), 500
