import { expect, test } from '../fixtures/auth';

test.describe('系统管理 / 权限配置', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/system/permission');
    await page.getByText('菜单树', { exact: true }).waitFor();
  });

  test('展示菜单权限与详情', async ({ page }) => {
    await expect(page.getByRole('tab', { name: '菜单权限' })).toBeVisible();
    await expect(page.getByText('菜单树', { exact: true })).toBeVisible();
    await expect(page.getByText('菜单详情', { exact: true })).toBeVisible();
    await expect(page.getByLabel('菜单名称')).toHaveValue('用户管理');
    await expect(page.getByLabel('权限标识')).toHaveValue('system:user:view');
  });

  test('可保存菜单详情', async ({ page }) => {
    await page.getByLabel('菜单名称').fill('用户中心');
    await page.getByRole('button', { name: '保 存' }).click();
    await expect(page.getByText('菜单已保存')).toBeVisible();
    await expect(page.getByRole('tree').getByText('用户中心')).toBeVisible();

    await page.getByRole('tab', { name: '按钮权限' }).click();
    const buttonPanel = page.getByRole('tabpanel', { name: '按钮权限' });
    await expect(buttonPanel.getByRole('row').filter({ hasText: 'system:user:add' })).toContainText(
      '系统管理 / 用户中心',
    );
  });

  test('可新增同级菜单', async ({ page }) => {
    await page.getByRole('button', { name: '+ 新增同级' }).click();
    await expect(page.getByText('已新增同级菜单')).toBeVisible();
    await expect(page.getByLabel('菜单名称')).toHaveValue('新菜单');
  });

  test('可管理按钮权限', async ({ page }) => {
    await page.getByRole('tab', { name: '按钮权限' }).click();
    const buttonPanel = page.getByRole('tabpanel', { name: '按钮权限' });
    await expect(buttonPanel.getByRole('button', { name: '新增按钮权限' })).toBeVisible();
    await expect(buttonPanel.getByText('system:user:add')).toBeVisible();

    await buttonPanel.getByRole('button', { name: '新增按钮权限' }).click();
    const dialog = page.getByRole('dialog', { name: '新增按钮权限' });
    await dialog.getByLabel('权限名称').fill('导入');
    await dialog.getByLabel('权限码').fill('system:user:import');
    await dialog.getByRole('button', { name: '保 存' }).click();

    await expect(buttonPanel.getByText('system:user:import')).toBeVisible();
    await expect(page.getByText('按钮权限已添加')).toBeVisible();
  });

  test('删除菜单时同步清理按钮权限', async ({ page }) => {
    await page.getByRole('button', { name: '删除' }).first().click();
    await page.getByRole('button', { name: '确 定' }).click();
    await expect(page.getByText('菜单已删除')).toBeVisible();

    await page.getByRole('tab', { name: '按钮权限' }).click();
    const buttonPanel = page.getByRole('tabpanel', { name: '按钮权限' });
    await expect(buttonPanel.getByText('system:user:add')).toHaveCount(0);
    await expect(buttonPanel.getByText('system:user:edit')).toHaveCount(0);
  });
});
