import { test, expect } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { UserManagementPage } from './pages/UserManagementPage';
import { generateTestUser } from './fixtures/test-data';

test.describe('用户管理 E2E 测试', () => {
  let loginPage: LoginPage;
  let dashboardPage: DashboardPage;
  let userManagementPage: UserManagementPage;

  test.beforeEach(async ({ page }) => {
    loginPage = new LoginPage(page);
    dashboardPage = new DashboardPage(page);
    userManagementPage = new UserManagementPage(page);
    
    // 清理localStorage
    await page.goto('/');
    await page.evaluate(() => localStorage.clear());
    
    // 重新登录
    await loginPage.goto();
    await loginPage.login('e2e_test_user', 'admin123');
  });

  test('创建用户完整流程', async ({ page }) => {
    await dashboardPage.navigateToUserManagement();
    
    await userManagementPage.clickCreateUser();
    
    const timestamp = Date.now();
    const userData = {
      username: `testuser_${timestamp}`,
      nickname: `测试用户${timestamp}`,
      email: `test_${timestamp}@example.com`,
      phone: '13800138000',
      password: 'Test123!@#',
      confirmPassword: 'Test123!@#',
    };
    
    await userManagementPage.fillUserForm(userData);
    await userManagementPage.submitForm();
    
    await expect(userManagementPage.successMessage).toBeVisible();
    await page.waitForTimeout(3000);
    
    const userCount = await userManagementPage.getUserCount();
    console.log(`User count after creation: ${userCount}`);
    
    await page.reload();
    await page.waitForLoadState('networkidle');
    await page.waitForTimeout(2000);
    
    const userCountAfterReload = await userManagementPage.getUserCount();
    console.log(`User count after reload: ${userCountAfterReload}`);
    
    await expect(userManagementPage.table).toContainText(userData.username);
  });

  test('编辑用户流程', async ({ page }) => {
    await dashboardPage.navigateToUserManagement();
    
    await userManagementPage.editUser(1);
    
    await page.fill('input[name="email"]', 'updated@example.com');
    
    await userManagementPage.submitForm();
    
    await expect(userManagementPage.successMessage).toBeVisible();
    await expect(userManagementPage.table).toContainText('updated@example.com');
  });

  test('删除用户流程', async ({ page }) => {
    await dashboardPage.navigateToUserManagement();
    
    // 先创建一个测试用户
    await userManagementPage.clickCreateUser();
    const timestamp = Date.now();
    const userData = {
      username: `delete_test_${timestamp}`,
      nickname: `待删除用户${timestamp}`,
      email: `delete_${timestamp}@example.com`,
      phone: '13800138000',
      password: 'Test123!@#',
      confirmPassword: 'Test123!@#',
    };
    await userManagementPage.fillUserForm(userData);
    await userManagementPage.submitForm();
    await expect(userManagementPage.successMessage).toBeVisible();
    
    // 等待表格刷新
    await page.waitForTimeout(2000);
    
    // 搜索刚创建的用户
    await userManagementPage.search(userData.username);
    await page.waitForTimeout(1000);
    
    // 删除该用户
    await userManagementPage.deleteUser(1);
    await userManagementPage.confirmDelete();
    
    await expect(userManagementPage.successMessage).toBeVisible();
    
    // 验证用户已被删除
    await userManagementPage.reload();
    await userManagementPage.search(userData.username);
    await expect(userManagementPage.table).not.toContainText(userData.username);
  });

  test('搜索用户功能', async ({ page }) => {
    await dashboardPage.navigateToUserManagement();
    
    await userManagementPage.search('admin');
    
    await expect(userManagementPage.table).toContainText('admin');
  });

  test('分页功能', async ({ page }) => {
    await dashboardPage.navigateToUserManagement();
    
    const currentPage = await userManagementPage.getCurrentPage();
    expect(currentPage).toBe('1');
    
    await userManagementPage.nextPage();
    
    const newPage = await userManagementPage.getCurrentPage();
    expect(newPage).toBe('2');
  });

  test('批量删除用户', async ({ page }) => {
    await dashboardPage.navigateToUserManagement();
    
    await page.check('table tbody tr:nth-child(1) input[type="checkbox"]');
    await page.check('table tbody tr:nth-child(2) input[type="checkbox"]');
    
    await page.click('button:has-text("批量删除")');
    await page.click('.confirm-dialog .confirm-button');
    
    await expect(userManagementPage.successMessage).toBeVisible();
  });

  test('用户状态切换', async ({ page }) => {
    await dashboardPage.navigateToUserManagement();
    
    await page.click('table tbody tr:first-child .status-toggle');
    
    await expect(userManagementPage.successMessage).toBeVisible();
  });

  test('导出用户数据', async ({ page }) => {
    await dashboardPage.navigateToUserManagement();
    
    const downloadPromise = page.waitForEvent('download');
    await page.click('button:has-text("导出")');
    const download = await downloadPromise;
    
    expect(download.suggestedFilename()).toMatch(/users.*\.xlsx/);
  });
});
