#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
用户认证系统
提供登录验证、session管理和权限检查功能
"""

import os
import json
import hashlib
import secrets
import time
from flask import Flask, request, jsonify, session, redirect, render_template_string, render_template, send_file, url_for
from flask_cors import CORS
from datetime import datetime, timedelta

# 尝试导入回访记录相关模块
try:
    from callback_record_mysql import MySQLCallbackRecordManager, CallbackRecord
    from database_config import DatabaseConfig
    CALLBACK_AVAILABLE = True
except ImportError as e:
    print(f"⚠️  回访记录模块导入失败: {e}")
    CALLBACK_AVAILABLE = False

# 尝试导入clinic_config，如果失败则使用默认配置
try:
    from clinic_config import DEFAULT_USERS, get_user_by_username, get_clinic_info
    print("✅ 成功导入clinic_config配置")
except ImportError as e:
    print(f"⚠️  无法导入clinic_config: {e}")
    print("使用默认用户配置...")
    
    # 最小默认用户配置（仅作为备用）
    DEFAULT_USERS = [
        # 管理员
        {
            'username': 'admin',
            'password': 'admin123',
            'role': 'admin',
            'clinic_id': 'admin',
            'real_name': '系统管理员',
            'clinic_name': '总部'
        }
    ]
    
    def get_user_by_username(username):
        """根据用户名获取用户信息"""
        for user in DEFAULT_USERS:
            if user['username'] == username:
                return user
        return None
    
    def get_clinic_info(clinic_id):
        """获取门诊信息"""
        return {'name': '未知门诊'}

def load_clinic_patients(clinic_id):
    """加载指定门诊的患者数据"""
    try:
        # 获取门诊信息
        clinic_info = get_clinic_info(clinic_id)
        if not clinic_info:
            print(f"❌ 门诊ID不存在: {clinic_id}")
            return [], []

        # 构建JSON文件路径
        clinic_name_mapping = {
            'clinic_xuexian': '学前街门诊',
            'clinic_dafeng': '大丰门诊',
            'clinic_dongting': '东亭门诊',
            'clinic_helai': '河埒门诊',
            'clinic_hongdou': '红豆门诊',
            'clinic_huishan': '惠山门诊',
            'clinic_mashan': '马山门诊',
            'clinic_hospital': '通善口腔医院',
            'clinic_xinwu': '新吴门诊'
        }

        clinic_name = clinic_name_mapping.get(clinic_id, '未知门诊')

        # 优先尝试使用合并结果.json（包含更完整的数据）
        merged_file = '合并结果.json'
        if os.path.exists(merged_file):
            print(f"📄 使用合并数据文件: {merged_file}")
            with open(merged_file, 'r', encoding='utf-8') as f:
                all_patients = json.load(f)

            # 筛选出属于当前门诊的患者
            patients = []
            for patient in all_patients:
                patient_clinic = patient.get('诊所', '')
                patient_clinic_full = patient.get('最后一次就诊诊所', '')

                # 根据门诊名称匹配患者
                if (clinic_name in patient_clinic_full or
                    (clinic_id == 'clinic_xuexian' and ('学前街' in patient_clinic_full or '学前街' in patient_clinic)) or
                    (clinic_id == 'clinic_dongting' and ('东亭' in patient_clinic_full or '东亭' in patient_clinic)) or
                    (clinic_id == 'clinic_dafeng' and ('大丰' in patient_clinic_full or '大丰' in patient_clinic)) or
                    (clinic_id == 'clinic_huishan' and ('惠山' in patient_clinic_full or '惠山' in patient_clinic)) or
                    (clinic_id == 'clinic_helai' and ('河埒' in patient_clinic_full or '河埒' in patient_clinic)) or
                    (clinic_id == 'clinic_hongdou' and ('红豆' in patient_clinic_full or '红豆' in patient_clinic)) or
                    (clinic_id == 'clinic_mashan' and ('马山' in patient_clinic_full or '马山' in patient_clinic)) or
                    (clinic_id == 'clinic_hospital' and ('通善口腔医院' in patient_clinic_full or '通善总院' in patient_clinic)) or
                    (clinic_id == 'clinic_xinwu' and ('新吴' in patient_clinic_full or '新吴' in patient_clinic))):
                    patients.append(patient)
        else:
            # 回退到使用诊所患者json文件
            json_file = f'诊所患者json/{clinic_name}.json'
            if not os.path.exists(json_file):
                print(f"❌ 患者数据文件不存在: {json_file}")
                return [], []

            with open(json_file, 'r', encoding='utf-8') as f:
                patients = json.load(f)

        # 提取医生列表
        doctors = set()
        for patient in patients:
            doctor = patient.get('最后一次就诊医生')
            if doctor and doctor.strip():
                doctors.add(doctor.strip())

        print(f"✅ 加载 {clinic_name} 患者数据: {len(patients)} 人, {len(doctors)} 位医生")
        return patients, sorted(list(doctors))

    except Exception as e:
        print(f"❌ 加载 {clinic_id} 患者数据失败: {e}")
        return [], []

def load_patient_detail(clinic_id, patient_id):
    """加载指定患者的详细信息"""
    try:
        # 加载门诊的所有患者数据
        patients, _ = load_clinic_patients(clinic_id)

        # 查找指定患者
        patient = None
        for p in patients:
            if p.get('病历号') == patient_id:
                patient = p
                break

        if not patient:
            print(f"❌ 未找到患者: {patient_id}")
            return None

        print(f"✅ 加载患者详情: {patient.get('姓名', '未知')} ({patient_id})")
        return patient

    except Exception as e:
        print(f"❌ 加载患者详情失败: {e}")
        return None

def load_callback_records(patient_id):
    """加载患者的回访记录"""
    try:
        if db_manager:
            # 从数据库获取
            records = db_manager.get_records_by_case_number(patient_id)
            return [record.to_dict() for record in records]
        else:
            # 从临时内存获取
            return temp_callback_records.get(patient_id, [])
    except Exception as e:
        print(f"❌ 加载回访记录失败: {e}")
        return []

def load_callback_script(clinic_id, patient_id):
    """加载患者的回访话术"""
    try:
        # 门诊名称映射
        clinic_name_mapping = {
            'clinic_xuexian': '学前街门诊',
            'clinic_dafeng': '大丰门诊',
            'clinic_dongting': '东亭门诊',
            'clinic_helai': '河埒门诊',
            'clinic_hongdou': '红豆门诊',
            'clinic_huishan': '惠山门诊',
            'clinic_mashan': '马山门诊',
            'clinic_hospital': '通善口腔医院',
            'clinic_xinwu': '新吴门诊'
        }

        clinic_name = clinic_name_mapping.get(clinic_id, '未知门诊')

        # 尝试从dify_callback_results目录加载回访话术
        import glob
        patterns = [
            f'dify_callback_results/中间结果_{clinic_name}.json',  # 无时间戳的文件
            f'dify_callback_results/中间结果_{clinic_name}_*.json',  # 有时间戳的文件
            f'../dify_callback_results/中间结果_{clinic_name}.json',
            f'../dify_callback_results/中间结果_{clinic_name}_*.json',
            f'../../dify_callback_results/中间结果_{clinic_name}.json',
            f'../../dify_callback_results/中间结果_{clinic_name}_*.json'
        ]

        for pattern in patterns:
            files = glob.glob(pattern)
            if files:
                # 使用最新的文件
                latest_file = max(files, key=os.path.getmtime)
                print(f"📄 加载回访话术文件: {latest_file}")

                with open(latest_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)

                # 获取callbacks列表
                callbacks = data.get('callbacks', [])
                print(f"📊 话术数据包含 {len(callbacks)} 个患者")

                # 查找患者的回访话术
                for item in callbacks:
                    if item.get('patient_id') == patient_id:
                        script = item.get('callback_script', '')
                        print(f"✅ 找到患者 {patient_id} 的回访话术，长度: {len(script)}")
                        return format_callback_script(script)

                print(f"⚠️ 未找到患者 {patient_id} 的回访话术")
                break

        print(f"❌ 未找到门诊 {clinic_name} 的回访话术文件")
        return None
    except Exception as e:
        print(f"❌ 加载回访话术失败: {e}")
        import traceback
        traceback.print_exc()
        return None

def format_callback_script(script):
    """格式化回访话术为HTML显示"""
    if not script:
        return None

    try:
        import re

        # 移除开头的JSON部分
        script = re.sub(r'^```json.*?```\n', '', script, flags=re.DOTALL)

        # 分割各个部分
        sections = []
        current_section = None
        current_content = []

        lines = script.split('\n')
        for line in lines:
            line = line.strip()
            if not line:
                continue

            # 检查是否是新的部分标题
            if line.startswith('═══') and '部分：' in line:
                # 保存上一个部分
                if current_section and current_content:
                    sections.append({
                        'title': current_section,
                        'content': current_content.copy()
                    })

                # 开始新的部分
                current_section = line.replace('═══', '').strip()
                current_content = []
            elif line.startswith('•'):
                # 添加内容项
                current_content.append(line[1:].strip())
            elif line.startswith('**') and line.endswith('**'):
                # 子标题
                current_content.append(f"<strong>{line[2:-2]}</strong>")
            elif line and current_section:
                # 其他内容
                current_content.append(line)

        # 保存最后一个部分
        if current_section and current_content:
            sections.append({
                'title': current_section,
                'content': current_content.copy()
            })

        # 生成HTML
        if not sections:
            return script  # 如果解析失败，返回原始内容

        html_parts = []
        colors = [
            ('bg-blue-100', 'border-blue-500', 'text-blue-800'),
            ('bg-yellow-100', 'border-yellow-500', 'text-yellow-800'),
            ('bg-green-100', 'border-green-500', 'text-green-800'),
            ('bg-purple-100', 'border-purple-500', 'text-purple-800')
        ]

        for i, section in enumerate(sections):
            bg_color, border_color, text_color = colors[i % len(colors)]

            content_html = []
            for item in section['content']:
                if item.startswith('<strong>'):
                    content_html.append(f'<div class="font-semibold mt-2 mb-1">{item}</div>')
                else:
                    content_html.append(f'<div class="mb-1">• {item}</div>')

            section_html = f'''
            <div class="mb-6 p-4 {bg_color} border-l-4 {border_color} rounded-lg">
                <h4 class="font-bold {text_color} mb-3 flex items-center">
                    <i class="fas fa-comment mr-2"></i>{section['title']}
                </h4>
                <div class="text-gray-700 leading-relaxed">
                    {''.join(content_html)}
                </div>
            </div>'''

            html_parts.append(section_html)

        return ''.join(html_parts)

    except Exception as e:
        print(f"❌ 格式化回访话术失败: {e}")
        return script  # 返回原始内容

def generate_callback_script(patient):
    """生成患者的回访话术（保持向后兼容）"""
    try:
        # 这个函数保持向后兼容，实际加载由load_callback_script处理
        return None
    except Exception as e:
        print(f"❌ 生成回访话术失败: {e}")
        return None

class AuthSystem:
    """用户认证系统"""
    
    def __init__(self):
        self.users = {user['username']: user for user in DEFAULT_USERS}
        self.sessions = {}  # 存储活跃session
        self.session_timeout = 8 * 60 * 60  # 8小时超时
    
    def hash_password(self, password):
        """密码哈希"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def verify_password(self, username, password):
        """验证密码"""
        user = self.users.get(username)
        if not user:
            return False
        
        # 简单密码验证（生产环境应使用bcrypt等）
        return user['password'] == password
    
    def create_session(self, username):
        """创建用户session"""
        session_id = secrets.token_urlsafe(32)
        user = self.users[username]
        
        session_data = {
            'session_id': session_id,
            'username': username,
            'real_name': user['real_name'],
            'role': user['role'],
            'clinic_id': user['clinic_id'],
            'clinic_name': user.get('clinic_name', '总部'),
            'created_at': datetime.now().isoformat(),
            'expires_at': (datetime.now() + timedelta(seconds=self.session_timeout)).isoformat()
        }
        
        self.sessions[session_id] = session_data
        return session_data
    
    def validate_session(self, session_id):
        """验证session有效性"""
        if not session_id or session_id not in self.sessions:
            return None
        
        session_data = self.sessions[session_id]
        expires_at = datetime.fromisoformat(session_data['expires_at'])
        
        if datetime.now() > expires_at:
            # Session过期，清理
            del self.sessions[session_id]
            return None
        
        # 延长session有效期
        session_data['expires_at'] = (datetime.now() + timedelta(seconds=self.session_timeout)).isoformat()
        return session_data
    
    def logout(self, session_id):
        """用户登出"""
        if session_id in self.sessions:
            del self.sessions[session_id]
            return True
        return False
    
    def check_clinic_access(self, session_data, clinic_id):
        """检查门诊访问权限"""
        if not session_data:
            return False
        
        # 管理员可以访问所有门诊
        if session_data['role'] == 'admin':
            return True
        
        # 门诊用户只能访问自己的门诊
        if session_data['role'] == 'clinic_user':
            return session_data['clinic_id'] == clinic_id
        
        return False
    
    def get_accessible_clinics(self, session_data):
        """获取用户可访问的门诊列表"""
        if not session_data:
            return []
        
        if session_data['role'] == 'admin':
            # 管理员可以访问所有门诊
            return [
                'clinic_xuexian', 'clinic_dafeng', 'clinic_dongting', 
                'clinic_helai', 'clinic_hongdou', 'clinic_huishan',
                'clinic_mashan', 'clinic_hospital', 'clinic_xinwu'
            ]
        elif session_data['role'] == 'clinic_user':
            # 门诊用户只能访问自己的门诊
            return [session_data['clinic_id']]
        
        return []

