"""
完整业务流程E2E测试
测试用户管理、角色管理等核心功能
"""

from playwright.sync_api import sync_playwright
import time

class E2ETestSuite:
    def __init__(self):
        self.browser = None
        self.context = None
        self.page = None
        self.test_results = []
    
    def setup(self):
        """初始化测试环境"""
        print("\n" + "=" * 60)
        print("初始化测试环境...")
        print("=" * 60)
        
        p = sync_playwright().start()
        self.browser = p.chromium.launch(headless=True)
        self.context = self.browser.new_context()
        self.page = self.context.new_page()
        
        print("✅ 浏览器初始化完成")
    
    def teardown(self):
        """清理测试环境"""
        if self.browser:
            self.browser.close()
        print("\n✅ 测试环境已清理")
    
    def login(self):
        """登录功能测试"""
        print("\n" + "=" * 60)
        print("测试1: 登录功能")
        print("=" * 60)
        
        try:
            print("1. 访问登录页面...")
            self.page.goto('http://localhost:3002/login')
            self.page.wait_for_load_state('networkidle')
            
            print("2. 填写登录表单...")
            self.page.fill('input[type="text"], input[placeholder*="用户名"]', 'admin')
            self.page.fill('input[type="password"]', 'admin123')
            
            print("3. 提交登录...")
            with self.page.expect_navigation(timeout=10000):
                self.page.click('button:has-text("登录")')
            
            time.sleep(2)
            self.page.wait_for_load_state('networkidle')
            
            current_url = self.page.url
            token = self.page.evaluate('() => localStorage.getItem("token")')
            
            if token and '/login' not in current_url:
                print("✅ 登录成功")
                print(f"   当前URL: {current_url}")
                self.test_results.append(("登录功能", "PASS"))
                return True
            else:
                print("❌ 登录失败")
                self.test_results.append(("登录功能", "FAIL"))
                return False
                
        except Exception as e:
            print(f"❌ 登录测试错误: {str(e)}")
            self.test_results.append(("登录功能", "ERROR"))
            return False
    
    def test_user_management(self):
        """用户管理功能测试"""
        print("\n" + "=" * 60)
        print("测试2: 用户管理功能")
        print("=" * 60)
        
        try:
            print("1. 导航到用户管理页面...")
            self.page.goto('http://localhost:3002/users')
            time.sleep(2)
            self.page.wait_for_load_state('networkidle')
            
            print("2. 检查页面元素...")
            current_url = self.page.url
            print(f"   当前URL: {current_url}")
            
            has_user_list = self.page.locator('table, .el-table').count() > 0
            print(f"   用户列表表格: {'存在' if has_user_list else '不存在'}")
            
            self.page.screenshot(path='/tmp/user_management.png', full_page=True)
            print("   截图已保存")
            
            if '/users' in current_url:
                print("✅ 用户管理页面访问成功")
                self.test_results.append(("用户管理", "PASS"))
                return True
            else:
                print("❌ 用户管理页面访问失败")
                self.test_results.append(("用户管理", "FAIL"))
                return False
                
        except Exception as e:
            print(f"❌ 用户管理测试错误: {str(e)}")
            self.test_results.append(("用户管理", "ERROR"))
            return False
    
    def test_role_management(self):
        """角色管理功能测试"""
        print("\n" + "=" * 60)
        print("测试3: 角色管理功能")
        print("=" * 60)
        
        try:
            print("1. 导航到角色管理页面...")
            self.page.goto('http://localhost:3002/roles')
            time.sleep(2)
            self.page.wait_for_load_state('networkidle')
            
            print("2. 检查页面元素...")
            current_url = self.page.url
            print(f"   当前URL: {current_url}")
            
            has_role_list = self.page.locator('table, .el-table').count() > 0
            print(f"   角色列表表格: {'存在' if has_role_list else '不存在'}")
            
            self.page.screenshot(path='/tmp/role_management.png', full_page=True)
            print("   截图已保存")
            
            if '/roles' in current_url:
                print("✅ 角色管理页面访问成功")
                self.test_results.append(("角色管理", "PASS"))
                return True
            else:
                print("❌ 角色管理页面访问失败")
                self.test_results.append(("角色管理", "FAIL"))
                return False
                
        except Exception as e:
            print(f"❌ 角色管理测试错误: {str(e)}")
            self.test_results.append(("角色管理", "ERROR"))
            return False
    
    def test_dashboard(self):
        """Dashboard功能测试"""
        print("\n" + "=" * 60)
        print("测试4: Dashboard功能")
        print("=" * 60)
        
        try:
            print("1. 导航到Dashboard页面...")
            self.page.goto('http://localhost:3002/dashboard')
            time.sleep(2)
            self.page.wait_for_load_state('networkidle')
            
            print("2. 检查页面元素...")
            current_url = self.page.url
            print(f"   当前URL: {current_url}")
            
            page_title = self.page.title()
            print(f"   页面标题: {page_title}")
            
            self.page.screenshot(path='/tmp/dashboard.png', full_page=True)
            print("   截图已保存")
            
            if '/dashboard' in current_url:
                print("✅ Dashboard页面访问成功")
                self.test_results.append(("Dashboard", "PASS"))
                return True
            else:
                print("❌ Dashboard页面访问失败")
                self.test_results.append(("Dashboard", "FAIL"))
                return False
                
        except Exception as e:
            print(f"❌ Dashboard测试错误: {str(e)}")
            self.test_results.append(("Dashboard", "ERROR"))
            return False
    
    def run_all_tests(self):
        """运行所有测试"""
        print("\n" + "=" * 60)
        print("开始运行完整测试套件")
        print("=" * 60)
        
        self.setup()
        
        try:
            if not self.login():
                print("\n❌ 登录失败，无法继续后续测试")
                return
            
            self.test_dashboard()
            self.test_user_management()
            self.test_role_management()
            
        finally:
            self.print_summary()
            self.teardown()
    
    def print_summary(self):
        """打印测试摘要"""
        print("\n" + "=" * 60)
        print("测试结果摘要")
        print("=" * 60)
        
        pass_count = sum(1 for _, result in self.test_results if result == "PASS")
        fail_count = sum(1 for _, result in self.test_results if result == "FAIL")
        error_count = sum(1 for _, result in self.test_results if result == "ERROR")
        
        for test_name, result in self.test_results:
            icon = "✅" if result == "PASS" else "❌" if result == "FAIL" else "⚠️"
            print(f"{icon} {test_name}: {result}")
        
        print("\n" + "-" * 60)
        print(f"总计: {len(self.test_results)} 个测试")
        print(f"通过: {pass_count} 个")
        print(f"失败: {fail_count} 个")
        print(f"错误: {error_count} 个")
        print("=" * 60)
        
        if fail_count == 0 and error_count == 0:
            print("\n🎉 所有测试通过！")
        else:
            print(f"\n⚠️  有 {fail_count + error_count} 个测试未通过")

if __name__ == "__main__":
    suite = E2ETestSuite()
    suite.run_all_tests()
