import { test, expect, Page } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
import { UserManagementPage } from './pages/UserManagementPage';
import { RoleManagementPage } from './pages/RoleManagementPage';
import { MenuManagementPage } from './pages/MenuManagementPage';
import { OperationLogPage } from './pages/OperationLogPage';
import { DictionaryManagementPage } from './pages/DictionaryManagementPage';
import { SystemConfigPage } from './pages/SystemConfigPage';
import { FileManagementPage } from './pages/FileManagementPage';

test.describe('系统全面集成测试', () => {
  let loginPage: LoginPage;
  let userManagementPage: UserManagementPage;
  let roleManagementPage: RoleManagementPage;
  let menuManagementPage: MenuManagementPage;
  let operationLogPage: OperationLogPage;
  let dictionaryManagementPage: DictionaryManagementPage;
  let systemConfigPage: SystemConfigPage;
  let fileManagementPage: FileManagementPage;

  test.beforeEach(async ({ page }) => {
    loginPage = new LoginPage(page);
    userManagementPage = new UserManagementPage(page);
    roleManagementPage = new RoleManagementPage(page);
    menuManagementPage = new MenuManagementPage(page);
    operationLogPage = new OperationLogPage(page);
    dictionaryManagementPage = new DictionaryManagementPage(page);
    systemConfigPage = new SystemConfigPage(page);
    fileManagementPage = new FileManagementPage(page);
  });

  test.describe('1. 用户认证流程测试', () => {
    test('1.1 正确的用户名和密码登录成功', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      
      await expect(page).toHaveURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      await expect(page.locator('.dashboard')).toBeVisible();
    });

    test('1.2 错误的密码登录失败', async ({ page }) => {
      await loginPage.goto();
      await loginPage.usernameInput.fill('admin');
      await loginPage.passwordInput.fill('wrongpassword');
      await loginPage.loginButton.click();
      
      await page.waitForTimeout(2000);
      
      await expect(page).toHaveURL(/.*login/, { timeout: 5000 });
    });

    test('1.3 不存在的用户登录失败', async ({ page }) => {
      await loginPage.goto();
      await loginPage.usernameInput.fill('nonexistent');
      await loginPage.passwordInput.fill('Test@123');
      await loginPage.loginButton.click();
      
      await page.waitForTimeout(2000);
      
      await expect(page).toHaveURL(/.*login/, { timeout: 5000 });
    });

    test('1.4 空用户名或密码登录失败', async ({ page }) => {
      await loginPage.goto();
      await loginPage.usernameInput.fill('');
      await loginPage.passwordInput.fill('Test@123');
      await loginPage.loginButton.click();
      
      await expect(page.locator('.el-form-item__error')).toBeVisible({ timeout: 5000 });
    });

    test('1.5 禁用用户登录失败', async ({ page }) => {
      await loginPage.goto();
      await loginPage.usernameInput.fill('disableduser');
      await loginPage.passwordInput.fill('Test@123');
      await loginPage.loginButton.click();
      
      await page.waitForTimeout(2000);
      
      await expect(page).toHaveURL(/.*login/, { timeout: 5000 });
    });

    test('1.6 登出功能正常', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      
      await expect(page).toHaveURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      await page.locator('.el-avatar').click();
      await page.waitForTimeout(500);
      await page.locator('.el-dropdown-menu').getByText('退出登录').click();
      
      await expect(page).toHaveURL(/.*login/, { timeout: 5000 });
    });
  });

  test.describe('2. 用户管理流程测试', () => {
    test.beforeEach(async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
    });

    test('2.1 查询用户列表', async ({ page }) => {
      await userManagementPage.goto();
      
      await expect(page.locator('.user-table')).toBeVisible({ timeout: 5000 });
      await expect(page.locator('.user-row')).toHaveCount(await page.locator('.user-row').count());
    });

    test('2.2 创建新用户', async ({ page }) => {
      const timestamp = Date.now();
      const username = `testuser_${timestamp}`;
      
      await userManagementPage.goto();
      await userManagementPage.clickCreateUser();
      await userManagementPage.fillUserForm({
        username: username,
        password: 'Test@123',
        email: `${username}@test.com`,
        phone: '13800138000',
        nickname: `测试用户${timestamp}`
      });
      await userManagementPage.submitUserForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      await userManagementPage.searchUser(username);
      await expect(page.locator('.user-row').first()).toContainText(username);
    });

    test('2.3 编辑用户信息', async ({ page }) => {
      await userManagementPage.goto();
      
      const firstUser = page.locator('.user-row').first();
      await firstUser.locator('[data-testid="edit-button"]').click();
      
      const newNickname = `更新昵称_${Date.now()}`;
      await page.fill('[name="nickname"]', newNickname);
      await page.click('[data-testid="submit-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('2.4 删除用户', async ({ page }) => {
      const timestamp = Date.now();
      const username = `deleteuser_${timestamp}`;
      
      await userManagementPage.goto();
      await userManagementPage.clickCreateUser();
      await userManagementPage.fillUserForm({
        username: username,
        password: 'Test@123',
        email: `${username}@test.com`,
        phone: '13800138000',
        nickname: `待删除用户${timestamp}`
      });
      await userManagementPage.submitUserForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      await userManagementPage.searchUser(username);
      const userRow = page.locator('.user-row').first();
      await userRow.locator('[data-testid="delete-button"]').click();
      
      page.on('dialog', dialog => dialog.accept());
      await page.click('[data-testid="confirm-delete-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('2.5 分配用户角色', async ({ page }) => {
      await userManagementPage.goto();
      
      const firstUser = page.locator('.user-row').first();
      await firstUser.locator('[data-testid="assign-role-button"]').click();
      
      await page.check('[data-testid="role-admin"]');
      await page.click('[data-testid="submit-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('2.6 启用/禁用用户', async ({ page }) => {
      await userManagementPage.goto();
      
      const firstUser = page.locator('.user-row').first();
      const statusButton = firstUser.locator('[data-testid="toggle-status-button"]');
      const currentStatus = await statusButton.getAttribute('data-status');
      
      await statusButton.click();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      const newStatus = await statusButton.getAttribute('data-status');
      expect(newStatus).not.toBe(currentStatus);
    });
  });

  test.describe('3. 角色管理流程测试', () => {
    test.beforeEach(async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
    });

    test('3.1 查询角色列表', async ({ page }) => {
      await roleManagementPage.goto();
      
      await expect(page.locator('.role-table')).toBeVisible({ timeout: 5000 });
      const roleCount = await page.locator('.role-row').count();
      expect(roleCount).toBeGreaterThan(0);
    });

    test('3.2 创建新角色', async ({ page }) => {
      const timestamp = Date.now();
      const roleName = `测试角色_${timestamp}`;
      const roleKey = `test_role_${timestamp}`;
      
      await roleManagementPage.goto();
      await roleManagementPage.clickCreateRole();
      await roleManagementPage.fillRoleForm({
        roleName: roleName,
        roleKey: roleKey,
        roleSort: '99'
      });
      await roleManagementPage.submitRoleForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      await roleManagementPage.searchRole(roleName);
      await expect(page.locator('.role-row').first()).toContainText(roleName);
    });

    test('3.3 编辑角色', async ({ page }) => {
      await roleManagementPage.goto();
      
      const firstRole = page.locator('.role-row').first();
      await firstRole.locator('[data-testid="edit-button"]').click();
      
      const newRoleName = `更新角色_${Date.now()}`;
      await page.fill('[name="roleName"]', newRoleName);
      await page.click('[data-testid="submit-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('3.4 删除角色', async ({ page }) => {
      const timestamp = Date.now();
      const roleName = `待删除角色_${timestamp}`;
      const roleKey = `delete_role_${timestamp}`;
      
      await roleManagementPage.goto();
      await roleManagementPage.clickCreateRole();
      await roleManagementPage.fillRoleForm({
        roleName: roleName,
        roleKey: roleKey,
        roleSort: '99'
      });
      await roleManagementPage.submitRoleForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      await roleManagementPage.searchRole(roleName);
      const roleRow = page.locator('.role-row').first();
      await roleRow.locator('[data-testid="delete-button"]').click();
      
      page.on('dialog', dialog => dialog.accept());
      await page.click('[data-testid="confirm-delete-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('3.5 分配角色权限', async ({ page }) => {
      await roleManagementPage.goto();
      
      const firstRole = page.locator('.role-row').first();
      await firstRole.locator('[data-testid="assign-permission-button"]').click();
      
      await page.check('[data-testid="permission-user-manage"]');
      await page.click('[data-testid="submit-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });
  });

  test.describe('4. 菜单管理流程测试', () => {
    test.beforeEach(async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
    });

    test('4.1 查询菜单树', async ({ page }) => {
      await menuManagementPage.goto();
      
      await expect(page.locator('.menu-tree')).toBeVisible({ timeout: 5000 });
      const menuCount = await page.locator('.menu-node').count();
      expect(menuCount).toBeGreaterThan(0);
    });

    test('4.2 创建新菜单', async ({ page }) => {
      const timestamp = Date.now();
      const menuName = `测试菜单_${timestamp}`;
      
      await menuManagementPage.goto();
      await menuManagementPage.clickCreateMenu();
      await menuManagementPage.fillMenuForm({
        menuName: menuName,
        path: `/test-${timestamp}`,
        component: 'test/index',
        menuType: 'C',
        orderNum: '99'
      });
      await menuManagementPage.submitMenuForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('4.3 编辑菜单', async ({ page }) => {
      await menuManagementPage.goto();
      
      const firstMenu = page.locator('.menu-node').first();
      await firstMenu.locator('[data-testid="edit-button"]').click();
      
      const newMenuName = `更新菜单_${Date.now()}`;
      await page.fill('[name="menuName"]', newMenuName);
      await page.click('[data-testid="submit-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('4.4 删除菜单', async ({ page }) => {
      const timestamp = Date.now();
      const menuName = `待删除菜单_${timestamp}`;
      
      await menuManagementPage.goto();
      await menuManagementPage.clickCreateMenu();
      await menuManagementPage.fillMenuForm({
        menuName: menuName,
        path: `/delete-${timestamp}`,
        component: 'delete/index',
        menuType: 'C',
        orderNum: '99'
      });
      await menuManagementPage.submitMenuForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      const menuNode = page.locator(`.menu-node:has-text("${menuName}")`).first();
      await menuNode.locator('[data-testid="delete-button"]').click();
      
      page.on('dialog', dialog => dialog.accept());
      await page.click('[data-testid="confirm-delete-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });
  });

  test.describe('5. 权限验证测试', () => {
    test('5.1 管理员可以访问所有功能', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      await userManagementPage.goto();
      await expect(page.locator('.user-table')).toBeVisible({ timeout: 5000 });
      
      await roleManagementPage.goto();
      await expect(page.locator('.role-table')).toBeVisible({ timeout: 5000 });
      
      await menuManagementPage.goto();
      await expect(page.locator('.menu-tree')).toBeVisible({ timeout: 5000 });
    });

    test('5.2 普通用户只能访问授权功能', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('normaluser', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      await page.goto('/user-management');
      
      const hasAccess = await page.locator('.user-table').isVisible().catch(() => false);
      
      if (!hasAccess) {
        await expect(page.locator('.no-permission')).toBeVisible({ timeout: 5000 });
      }
    });

    test('5.3 未登录用户访问受保护页面跳转到登录页', async ({ page }) => {
      await page.goto('/user-management');
      
      await expect(page).toHaveURL(/.*login/, { timeout: 5000 });
    });
  });

  test.describe('6. 操作日志测试', () => {
    test.beforeEach(async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
    });

    test('6.1 查询操作日志列表', async ({ page }) => {
      await operationLogPage.goto();
      
      await expect(page.locator('.log-table')).toBeVisible({ timeout: 5000 });
      const logCount = await page.locator('.log-row').count();
      expect(logCount).toBeGreaterThan(0);
    });

    test('6.2 按时间范围查询日志', async ({ page }) => {
      await operationLogPage.goto();
      
      const today = new Date().toISOString().split('T')[0];
      await page.fill('[name="startDate"]', today);
      await page.fill('[name="endDate"]', today);
      await page.click('[data-testid="search-button"]');
      
      await expect(page.locator('.log-row').first()).toBeVisible({ timeout: 5000 });
    });

    test('6.3 按用户查询日志', async ({ page }) => {
      await operationLogPage.goto();
      
      await page.fill('[name="username"]', 'admin');
      await page.click('[data-testid="search-button"]');
      
      await expect(page.locator('.log-row').first()).toBeVisible({ timeout: 5000 });
      await expect(page.locator('.log-row').first()).toContainText('admin');
    });

    test('6.4 导出操作日志', async ({ page }) => {
      await operationLogPage.goto();
      
      const [download] = await Promise.all([
        page.waitForEvent('download'),
        page.click('[data-testid="export-button"]')
      ]);
      
      expect(download.suggestedFilename()).toContain('.xlsx');
    });
  });

  test.describe('7. 字典管理测试', () => {
    test.beforeEach(async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
    });

    test('7.1 查询字典类型列表', async ({ page }) => {
      await dictionaryManagementPage.goto();
      
      await expect(page.locator('.dict-type-table')).toBeVisible({ timeout: 5000 });
    });

    test('7.2 创建字典类型', async ({ page }) => {
      const timestamp = Date.now();
      const dictName = `测试字典_${timestamp}`;
      const dictType = `test_dict_${timestamp}`;
      
      await dictionaryManagementPage.goto();
      await dictionaryManagementPage.clickCreateDictType();
      await dictionaryManagementPage.fillDictTypeForm({
        dictName: dictName,
        dictType: dictType
      });
      await dictionaryManagementPage.submitDictTypeForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('7.3 查询字典数据', async ({ page }) => {
      await dictionaryManagementPage.goto();
      
      const firstDictType = page.locator('.dict-type-row').first();
      await firstDictType.click();
      
      await expect(page.locator('.dict-data-table')).toBeVisible({ timeout: 5000 });
    });

    test('7.4 创建字典数据', async ({ page }) => {
      await dictionaryManagementPage.goto();
      
      const firstDictType = page.locator('.dict-type-row').first();
      await firstDictType.click();
      
      await dictionaryManagementPage.clickCreateDictData();
      await dictionaryManagementPage.fillDictDataForm({
        dictLabel: `测试数据_${Date.now()}`,
        dictValue: `test_value_${Date.now()}`,
        dictSort: '99'
      });
      await dictionaryManagementPage.submitDictDataForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });
  });

  test.describe('8. 系统配置测试', () => {
    test.beforeEach(async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
    });

    test('8.1 查询系统配置列表', async ({ page }) => {
      await systemConfigPage.goto();
      
      await expect(page.locator('.config-table')).toBeVisible({ timeout: 5000 });
    });

    test('8.2 创建系统配置', async ({ page }) => {
      const timestamp = Date.now();
      const configKey = `test.config.${timestamp}`;
      const configValue = `test_value_${timestamp}`;
      
      await systemConfigPage.goto();
      await systemConfigPage.clickCreateConfig();
      await systemConfigPage.fillConfigForm({
        configKey: configKey,
        configValue: configValue,
        configName: `测试配置_${timestamp}`
      });
      await systemConfigPage.submitConfigForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('8.3 编辑系统配置', async ({ page }) => {
      await systemConfigPage.goto();
      
      const firstConfig = page.locator('.config-row').first();
      await firstConfig.locator('[data-testid="edit-button"]').click();
      
      const newValue = `updated_value_${Date.now()}`;
      await page.fill('[name="configValue"]', newValue);
      await page.click('[data-testid="submit-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('8.4 刷新配置缓存', async ({ page }) => {
      await systemConfigPage.goto();
      
      await page.click('[data-testid="refresh-cache-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });
  });

  test.describe('9. 文件管理测试', () => {
    test.beforeEach(async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
    });

    test('9.1 上传文件', async ({ page }) => {
      await fileManagementPage.goto();
      
      const fileInput = page.locator('input[type="file"]');
      await fileInput.setInputFiles({
        name: 'test-file.txt',
        mimeType: 'text/plain',
        buffer: Buffer.from('This is a test file')
      });
      
      await page.click('[data-testid="upload-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 10000 });
    });

    test('9.2 查询文件列表', async ({ page }) => {
      await fileManagementPage.goto();
      
      await expect(page.locator('.file-table')).toBeVisible({ timeout: 5000 });
    });

    test('9.3 下载文件', async ({ page }) => {
      await fileManagementPage.goto();
      
      const firstFile = page.locator('.file-row').first();
      const [download] = await Promise.all([
        page.waitForEvent('download'),
        firstFile.locator('[data-testid="download-button"]').click()
      ]);
      
      expect(download).toBeTruthy();
    });

    test('9.4 删除文件', async ({ page }) => {
      await fileManagementPage.goto();
      
      const firstFile = page.locator('.file-row').first();
      await firstFile.locator('[data-testid="delete-button"]').click();
      
      page.on('dialog', dialog => dialog.accept());
      await page.click('[data-testid="confirm-delete-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
    });

    test('9.5 预览文件', async ({ page }) => {
      await fileManagementPage.goto();
      
      const firstFile = page.locator('.file-row').first();
      await firstFile.locator('[data-testid="preview-button"]').click();
      
      await expect(page.locator('.file-preview-modal')).toBeVisible({ timeout: 5000 });
    });
  });

  test.describe('10. 异常场景测试', () => {
    test('10.1 网络错误处理', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      await page.route('**/api/**', route => route.abort('failed'));
      
      await userManagementPage.goto();
      
      await expect(page.locator('.error-message')).toBeVisible({ timeout: 10000 });
    });

    test('10.2 并发操作处理', async ({ page, context }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      const page2 = await context.newPage();
      const loginPage2 = new LoginPage(page2);
      await loginPage2.goto();
      await loginPage2.login('admin', 'Test@123');
      await page2.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      await userManagementPage.goto();
      await page2.goto('/user-management');
      
      await expect(page.locator('.user-table')).toBeVisible({ timeout: 5000 });
      await expect(page2.locator('.user-table')).toBeVisible({ timeout: 5000 });
      
      await page2.close();
    });

    test('10.3 数据验证错误', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      await userManagementPage.goto();
      await userManagementPage.clickCreateUser();
      await userManagementPage.fillUserForm({
        username: '',
        password: '123',
        email: 'invalid-email',
        phone: 'invalid-phone',
        nickname: ''
      });
      await userManagementPage.submitUserForm();
      
      await expect(page.locator('.error-message')).toBeVisible({ timeout: 5000 });
    });

    test('10.4 会话超时处理', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      await page.evaluate(() => {
        localStorage.removeItem('token');
        sessionStorage.clear();
      });
      
      await page.reload();
      
      await expect(page).toHaveURL(/.*login/, { timeout: 5000 });
    });

    test('10.5 权限不足操作', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('normaluser', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      const response = await page.request.post('/api/users', {
        data: {
          username: 'test',
          password: 'test123'
        }
      });
      
      expect(response.status()).toBe(403);
    });
  });

  test.describe('11. 性能测试', () => {
    test('11.1 页面加载性能', async ({ page }) => {
      const startTime = Date.now();
      
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      const loadTime = Date.now() - startTime;
      
      expect(loadTime).toBeLessThan(5000);
    });

    test('11.2 大数据量查询性能', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      const startTime = Date.now();
      
      await operationLogPage.goto();
      await expect(page.locator('.log-table')).toBeVisible({ timeout: 5000 });
      
      const queryTime = Date.now() - startTime;
      
      expect(queryTime).toBeLessThan(3000);
    });

    test('11.3 并发请求处理', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      const requests = Array(10).fill(null).map(() => 
        page.request.get('/api/users')
      );
      
      const responses = await Promise.all(requests);
      
      responses.forEach(response => {
        expect(response.status()).toBe(200);
      });
    });
  });

  test.describe('12. 数据一致性测试', () => {
    test('12.1 创建后立即查询数据一致性', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      const timestamp = Date.now();
      const username = `consistency_test_${timestamp}`;
      
      await userManagementPage.goto();
      await userManagementPage.clickCreateUser();
      await userManagementPage.fillUserForm({
        username: username,
        password: 'Test@123',
        email: `${username}@test.com`,
        phone: '13800138000',
        nickname: `一致性测试用户${timestamp}`
      });
      await userManagementPage.submitUserForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      await userManagementPage.searchUser(username);
      const userRow = page.locator('.user-row').first();
      
      await expect(userRow).toContainText(username);
      await expect(userRow).toContainText(`${username}@test.com`);
      await expect(userRow).toContainText('13800138000');
    });

    test('12.2 更新后数据一致性', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      await userManagementPage.goto();
      
      const firstUser = page.locator('.user-row').first();
      await firstUser.locator('[data-testid="edit-button"]').click();
      
      const newEmail = `updated_${Date.now()}@test.com`;
      const newPhone = `139${Date.now()}`.slice(0, 11);
      
      await page.fill('[name="email"]', newEmail);
      await page.fill('[name="phone"]', newPhone);
      await page.click('[data-testid="submit-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      await page.reload();
      
      const updatedUser = page.locator('.user-row').first();
      await expect(updatedUser).toContainText(newEmail);
      await expect(updatedUser).toContainText(newPhone);
    });

    test('12.3 删除后数据不可见', async ({ page }) => {
      await loginPage.goto();
      await loginPage.login('admin', 'Test@123');
      await page.waitForURL(/\/(dashboard|\/)$/, { timeout: 10000 });
      
      const timestamp = Date.now();
      const username = `delete_test_${timestamp}`;
      
      await userManagementPage.goto();
      await userManagementPage.clickCreateUser();
      await userManagementPage.fillUserForm({
        username: username,
        password: 'Test@123',
        email: `${username}@test.com`,
        phone: '13800138000',
        nickname: `删除测试用户${timestamp}`
      });
      await userManagementPage.submitUserForm();
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      await userManagementPage.searchUser(username);
      const userRow = page.locator('.user-row').first();
      await userRow.locator('[data-testid="delete-button"]').click();
      
      page.on('dialog', dialog => dialog.accept());
      await page.click('[data-testid="confirm-delete-button"]');
      
      await expect(page.locator('.success-message')).toBeVisible({ timeout: 5000 });
      
      await userManagementPage.searchUser(username);
      await expect(page.locator('.user-row')).toHaveCount(0, { timeout: 5000 });
    });
  });
});
