import { TIMEOUTS } from '../../utils/timeouts';
import { test, expect } from '../../utils/test-setup';

test.describe('公司创建功能', () => {
  test.beforeEach(async ({ adminLoginPage, companyManagementPage }) => {
    // 以管理员身份登录后台
    await adminLoginPage.goto();
    await adminLoginPage.login('admin', 'admin123');
    await adminLoginPage.expectLoginSuccess();
    await companyManagementPage.goto();
  });

  test.describe('基本创建流程测试', () => {
    test('应该成功创建公司（不选择平台）', async ({ companyManagementPage }) => {
      // 生成唯一公司名称
      const timestamp = Date.now();
      const companyName = `测试公司_${timestamp}`;

      // 创建公司（不选择平台）
      const result = await companyManagementPage.createCompany({
        companyName,
      });

      // 验证 API 响应成功
      expect(result.responses).toBeDefined();
      expect(result.responses?.length).toBeGreaterThan(0);
      const createResponse = result.responses?.find(r => r.url.includes('createCompany'));
      expect(createResponse?.ok).toBe(true);

      // 验证公司出现在列表中
      await expect(async () => {
        const exists = await companyManagementPage.companyExists(companyName);
        expect(exists).toBe(true);
      }).toPass({ timeout: TIMEOUTS.DIALOG });

      // 清理测试数据
      const deleteResult = await companyManagementPage.deleteCompany(companyName);
      expect(deleteResult).toBe(true);

      // 验证公司已被删除
      const existsAfterDelete = await companyManagementPage.companyExists(companyName);
      expect(existsAfterDelete).toBe(false);
    });

    test('创建后公司应该出现在列表中', async ({ companyManagementPage }) => {
      const timestamp = Date.now();
      const companyName = `测试公司_消息_${timestamp}`;

      // 创建公司
      await companyManagementPage.createCompany({
        companyName,
      });

      // 验证公司出现在列表中
      const exists = await companyManagementPage.companyExists(companyName);
      expect(exists).toBe(true);

      // 清理
      await companyManagementPage.deleteCompany(companyName);
    });
  });

  test.describe('完整表单字段测试', () => {
    test('应该成功创建公司（选择平台并填写所有字段）', async ({ platformManagementPage, companyManagementPage }) => {
      const timestamp = Date.now();

      // 首先创建测试平台
      const platformName = `测试平台_${timestamp}`;
      await platformManagementPage.goto();
      await platformManagementPage.createPlatform({
        platformName,
        contactPerson: '测试联系人',
        contactPhone: '13800138000',
        contactEmail: `test_${timestamp}@example.com`,
      });

      // 验证平台创建成功
      expect(await platformManagementPage.platformExists(platformName)).toBe(true);

      // 返回公司管理页面
      await companyManagementPage.goto();

      // 创建公司（选择平台并填写所有字段）
      const companyName = `测试公司_${timestamp}`;
      const result = await companyManagementPage.createCompany({
        companyName,
        contactPerson: '张三',
        contactPhone: '13900139000',
        contactEmail: `company_${timestamp}@example.com`,
        address: '北京市朝阳区',
      }, platformName);

      // 验证 API 响应成功
      const createResponse = result.responses?.find(r => r.url.includes('createCompany'));
      expect(createResponse?.ok).toBe(true);

      // 验证公司出现在列表中
      await expect(async () => {
        const exists = await companyManagementPage.companyExists(companyName);
        expect(exists).toBe(true);
      }).toPass({ timeout: TIMEOUTS.DIALOG });

      // 清理测试数据（先删除公司，再删除平台）
      await companyManagementPage.deleteCompany(companyName);
      await platformManagementPage.goto();
      await platformManagementPage.deletePlatform(platformName);
    });

    test('应该保存所有填写的字段数据', async ({ platformManagementPage, companyManagementPage }) => {
      const timestamp = Date.now();

      // 创建测试平台
      const platformName = `完整测试平台_${timestamp}`;
      await platformManagementPage.goto();
      await platformManagementPage.createPlatform({
        platformName,
        contactPerson: `平台联系人_${timestamp}`,
        contactPhone: '13800138000',
        contactEmail: `platform_${timestamp}@example.com`,
      });

      // 返回公司管理页面
      await companyManagementPage.goto();

      // 创建公司（填写所有字段）
      const companyName = `完整测试公司_${timestamp}`;
      const result = await companyManagementPage.createCompany({
        companyName,
        contactPerson: `测试联系人_${timestamp}`,
        contactPhone: '13800138000',
        contactEmail: `test_${timestamp}@example.com`,
        address: '上海市浦东新区',
      }, platformName);

      // 验证创建成功
      const createResponse = result.responses?.find(r => r.url.includes('createCompany'));
      expect(createResponse?.ok).toBe(true);

      // 验证公司出现在列表中
      const exists = await companyManagementPage.companyExists(companyName);
      expect(exists).toBe(true);

      // 清理
      await companyManagementPage.deleteCompany(companyName);
      await platformManagementPage.goto();
      await platformManagementPage.deletePlatform(platformName);
    });

    test('应该支持不同的联系人信息', async ({ platformManagementPage, companyManagementPage }) => {
      const timestamp = Date.now();

      // 创建测试平台
      const platformName = `联系人测试平台_${timestamp}`;
      await platformManagementPage.goto();
      await platformManagementPage.createPlatform({
        platformName,
        contactPerson: '平台联系人',
        contactPhone: '15011112222',
        contactEmail: `platform_${timestamp}@company.com`,
      });

      // 返回公司管理页面
      await companyManagementPage.goto();

      // 创建公司（不同的联系人信息）
      const companyName = `联系人测试公司_${timestamp}`;
      const result = await companyManagementPage.createCompany({
        companyName,
        contactPerson: `李四_${timestamp}`,
        contactPhone: '15011112222',
        contactEmail: `lisi_${timestamp}@company.com`,
        address: '深圳市南山区',
      }, platformName);

      // 验证 API 响应成功
      const createResponse = result.responses?.find(r => r.url.includes('createCompany'));
      expect(createResponse?.ok).toBe(true);

      // 验证公司存在于列表中
      const exists = await companyManagementPage.companyExists(companyName);
      expect(exists).toBe(true);

      // 清理
      await companyManagementPage.deleteCompany(companyName);
      await platformManagementPage.goto();
      await platformManagementPage.deletePlatform(platformName);
    });
  });

  test.describe('表单验证测试', () => {
    test('未填写公司名称时应显示内联验证错误', async ({ companyManagementPage }) => {
      // 打开创建对话框
      await companyManagementPage.openCreateDialog();

      // 不填写任何字段，直接尝试提交
      const submitButton = companyManagementPage.page.locator('[data-testid="submit-create-company-button"]');
      await submitButton.click();

      // 验证对话框仍然打开（表单验证阻止了提交）
      const dialog = companyManagementPage.page.locator('[role="dialog"]');
      await expect(dialog).toBeVisible();

      // 关闭对话框
      await companyManagementPage.cancelDialog();
    });

    test('表单应该正确验证邮箱格式', async ({ companyManagementPage }) => {
      const timestamp = Date.now();
      const companyName = `邮箱测试公司_${timestamp}`;

      // 打开创建对话框
      await companyManagementPage.openCreateDialog();

      // 填写公司名称
      await companyManagementPage.companyNameInput.fill(companyName);

      // 填写无效邮箱格式
      await companyManagementPage.contactEmailInput.fill('invalid-email-format');

      // 尝试提交
      const submitButton = companyManagementPage.page.locator('[data-testid="submit-create-company-button"]');
      await submitButton.click();

      // 验证对话框仍然打开（表单验证阻止了提交）
      const dialog = companyManagementPage.page.locator('[role="dialog"]');
      await expect(dialog).toBeVisible();

      // 关闭对话框
      await companyManagementPage.cancelDialog();
    });
  });

  test.describe('取消和关闭操作测试', () => {
    test('应该能取消创建公司操作', async ({ companyManagementPage }) => {
      const timestamp = Date.now();
      const companyName = `取消测试公司_${timestamp}`;

      // 打开创建对话框并填写表单
      await companyManagementPage.openCreateDialog();
      await companyManagementPage.companyNameInput.fill(companyName);

      // 点击取消按钮
      await companyManagementPage.cancelDialog();

      // 验证对话框关闭
      const dialog = companyManagementPage.page.locator('[role="dialog"]');
      await expect(dialog).not.toBeVisible();

      // 验证公司没有被创建
      const exists = await companyManagementPage.companyExists(companyName);
      expect(exists).toBe(false);
    });

    test('应该能通过关闭对话框取消创建', async ({ companyManagementPage }) => {
      const timestamp = Date.now();
      const companyName = `关闭测试公司_${timestamp}`;

      // 打开创建对话框并填写表单
      await companyManagementPage.openCreateDialog();
      await companyManagementPage.companyNameInput.fill(companyName);

      // 按 ESC 键关闭对话框
      await companyManagementPage.page.keyboard.press('Escape');

      // 等待对话框关闭
      await companyManagementPage.waitForDialogClosed();

      // 验证公司没有出现在列表中
      const exists = await companyManagementPage.companyExists(companyName);
      expect(exists).toBe(false);
    });

    test('应该能通过点击对话框外部取消创建', async ({ companyManagementPage }) => {
      const timestamp = Date.now();
      const companyName = `外部点击测试公司_${timestamp}`;

      // 打开创建对话框并填写表单
      await companyManagementPage.openCreateDialog();
      await companyManagementPage.companyNameInput.fill(companyName);

      // 点击对话框外部区域（使用 Radix UI Dialog overlay）
      // Radix Dialog 使用 data-radix-dialog-overlay 或 [data-state="open"] 作为 backdrop
      const backdrop = companyManagementPage.page.locator('[data-radix-dialog-overlay]').or(
        companyManagementPage.page.locator('[data-state="open"][role="presentation"]')
      );

      // 验证 backdrop 存在
      const backdropCount = await backdrop.count();
      if (backdropCount > 0) {
        // 点击 backdrop 关闭对话框
        await backdrop.first().click();
        await companyManagementPage.waitForDialogClosed();
      } else {
        // 如果找不到 backdrop（某些浏览器行为），使用 ESC 键作为备选
        await companyManagementPage.page.keyboard.press('Escape');
        await companyManagementPage.waitForDialogClosed();
      }

      // 验证公司没有出现在列表中
      const exists = await companyManagementPage.companyExists(companyName);
      expect(exists).toBe(false);
    });
  });

  test.describe('对话框元素验证', () => {
    test('应该显示创建公司对话框的所有字段', async ({ companyManagementPage }) => {
      // 打开创建对话框
      await companyManagementPage.openCreateDialog();

      // 验证对话框存在
      const dialog = companyManagementPage.page.locator('[role="dialog"]');
      await expect(dialog).toBeVisible();

      // 验证平台选择器存在（可选字段）
      await expect(companyManagementPage.platformSelector).toBeVisible();

      // 验证公司名称输入框存在（必填字段）
      await expect(companyManagementPage.companyNameInput).toBeVisible();

      // 验证可选字段输入框存在
      await expect(companyManagementPage.contactPersonInput).toBeVisible();
      await expect(companyManagementPage.contactPhoneInput).toBeVisible();
      await expect(companyManagementPage.contactEmailInput).toBeVisible();
      await expect(companyManagementPage.addressInput).toBeVisible();

      // 验证按钮存在（使用 role 选择器，因为 data-testid 可能不存在）
      await expect(companyManagementPage.page.getByRole('button', { name: '创建' })).toBeVisible();
      await expect(companyManagementPage.cancelButton).toBeVisible();

      // 关闭对话框
      await companyManagementPage.cancelDialog();
    });
  });

  test.describe('数据唯一性测试', () => {
    test('不同测试应该使用不同的公司名称', async ({ companyManagementPage }) => {
      // 生成两个不同的公司名称
      const timestamp = Date.now();
      const companyName1 = `唯一性测试公司_A_${timestamp}`;
      const companyName2 = `唯一性测试公司_B_${timestamp}`;

      // 创建第一个公司
      await companyManagementPage.createCompany({
        companyName: companyName1,
      });

      expect(await companyManagementPage.companyExists(companyName1)).toBe(true);

      // 创建第二个公司
      await companyManagementPage.createCompany({
        companyName: companyName2,
      });

      expect(await companyManagementPage.companyExists(companyName2)).toBe(true);

      // 清理两个公司
      await companyManagementPage.deleteCompany(companyName1);
      await companyManagementPage.deleteCompany(companyName2);

      // 验证清理成功
      expect(await companyManagementPage.companyExists(companyName1)).toBe(false);
      expect(await companyManagementPage.companyExists(companyName2)).toBe(false);
    });

    test('同一平台下公司名称应该唯一', async ({ platformManagementPage, companyManagementPage }) => {
      const timestamp = Date.now();

      // 创建测试平台
      const platformName = `唯一性测试平台_${timestamp}`;
      await platformManagementPage.goto();
      await platformManagementPage.createPlatform({
        platformName,
        contactPerson: '测试联系人',
        contactPhone: '13800138000',
        contactEmail: `test_${timestamp}@example.com`,
      });

      // 返回公司管理页面
      await companyManagementPage.goto();

      // 创建第一个公司
      const companyName = `同平台公司_${timestamp}`;
      await companyManagementPage.createCompany({
        companyName,
      }, platformName);

      expect(await companyManagementPage.companyExists(companyName)).toBe(true);

      // 尝试创建同名公司（同一平台）
      const result = await companyManagementPage.createCompany({
        companyName,
      }, platformName);

      // 验证创建失败或显示错误
      // 根据后端行为，可能返回错误或显示验证消息
      if (result.hasError || !result.success) {
        // 预期行为：创建失败
        expect(result.hasError || !result.success).toBe(true);
      }

      // 验证列表中只有一个同名公司（没有重复创建）
      const companyRow = companyManagementPage.companyTable.locator('tbody tr').filter({ hasText: companyName });
      const count = await companyRow.count();
      expect(count).toBe(1);

      // 清理
      await companyManagementPage.deleteCompany(companyName);
      await platformManagementPage.goto();
      await platformManagementPage.deletePlatform(platformName);
    });
  });

  test.describe('测试后清理验证', () => {
    test('应该能成功删除测试创建的公司', async ({ companyManagementPage }) => {
      const timestamp = Date.now();
      const companyName = `清理测试公司_${timestamp}`;

      // 创建公司
      await companyManagementPage.createCompany({
        companyName,
        contactPerson: `清理联系人_${timestamp}`,
        contactPhone: '13800003333',
        contactEmail: `cleanup_${timestamp}@test.com`,
      });

      // 验证公司存在
      expect(await companyManagementPage.companyExists(companyName)).toBe(true);

      // 删除公司
      const deleteResult = await companyManagementPage.deleteCompany(companyName);
      expect(deleteResult).toBe(true);

      // 验证公司已被删除
      await expect(async () => {
        const exists = await companyManagementPage.companyExists(companyName);
        expect(exists).toBe(false);
      }).toPass({ timeout: TIMEOUTS.DIALOG });
    });

    test('应该能成功删除测试创建的平台和公司', async ({ platformManagementPage, companyManagementPage }) => {
      const timestamp = Date.now();

      // 创建测试平台
      const platformName = `清理测试平台_${timestamp}`;
      await platformManagementPage.goto();
      await platformManagementPage.createPlatform({
        platformName,
        contactPerson: '测试联系人',
        contactPhone: '13800138000',
        contactEmail: `test_${timestamp}@example.com`,
      });

      // 返回公司管理页面
      await companyManagementPage.goto();

      // 创建公司
      const companyName = `清理测试公司_${timestamp}`;
      await companyManagementPage.createCompany({
        companyName,
      }, platformName);

      // 验证公司存在
      expect(await companyManagementPage.companyExists(companyName)).toBe(true);

      // 清理（先删除公司，再删除平台）
      await companyManagementPage.deleteCompany(companyName);
      await platformManagementPage.goto();
      await platformManagementPage.deletePlatform(platformName);

      // 验证清理成功
      await companyManagementPage.goto();
      expect(await companyManagementPage.companyExists(companyName)).toBe(false);
    });
  });

  test.describe('PlatformSelector 集成测试', () => {
    test('应该能异步加载平台选项', async ({ platformManagementPage, companyManagementPage }) => {
      const timestamp = Date.now();

      // 创建多个测试平台
      const platformNames = [
        `异步平台_A_${timestamp}`,
        `异步平台_B_${timestamp}`,
        `异步平台_C_${timestamp}`,
      ];

      await platformManagementPage.goto();
      for (const platformName of platformNames) {
        await platformManagementPage.createPlatform({
          platformName,
          contactPerson: '测试联系人',
          contactPhone: '13800138000',
          contactEmail: `test_${timestamp}@example.com`,
        });
      }

      // 返回公司管理页面
      await companyManagementPage.goto();

      // 打开创建对话框
      await companyManagementPage.openCreateDialog();

      // 验证平台选择器可见
      await expect(companyManagementPage.platformSelector).toBeVisible();

      // 关闭对话框
      await companyManagementPage.cancelDialog();

      // 清理平台
      await platformManagementPage.goto();
      for (const platformName of platformNames) {
        await platformManagementPage.deletePlatform(platformName);
      }
    });

    test('应该能使用 selectRadixOptionAsync 选择平台', async ({ platformManagementPage, companyManagementPage }) => {
      const timestamp = Date.now();

      // 创建测试平台
      const platformName = `Radix测试平台_${timestamp}`;
      await platformManagementPage.goto();
      await platformManagementPage.createPlatform({
        platformName,
        contactPerson: '测试联系人',
        contactPhone: '13800138000',
        contactEmail: `test_${timestamp}@example.com`,
      });

      // 返回公司管理页面
      await companyManagementPage.goto();

      // 创建公司并选择平台
      const companyName = `Radix测试公司_${timestamp}`;
      const result = await companyManagementPage.createCompany({
        companyName,
      }, platformName);

      // 验证创建成功
      const createResponse = result.responses?.find(r => r.url.includes('createCompany'));
      expect(createResponse?.ok).toBe(true);

      // 验证公司出现在列表中
      const exists = await companyManagementPage.companyExists(companyName);
      expect(exists).toBe(true);

      // 清理
      await companyManagementPage.deleteCompany(companyName);
      await platformManagementPage.goto();
      await platformManagementPage.deletePlatform(platformName);
    });
  });
});
