import { test, expect } from '@playwright/test';

test.describe('UAT阶段二：用户管理功能验证', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/');
    await page.waitForLoadState('networkidle');
    
    const usernameInput = page.locator('input[type="text"]').first();
    const passwordInput = page.locator('input[type="password"]').first();
    const loginButton = page.locator('button:has-text("登录")');
    
    await usernameInput.fill('admin');
    await passwordInput.fill('admin123');
    await loginButton.click();
    
    await page.waitForURL('**/dashboard', { timeout: 30000 });
    await page.waitForLoadState('networkidle');
  });

  test('UAT-USER-001: 用户列表加载', async ({ page }) => {
    const systemMenu = page.locator('.el-sub-menu__title:has-text("系统管理")');
    await systemMenu.click();
    await page.waitForTimeout(1000);
    
    await page.click('text=用户管理');
    await page.waitForURL('**/users', { timeout: 30000 });
    await page.waitForLoadState('networkidle');
    
    await expect(page.locator('.el-table')).toBeVisible({ timeout: 10000 });
    await expect(page.locator('.el-table__body-wrapper')).toBeVisible();
  });

  test('UAT-USER-002: 用户搜索功能', async ({ page }) => {
    const systemMenu = page.locator('.el-sub-menu__title:has-text("系统管理")');
    await systemMenu.click();
    await page.waitForTimeout(1000);
    
    await page.click('text=用户管理');
    await page.waitForURL('**/users', { timeout: 30000 });
    await page.waitForLoadState('networkidle');
    
    const searchInput = page.locator('input[placeholder*="搜索"]').first();
    if (await searchInput.isVisible()) {
      await searchInput.fill('admin');
      await page.waitForTimeout(1000);
      
      await expect(page.locator('.el-table')).toBeVisible();
    }
  });

  test('UAT-USER-003: 新增用户表单验证', async ({ page }) => {
    const systemMenu = page.locator('.el-sub-menu__title:has-text("系统管理")');
    await systemMenu.click();
    await page.waitForTimeout(1000);
    
    await page.click('text=用户管理');
    await page.waitForURL('**/users', { timeout: 30000 });
    await page.waitForLoadState('networkidle');
    
    const addButton = page.locator('button:has-text("新增用户")').first();
    if (await addButton.isVisible()) {
      await addButton.click();
      await page.waitForTimeout(500);
      
      await expect(page.locator('.el-dialog')).toBeVisible();
      
      const confirmButton = page.locator('.el-dialog button:has-text("确定")');
      if (await confirmButton.isVisible()) {
        await confirmButton.click();
        await page.waitForTimeout(500);
        
        const formErrors = page.locator('.el-form-item__error');
        const errorCount = await formErrors.count();
        expect(errorCount).toBeGreaterThan(0);
      }
    }
  });
});
