"""
调试用户管理页面访问问题
"""

from playwright.sync_api import sync_playwright
import time

def debug_user_management():
    """调试用户管理页面访问"""
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context()
        page = context.new_page()
        
        console_messages = []
        
        def handle_console(msg):
            console_messages.append({
                'type': msg.type,
                'text': msg.text
            })
            print(f"[Console {msg.type}] {msg.text}")
        
        def handle_request(request):
            if 'api' in request.url:
                print(f"[Request {request.method}] {request.url}")
                auth_header = request.headers.get('authorization', 'None')
                token_header = request.headers.get('token', 'None')
                print(f"  Authorization: {auth_header[:30] if auth_header != 'None' else 'None'}...")
                print(f"  Token: {token_header[:30] if token_header != 'None' else 'None'}...")
        
        def handle_response(response):
            if 'api' in response.url:
                print(f"[Response {response.status}] {response.url}")
        
        page.on('console', handle_console)
        page.on('request', handle_request)
        page.on('response', handle_response)
        
        try:
            print("=" * 60)
            print("调试用户管理页面访问")
            print("=" * 60)
            
            print("\n1. 登录...")
            page.goto('http://localhost:3002/login')
            page.wait_for_load_state('networkidle')
            page.fill('input[type="text"], input[placeholder*="用户名"]', 'admin')
            page.fill('input[type="password"]', 'admin123')
            
            with page.expect_navigation(timeout=10000):
                page.click('button:has-text("登录")')
            
            time.sleep(2)
            page.wait_for_load_state('networkidle')
            
            token = page.evaluate('() => localStorage.getItem("token")')
            print(f"\nToken after login: {token[:50] if token else 'None'}...")
            
            print("\n2. 访问用户管理页面...")
            page.goto('http://localhost:3002/users')
            time.sleep(3)
            page.wait_for_load_state('networkidle')
            
            current_url = page.url
            print(f"\n当前URL: {current_url}")
            
            token_after = page.evaluate('() => localStorage.getItem("token")')
            print(f"Token after navigation: {token_after[:50] if token_after else 'None'}...")
            
            page.screenshot(path='/tmp/debug_user_mgmt.png', full_page=True)
            
            print("\n" + "=" * 60)
            print("调试信息汇总:")
            print("=" * 60)
            print(f"登录后Token: {'存在' if token else '不存在'}")
            print(f"跳转后Token: {'存在' if token_after else '不存在'}")
            print(f"最终URL: {current_url}")
            
            if '/login' in current_url:
                print("\n❌ 被重定向回登录页")
                print("可能原因:")
                print("1. Token在跳转时丢失")
                print("2. 路由守卫检测到Token无效")
                print("3. 权限验证失败")
            else:
                print("\n✅ 成功访问用户管理页面")
            
        except Exception as e:
            print(f"\n❌ 错误: {str(e)}")
            import traceback
            traceback.print_exc()
        finally:
            browser.close()

if __name__ == "__main__":
    debug_user_management()