# 创建Flask应用
app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'dev_secret_key_2024')

# 配置CORS，允许跨域请求
CORS(app, supports_credentials=True, origins=['http://localhost:5001', 'http://127.0.0.1:5001'])

# 初始化认证系统
auth_system = AuthSystem()

# 初始化回访记录管理器
db_manager = None
# 临时存储（当数据库不可用时使用）
temp_callback_records = {}
# 内存存储最新的回访结果，用于状态API
callback_results_cache = {}

if CALLBACK_AVAILABLE:
    try:
        # 直接使用环境变量构建数据库配置
        db_host = os.getenv('DB_HOST', 'localhost')  # 本地开发默认使用localhost
        db_port = int(os.getenv('DB_PORT', '3306'))  # 本地开发使用Docker映射的端口3306
        db_user = os.getenv('DB_USER', 'callback_user')  # 使用Docker创建的用户
        db_password = os.getenv('DB_PASSWORD', 'dev_password_123')  # 使用Docker的callback_user密码
        db_name = os.getenv('DB_NAME', 'callback_system')
        
        print(f"尝试连接数据库: {db_host}:{db_port}")
        db_manager = MySQLCallbackRecordManager(
            host=db_host,
            port=db_port,
            user=db_user,
            password=db_password,
            database=db_name,
            charset='utf8mb4'
        )
        print("✅ 回访记录数据库管理器初始化成功")
    except Exception as e:
        print(f"⚠️  回访记录数据库管理器初始化失败: {e}")
        print("将使用临时内存存储")
        db_manager = None

