import { test, expect } from '@playwright/test';
import { LoginPage } from './pages/LoginPage';
import { DashboardPage } from './pages/DashboardPage';
import { UserManagementPage } from './pages/UserManagementPage';
import { RoleManagementPage } from './pages/RoleManagementPage';

test.describe('完整业务流程 E2E 测试', () => {
  let loginPage: LoginPage;
  let dashboardPage: DashboardPage;
  let userManagementPage: UserManagementPage;
  let roleManagementPage: RoleManagementPage;

  test.beforeEach(async ({ page }) => {
    loginPage = new LoginPage(page);
    dashboardPage = new DashboardPage(page);
    userManagementPage = new UserManagementPage(page);
    roleManagementPage = new RoleManagementPage(page);
  });

  test('完整用户管理流程：登录 -> 创建角色 -> 创建用户 -> 分配角色 -> 删除', async ({ page }) => {
    const timestamp = Date.now();

    await test.step('1. 管理员登录', async () => {
      await loginPage.goto();
      await loginPage.login('admin', 'admin123');
      await expect(page).toHaveURL(/.*dashboard/);
    });

    await test.step('2. 创建新角色', async () => {
      await dashboardPage.navigateToRoleManagement();
      await roleManagementPage.clickCreateRole();

      const roleData = {
        roleName: `测试角色_${timestamp}`,
        roleKey: `test_role_${timestamp}`,
        roleSort: '1',
        status: '1',
        remark: `测试角色备注_${timestamp}`,
      };

      await roleManagementPage.fillRoleForm(roleData);
      await roleManagementPage.submitForm();
      await expect(roleManagementPage.successMessage).toBeVisible();
      await expect(roleManagementPage.table).toContainText(roleData.roleName);
    });

    await test.step('3. 为角色分配权限', async () => {
      await dashboardPage.navigateToRoleManagement();
      await roleManagementPage.openPermissionDialog(1);
      await roleManagementPage.selectPermission('user:view');
      await roleManagementPage.selectPermission('user:create');
      await roleManagementPage.selectPermission('user:edit');
      await roleManagementPage.savePermissions();
      await expect(roleManagementPage.successMessage).toBeVisible();
    });

    await test.step('4. 创建新用户', async () => {
      await dashboardPage.navigateToUserManagement();
      await userManagementPage.clickCreateUser();

      const userData = {
        username: `testuser_${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 expect(userManagementPage.table).toContainText(userData.username);
    });

    await test.step('5. 为用户分配角色', async () => {
      await dashboardPage.navigateToUserManagement();
      await userManagementPage.editUser(1);
      await page.click('.role-select');
      await page.click('option:has-text("测试角色")');
      await userManagementPage.submitForm();
      await expect(userManagementPage.successMessage).toBeVisible();
    });

    await test.step('6. 验证用户登录', async () => {
      await loginPage.logout();
      await loginPage.goto();
      await loginPage.login(`testuser_${timestamp}`, 'Test123!@#');
      await expect(page).toHaveURL(/.*dashboard/);
      const username = await dashboardPage.getUsername();
      expect(username).toContain(`testuser_${timestamp}`);
    });

    await test.step('7. 管理员删除测试用户', async () => {
      await loginPage.logout();
      await loginPage.goto();
      await loginPage.login('admin', 'admin123');
      await dashboardPage.navigateToUserManagement();
      await userManagementPage.search(`testuser_${timestamp}`);
      await userManagementPage.deleteUser(1);
      await userManagementPage.confirmDelete();
      await expect(userManagementPage.successMessage).toBeVisible();
    });

    await test.step('8. 管理员删除测试角色', async () => {
      await dashboardPage.navigateToRoleManagement();
      await roleManagementPage.search(`测试角色_${timestamp}`);
      await roleManagementPage.deleteRole(1);
      await roleManagementPage.confirmDelete();
      await expect(roleManagementPage.successMessage).toBeVisible();
    });
  });

  test('完整菜单管理流程：创建菜单 -> 构建菜单树 -> 删除菜单', async ({ page }) => {
    const timestamp = Date.now();

    await test.step('1. 管理员登录', async () => {
      await loginPage.goto();
      await loginPage.login('admin', 'admin123');
      await expect(page).toHaveURL(/.*dashboard/);
    });

    await test.step('2. 创建父级菜单', async () => {
      await dashboardPage.navigateToMenuManagement();
      await page.click('text=新增菜单');

      await page.fill('input[name="menuName"]', `父级菜单_${timestamp}`);
      await page.fill('input[name="parentId"]', '0');
      await page.fill('input[name="orderNum"]', '1');
      await page.selectOption('select[name="menuType"]', 'M');
      await page.fill('input[name="component"]', `parent_${timestamp}`);
      await page.fill('input[name="perms"]', `parent:view_${timestamp}`);
      await page.selectOption('select[name="status"]', '1');

      await page.click('button[type="submit"]');
      await expect(page.locator('.success-message')).toBeVisible();
    });

    await test.step('3. 创建子级菜单', async () => {
      await dashboardPage.navigateToMenuManagement();
      await page.click('text=新增菜单');

      await page.fill('input[name="menuName"]', `子级菜单_${timestamp}`);
      await page.fill('input[name="parentId"]', '1');
      await page.fill('input[name="orderNum"]', '1');
      await page.selectOption('select[name="menuType"]', 'C');
      await page.fill('input[name="component"]', `child_${timestamp}`);
      await page.fill('input[name="perms"]', `child:view_${timestamp}`);
      await page.selectOption('select[name="status"]', '1');

      await page.click('button[type="submit"]');
      await expect(page.locator('.success-message')).toBeVisible();
    });

    await test.step('4. 验证菜单树结构', async () => {
      await dashboardPage.navigateToMenuManagement();
      await expect(page.locator('table')).toContainText(`父级菜单_${timestamp}`);
      await expect(page.locator('table')).toContainText(`子级菜单_${timestamp}`);
    });

    await test.step('5. 删除子级菜单', async () => {
      await dashboardPage.navigateToMenuManagement();
      await page.click('table tbody tr:has-text("子级菜单") .delete-button');
      await page.click('.confirm-dialog .confirm-button');
      await expect(page.locator('.success-message')).toBeVisible();
    });

    await test.step('6. 删除父级菜单', async () => {
      await dashboardPage.navigateToMenuManagement();
      await page.click('table tbody tr:has-text("父级菜单") .delete-button');
      await page.click('.confirm-dialog .confirm-button');
      await expect(page.locator('.success-message')).toBeVisible();
    });
  });

  test('完整系统配置流程：修改配置 -> 验证配置 -> 恢复默认', async ({ page }) => {
    const timestamp = Date.now();

    await test.step('1. 管理员登录', async () => {
      await loginPage.goto();
      await loginPage.login('admin', 'admin123');
      await expect(page).toHaveURL(/.*dashboard/);
    });

    await test.step('2. 修改系统配置', async () => {
      await dashboardPage.navigateToSystemConfig();
      await page.click('table tbody tr:first-child .edit-button');
      await page.fill('input[name="configValue"]', `test_value_${timestamp}`);
      await page.click('button[type="submit"]');
      await expect(page.locator('.success-message')).toBeVisible();
    });

    await test.step('3. 验证配置修改', async () => {
      await dashboardPage.navigateToSystemConfig();
      await expect(page.locator('table')).toContainText(`test_value_${timestamp}`);
    });

    await test.step('4. 恢复默认配置', async () => {
      await dashboardPage.navigateToSystemConfig();
      await page.click('table tbody tr:first-child .edit-button');
      await page.fill('input[name="configValue"]', 'default_value');
      await page.click('button[type="submit"]');
      await expect(page.locator('.success-message')).toBeVisible();
    });
  });

  test('完整权限控制流程：创建受限角色 -> 创建用户 -> 验证权限限制', async ({ page }) => {
    const timestamp = Date.now();

    await test.step('1. 管理员登录', async () => {
      await loginPage.goto();
      await loginPage.login('admin', 'admin123');
      await expect(page).toHaveURL(/.*dashboard/);
    });

    await test.step('2. 创建受限角色', async () => {
      await dashboardPage.navigateToRoleManagement();
      await roleManagementPage.clickCreateRole();

      const roleData = {
        roleName: `受限角色_${timestamp}`,
        roleKey: `limited_role_${timestamp}`,
        roleSort: '1',
        status: '1',
        remark: '仅查看权限',
      };

      await roleManagementPage.fillRoleForm(roleData);
      await roleManagementPage.submitForm();
      await expect(roleManagementPage.successMessage).toBeVisible();
    });

    await test.step('3. 为受限角色分配仅查看权限', async () => {
      await dashboardPage.navigateToRoleManagement();
      await roleManagementPage.openPermissionDialog(1);
      await roleManagementPage.selectPermission('user:view');
      await roleManagementPage.savePermissions();
      await expect(roleManagementPage.successMessage).toBeVisible();
    });

    await test.step('4. 创建受限用户', async () => {
      await dashboardPage.navigateToUserManagement();
      await userManagementPage.clickCreateUser();

      const userData = {
        username: `limiteduser_${timestamp}`,
        email: `limited_${timestamp}@example.com`,
        phone: '13800138000',
        password: 'Test123!@#',
        confirmPassword: 'Test123!@#',
      };

      await userManagementPage.fillUserForm(userData);
      await userManagementPage.submitForm();
      await expect(userManagementPage.successMessage).toBeVisible();
    });

    await test.step('5. 验证受限用户权限', async () => {
      await loginPage.logout();
      await loginPage.goto();
      await loginPage.login(`limiteduser_${timestamp}`, 'Test123!@#');
      await expect(page).toHaveURL(/.*dashboard/);

      await dashboardPage.navigateToUserManagement();
      await expect(page).toHaveURL(/.*users/);

      await page.goto('/users/create');
      await expect(page).toHaveURL(/.*dashboard/);
    });
  });
});