# 页面模板现在使用独立的模板文件
# - templates/login.html: 登录页面模板
# - templates/admin_dashboard.html: 管理员仪表板模板
# - templates/clinic_dashboard.html: 门诊用户仪表板模板
# - templates/patient_list.html: 患者列表页面模板
# - templates/patient_detail.html: 患者详情页面模板

@app.route('/api/health', methods=['GET'])
def health_check():
    """健康检查端点"""
    return jsonify({
        'status': 'ok',
        'timestamp': datetime.now().isoformat(),
        'service': 'auth_system',
        'version': '1.0.0'
    })

@app.route('/api/callback-records', methods=['POST'])
def save_callback_record():
    """保存回访记录API"""
    try:
        data = request.get_json()
        
        # 验证必需字段
        required_fields = ['caseNumber', 'callbackMethods']
        for field in required_fields:
            if field not in data or not data[field]:
                return jsonify({
                    'success': False, 
                    'message': f'缺少必需字段: {field}'
                }), 400
        
        # 从session获取当前登录用户信息
        session_id = session.get('session_id')
        current_user = '系统用户'  # 默认值
        
        if session_id:
            session_data = auth_system.validate_session(session_id)
            if session_data:
                # 优先使用真实姓名，如果没有则使用用户名
                current_user = session_data.get('real_name') or session_data.get('username', '系统用户')
                print(f"当前登录用户: {current_user} (session: {session_data})")
            else:
                print("Session验证失败，使用默认操作员")
        else:
            print("未找到session_id，使用默认操作员")
        
        # 构建回访记录内容
        result = data.get('callbackResult', '成功')  # 修复重复的字段名
        methods = ', '.join(data.get('callbackMethods', []))
        callback_record = f"回访方式: {methods}, 回访结果: {result}"
        
        if result == '成功' and data.get('nextAppointmentTime'):
            callback_record += f", 下次预约时间: {data['nextAppointmentTime']}"
        elif result == '不成功' and data.get('failureReason'):
            callback_record += f", 失败原因: {data['failureReason']}"
        elif result == '放弃回访' and data.get('abandonReason'):
            callback_record += f", 放弃原因: {data['abandonReason']}"
        
        # 添加AI反馈
        if data.get('aiFeedbackType'):
            callback_record += f", AI反馈: {data['aiFeedbackType']}"

        # 添加备注信息
        if result == '不成功' and data.get('failureReasonNote'):
            callback_record += f", 不成功备注: {data['failureReasonNote']}"
        elif result == '放弃回访' and data.get('abandonReasonNote'):
            callback_record += f", 放弃回访备注: {data['abandonReasonNote']}"

        # 添加AI反馈备注
        if data.get('aiFeedbackNote'):
            callback_record += f", AI反馈备注: {data['aiFeedbackNote']}"
        
        # 在记录末尾添加原始结果标识，用于解析
        callback_record += f" | ORIGINAL_RESULT: {result}"
            
        if db_manager:
            # 使用数据库存储
            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获取的真实用户名
            )
            record_id = db_manager.save_record(record)
            
            # 更新内存缓存
            callback_results_cache[data['caseNumber']] = {
                'callback_result': result,
                'create_time': datetime.now()
            }
        else:
            # 使用临时内存存储
            case_number = data['caseNumber']
            if case_number not in temp_callback_records:
                temp_callback_records[case_number] = []
            
            record_id = len(temp_callback_records[case_number]) + 1
            temp_callback_records[case_number].append({
                'id': record_id,
                'case_number': case_number,
                'callback_methods': data['callbackMethods'],
                'callback_record': callback_record,
                'operator': current_user,  # 使用从session获取的真实用户名
                'create_time': datetime.now().isoformat()
            })
        
        return jsonify({
            'success': True,
            'id': record_id,
            'message': '保存成功',
            'timestamp': datetime.now().isoformat(),
            'storage': 'database' if db_manager else 'memory',
            'operator': current_user  # 返回实际使用的操作员信息
        })
        
    except Exception as e:
        print(f"保存回访记录失败: {e}")
        return jsonify({
            'success': False, 
            'message': f'保存失败: {str(e)}'
        }), 500

@app.route('/api/callback-records/<case_number>', methods=['GET'])
def get_callback_records(case_number):
    """获取回访记录API"""
    try:
        if db_manager:
            # 从数据库获取
            records = db_manager.get_records_by_case_number(case_number)
            record_data = [record.to_dict() for record in records]
        else:
            # 从临时内存获取
            record_data = temp_callback_records.get(case_number, [])
        
        return jsonify({
            'success': True,
            'data': record_data,
            'count': len(record_data),
            'timestamp': datetime.now().isoformat(),
            'storage': 'database' if db_manager else 'memory'
        })
        
    except Exception as e:
        print(f"获取回访记录失败: {e}")
        return jsonify({
            'success': False, 
            'message': f'获取失败: {str(e)}'
        }), 500

@app.route('/api/callback-status/<clinic_id>', methods=['GET'])
def get_clinic_callback_status(clinic_id):
    """获取指定门诊所有患者的回访状态"""
    try:
        if not db_manager:
            return jsonify({'success': False, 'message': '数据库不可用'}), 500
        
        # 获取该门诊所有患者的回访状态
        all_records = db_manager.get_all_records()
        
        # 按病历号分组，获取最新的回访状态
        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:
                        from datetime import datetime
                        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 jsonify({
            'success': True,
            'data': status_dict
        })
    except Exception as e:
        print(f"获取回访状态失败: {e}")
        return jsonify({'success': False, 'message': f'获取失败: {str(e)}'}), 500

@app.route('/')
def index():
    """主页 - 重定向到登录页面"""
    return redirect(url_for('login'))

@app.route('/admin/dashboard')
def admin_dashboard():
    """管理员仪表板 - 门诊索引页"""
    session_id = session.get('session_id')
    if not session_id:
        return redirect('/login')

    session_data = auth_system.validate_session(session_id)
    if not session_data:
        session.pop('session_id', None)
        return redirect('/login')

    if session_data['role'] != 'admin':
        return redirect('/login')

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

@app.route('/clinic/<clinic_id>')
def clinic_dashboard(clinic_id):
    """门诊用户仪表板"""
    session_id = session.get('session_id')
    if not session_id:
        return redirect('/login')

    session_data = auth_system.validate_session(session_id)
    if not session_data:
        session.pop('session_id', None)
        return redirect('/login')

    # 检查用户是否有权限访问此门诊
    if not auth_system.check_clinic_access(session_data, clinic_id):
        return "无权限访问此门诊", 403

    # 获取门诊信息
    clinic_info = get_clinic_info(clinic_id)
    clinic_name = clinic_info.get('clinic_name', '未知门诊') if clinic_info else '未知门诊'

    return render_template('clinic_dashboard.html',
                         session_data=session_data,
                         clinic_id=clinic_id,
                         clinic_name=clinic_name)

@app.route('/patient_profiles/<clinic_id>/index.html')
def patient_list(clinic_id):
    """患者列表页面"""
    session_id = session.get('session_id')
    if not session_id:
        return redirect('/login')

    session_data = auth_system.validate_session(session_id)
    if not session_data:
        session.pop('session_id', None)
        return redirect('/login')

    # 检查用户是否有权限访问此门诊
    if not auth_system.check_clinic_access(session_data, clinic_id):
        return "无权限访问此门诊", 403

    # 获取门诊信息
    clinic_info = get_clinic_info(clinic_id)
    clinic_name = clinic_info.get('clinic_name', '未知门诊') if clinic_info else '未知门诊'

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

    return render_template('patient_list.html',
                         session_data=session_data,
                         clinic_id=clinic_id,
                         clinic_name=clinic_name,
                         patients=patients,
                         doctors=doctors)

@app.route('/patient_profiles/<clinic_id>/patients/<patient_id>.html')
def patient_detail(clinic_id, patient_id):
    """患者详情页面"""
    session_id = session.get('session_id')
    if not session_id:
        return redirect('/login')

    session_data = auth_system.validate_session(session_id)
    if not session_data:
        session.pop('session_id', None)
        return redirect('/login')

    # 检查用户是否有权限访问此门诊
    if not auth_system.check_clinic_access(session_data, clinic_id):
        return "无权限访问此门诊", 403

    # 获取门诊信息
    clinic_info = get_clinic_info(clinic_id)
    clinic_name = clinic_info.get('clinic_name', '未知门诊') if clinic_info else '未知门诊'

    # 加载患者详细信息
    patient = load_patient_detail(clinic_id, patient_id)
    if not patient:
        return "患者不存在", 404

    # 加载回访记录
    callback_records = load_callback_records(patient_id)

    # 加载回访话术
    callback_script = load_callback_script(clinic_id, patient_id)
    print(f"🎯 患者详情页面 - callback_script类型: {type(callback_script)}")
    if callback_script:
        print(f"🎯 患者详情页面 - callback_script长度: {len(callback_script)}")
        print(f"🎯 患者详情页面 - callback_script前100字符: {callback_script[:100]}")
    else:
        print(f"🎯 患者详情页面 - callback_script为空")

    return render_template('patient_detail.html',
                         session_data=session_data,
                         clinic_id=clinic_id,
                         clinic_name=clinic_name,
                         patient=patient,
                         callback_records=callback_records,
                         callback_script=callback_script)

@app.route('/login', methods=['GET', 'POST'])
def login():
    """登录页面"""
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        if auth_system.verify_password(username, password):
            # 登录成功，创建session
            session_data = auth_system.create_session(username)
            session['session_id'] = session_data['session_id']

            # 根据用户角色重定向
            if session_data['role'] == 'admin':
                # 管理员重定向到门诊索引页
                return redirect('/admin/dashboard')
            else:
                # 普通用户重定向到患者索引页
                return redirect(f'/patient_profiles/{session_data["clinic_id"]}/index.html')
        else:
            return render_template('login.html', error='用户名或密码错误')

    return render_template('login.html')

@app.route('/api/login', methods=['POST'])
def handle_login_api():
    """API登录接口"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400
        
        if auth_system.verify_password(username, password):
            # 登录成功
            session_data = auth_system.create_session(username)
            
            return jsonify({
                'success': True,
                'message': '登录成功',
                'user': {
                    'username': session_data['username'],
                    'real_name': session_data['real_name'],
                    'role': session_data['role'],
                    'clinic_id': session_data['clinic_id'],
                    'clinic_name': session_data['clinic_name']
                },
                'session_id': session_data['session_id']
            })
        else:
            return jsonify({'success': False, 'message': '用户名或密码错误'}), 401
            
    except Exception as e:
        return jsonify({'success': False, 'message': f'登录失败: {str(e)}'}), 500

@app.route('/api/user-info', methods=['GET', 'POST'])
def get_user_info():
    """获取用户信息"""
    session_id = session.get('session_id')
    
    # 如果是POST请求，也尝试从请求体中获取session_id
    if request.method == 'POST':
        try:
            data = request.get_json()
            if data and 'session_id' in data:
                # 这里我们仍然使用Flask session中的session_id，忽略POST中的session_id
                # 这是为了安全考虑
                pass
        except:
            pass
    
    if not session_id:
        return jsonify({'success': False, 'authenticated': False, 'message': '未登录'})
    
    session_data = auth_system.validate_session(session_id)
    if not session_data:
        session.pop('session_id', None)
        return jsonify({'success': False, 'authenticated': False, 'message': 'Session已过期'})
    
    return jsonify({
        'success': True,
        'authenticated': True,
        'user': {
            'username': session_data['username'],
            'realName': session_data['real_name'],
            'role': session_data['role'],
            'clinic_id': session_data['clinic_id'],
            'clinicName': session_data['clinic_name']
        }
    })

@app.route('/api/check-access/<clinic_id>')
def check_access(clinic_id):
    """检查门诊访问权限"""
    session_id = session.get('session_id')
    if not session_id:
        return jsonify({'has_access': False, 'message': '未登录'})
    
    session_data = auth_system.validate_session(session_id)
    if not session_data:
        session.pop('session_id', None)
        return jsonify({'has_access': False, 'message': 'Session已过期'})
    
    # 检查用户是否有权限访问指定门诊
    has_access = auth_system.check_clinic_access(session_data, clinic_id)
    
    return jsonify({
        'has_access': has_access,
        'message': '访问权限检查完成'
    })

@app.route('/api/auth/logout', methods=['POST'])
def api_logout():
    """API登出"""
    session_id = session.get('session_id')
    if session_id:
        auth_system.logout(session_id)
        session.pop('session_id', None)
    
    return jsonify({'success': True, 'message': '登出成功'})

@app.route('/api/export-data', methods=['GET'])
def export_data():
    """导出所有诊所的回访记录数据到Excel"""
    try:
        # 检查用户权限
        session_id = session.get('session_id')
        if not session_id:
            return jsonify({'success': False, 'message': '未登录'}), 401
        
        session_data = auth_system.validate_session(session_id)
        if not session_data:
            session.pop('session_id', None)
            return jsonify({'success': False, 'message': 'Session已过期'}), 401
        
        # 只有管理员可以导出所有数据
        if session_data['role'] != 'admin':
            return jsonify({'success': False, 'message': '权限不足，只有管理员可以导出数据'}), 403
        
        # 导入导出模块
        try:
            from 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"
        
        # 在Docker容器中，使用/app目录
        if os.path.exists('/app'):
            output_path = os.path.join('/app', output_filename)
        else:
            output_path = os.path.join(os.getcwd(), output_filename)
        
        print(f"导出路径: {output_path}")
        print(f"当前工作目录: {os.getcwd()}")
        
        # 导出数据
        try:
            exporter.export_to_excel(output_path)
            print(f"导出完成，文件路径: {output_path}")
        except Exception as export_error:
            print(f"导出过程中出错: {export_error}")
            import traceback
            traceback.print_exc()
            return jsonify({'success': False, 'message': f'导出过程出错: {str(export_error)}'}), 500
        
        # 检查文件是否生成成功
        if not os.path.exists(output_path):
            print(f"文件不存在: {output_path}")
            # 列出目录内容
            try:
                dir_content = os.listdir(os.path.dirname(output_path))
                print(f"目录内容: {dir_content}")
            except Exception as list_error:
                print(f"无法列出目录内容: {list_error}")
            return jsonify({'success': False, 'message': '文件生成失败'}), 500
        
        # 检查文件大小
        file_size = os.path.getsize(output_path)
        print(f"生成的文件大小: {file_size} 字节")
        
        # 返回文件下载链接
        return jsonify({
            'success': True,
            'message': '数据导出成功',
            'filename': output_filename,
            'download_url': f'/download/{output_filename}'
        })
        
    except Exception as e:
        print(f"导出数据失败: {e}")
        return jsonify({'success': False, 'message': f'导出失败: {str(e)}'}), 500

@app.route('/download/<filename>')
def download_file(filename):
    """下载导出的文件"""
    try:
        # 检查用户权限
        session_id = session.get('session_id')
        if not session_id:
            return jsonify({'success': False, 'message': '未登录'}), 401
        
        session_data = auth_system.validate_session(session_id)
        if not session_data:
            session.pop('session_id', None)
            return jsonify({'success': False, 'message': 'Session已过期'}), 401
        
        # 只有管理员可以下载文件
        if session_data['role'] != 'admin':
            return jsonify({'success': False, 'message': '权限不足'}), 403
        
        # 检查文件路径安全性
        if '..' in filename or filename.startswith('/'):
            return "非法文件路径", 400
        
        # 构建文件路径
        file_path = os.path.join(os.getcwd(), filename)
        
        if not os.path.exists(file_path):
            return "文件不存在", 404
        
        # 发送文件
        return send_file(file_path, as_attachment=True, download_name=filename)
        
    except Exception as e:
        return f"文件下载错误: {str(e)}", 500

# 注意：原来的 serve_patient_profiles 路由已被移除
# 现在所有患者相关页面都通过专门的动态路由处理：
# - /patient_profiles/<clinic_id>/index.html → patient_list 函数
# - /patient_profiles/<clinic_id>/patients/<patient_id>.html → patient_detail 函数

if __name__ == '__main__':
    print("🚀 启动患者画像系统认证服务器...")
    print("📋 系统信息:")
    print(f"   - 用户数量: {len(DEFAULT_USERS)}")
    print(f"   - 门诊数量: {len(set(user.get('clinic_id') for user in DEFAULT_USERS if user.get('clinic_id') != 'admin'))}")
    print(f"   - Session超时: {auth_system.session_timeout // 3600}小时")
    
    try:
        # 本地开发使用5001端口，Docker使用5000端口
        port = int(os.getenv('PORT', 5001))
        # 检测是否为开发环境
        is_development = os.getenv('FLASK_ENV') == 'development' or os.getenv('FLASK_DEBUG', '').lower() in ['1', 'true']

        print(f"🌐 服务器将在端口 {port} 启动")
        print(f"🔧 开发模式: {'开启' if is_development else '关闭'}")
        if is_development:
            print("🔥 热重载已启用")

        app.run(
            host='0.0.0.0',
            port=port,
            debug=is_development,
            use_reloader=is_development
        )
    except Exception as e:
        print(f"❌ 启动服务器失败: {e}")
        import traceback
        traceback.print_exc()