import { TIMEOUTS } from '../../utils/timeouts';
import { test, expect } from '../../utils/test-setup';
import { readFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const testUsers = JSON.parse(readFileSync(join(__dirname, '../../fixtures/test-users.json'), 'utf-8'));

test.describe('平台创建功能', () => {
  test.beforeEach(async ({ adminLoginPage, platformManagementPage }) => {
    // 以管理员身份登录后台
    await adminLoginPage.goto();
    await adminLoginPage.login(testUsers.admin.username, testUsers.admin.password);
    await adminLoginPage.expectLoginSuccess();
    await platformManagementPage.goto();
  });

  test.describe('基本创建流程测试', () => {
    test('应该成功创建平台（填写所有字段）', async ({ platformManagementPage }) => {
      // 生成唯一平台名称
      const timestamp = Date.now();
      const platformName = `测试平台_${timestamp}`;
      const contactPerson = `测试联系人_${timestamp}`;
      const contactPhone = '13800138000';
      const contactEmail = `test_${timestamp}@example.com`;

      // 创建平台（填写所有字段）
      const result = await platformManagementPage.createPlatform({
        platformName,
        contactPerson,
        contactPhone,
        contactEmail,
      });

      // 验证创建成功（通过 API 响应判断）
      expect(result.responses).toBeDefined();
      expect(result.responses?.length).toBeGreaterThan(0);
      const createResponse = result.responses?.find(r => r.url.includes('createPlatform'));
      expect(createResponse?.ok).toBe(true);

      // 验证平台出现在列表中（这是最可靠的验证方式）
      await expect(async () => {
        const exists = await platformManagementPage.platformExists(platformName);
        expect(exists).toBe(true);
      }).toPass({ timeout: TIMEOUTS.DIALOG });

      // 清理测试数据
      const deleteResult = await platformManagementPage.deletePlatform(platformName);
      expect(deleteResult).toBe(true);

      // 验证平台已被删除
      const existsAfterDelete = await platformManagementPage.platformExists(platformName);
      expect(existsAfterDelete).toBe(false);
    });

    test('创建后平台应该出现在列表中', async ({ platformManagementPage }) => {
      const timestamp = Date.now();
      const platformName = `测试平台_消息_${timestamp}`;
      const contactPerson = `联系人_${timestamp}`;
      const contactPhone = '13900139000';
      const contactEmail = `contact_${timestamp}@test.com`;

      // 创建平台
      await platformManagementPage.createPlatform({
        platformName,
        contactPerson,
        contactPhone,
        contactEmail,
      });

      // 验证平台出现在列表中
      const exists = await platformManagementPage.platformExists(platformName);
      expect(exists).toBe(true);

      // 清理
      await platformManagementPage.deletePlatform(platformName);
    });
  });

  test.describe('完整表单字段测试', () => {
    test('应该保存所有填写的字段数据', async ({ platformManagementPage }) => {
      // 生成唯一数据
      const timestamp = Date.now();
      const platformName = `完整测试平台_${timestamp}`;
      const contactPerson = `测试联系人_${timestamp}`;
      const contactPhone = '13800138000';
      const contactEmail = `test_${timestamp}@example.com`;

      // 创建平台（填写所有字段）
      const result = await platformManagementPage.createPlatform({
        platformName,
        contactPerson,
        contactPhone,
        contactEmail,
      });

      // 验证创建成功（通过 API 响应判断）
      const createResponse = result.responses?.find(r => r.url.includes('createPlatform'));
      expect(createResponse?.ok).toBe(true);

      // 验证平台出现在列表中
      await expect(async () => {
        const exists = await platformManagementPage.platformExists(platformName);
        expect(exists).toBe(true);
      }).toPass({ timeout: TIMEOUTS.DIALOG });

      // 清理测试数据
      await platformManagementPage.deletePlatform(platformName);
    });

    test('应该支持不同的联系人信息', async ({ platformManagementPage }) => {
      const timestamp = Date.now();
      const platformName = `联系人测试平台_${timestamp}`;
      const contactPerson = `张三_${timestamp}`;
      const contactPhone = '15011112222';
      const contactEmail = `zhangsan_${timestamp}@company.com`;

      // 创建平台
      const result = await platformManagementPage.createPlatform({
        platformName,
        contactPerson,
        contactPhone,
        contactEmail,
      });

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

      // 验证平台存在于列表中
      const exists = await platformManagementPage.platformExists(platformName);
      expect(exists).toBe(true);

      // 清理
      await platformManagementPage.deletePlatform(platformName);
    });
  });

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

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

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

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

    test('应该能取消创建平台操作', async ({ platformManagementPage }) => {
      const timestamp = Date.now();
      const platformName = `取消测试平台_${timestamp}`;

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

      // 填写平台名称
      await platformManagementPage.fillPlatformForm({
        platformName,
      });

      // 取消对话框
      await platformManagementPage.cancelDialog();

      // 验证平台没有出现在列表中
      const exists = await platformManagementPage.platformExists(platformName);
      expect(exists).toBe(false);
    });

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

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

      // 填写平台名称
      await platformManagementPage.fillPlatformForm({
        platformName,
      });

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

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

      // 验证平台没有出现在列表中
      const exists = await platformManagementPage.platformExists(platformName);
      expect(exists).toBe(false);
    });
  });

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

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

      // 验证平台名称输入框存在（必填字段）
      await expect(platformManagementPage.platformNameInput).toBeVisible();

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

      // 验证按钮存在
      await expect(platformManagementPage.page.getByRole('button', { name: '创建' })).toBeVisible();
      await expect(platformManagementPage.cancelButton).toBeVisible();

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

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

      // 创建第一个平台
      await platformManagementPage.createPlatform({
        platformName: platformName1,
        contactPerson: `联系人A_${timestamp}`,
        contactPhone: '13800001111',
        contactEmail: `test_a_${timestamp}@example.com`,
      });

      expect(await platformManagementPage.platformExists(platformName1)).toBe(true);

      // 创建第二个平台
      await platformManagementPage.createPlatform({
        platformName: platformName2,
        contactPerson: `联系人B_${timestamp}`,
        contactPhone: '13800002222',
        contactEmail: `test_b_${timestamp}@example.com`,
      });

      expect(await platformManagementPage.platformExists(platformName2)).toBe(true);

      // 清理两个平台
      await platformManagementPage.deletePlatform(platformName1);
      await platformManagementPage.deletePlatform(platformName2);

      // 验证清理成功
      expect(await platformManagementPage.platformExists(platformName1)).toBe(false);
      expect(await platformManagementPage.platformExists(platformName2)).toBe(false);
    });
  });

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

      // 创建平台
      await platformManagementPage.createPlatform({
        platformName,
        contactPerson: `清理联系人_${timestamp}`,
        contactPhone: '13800003333',
        contactEmail: `cleanup_${timestamp}@test.com`,
      });

      // 验证平台存在
      expect(await platformManagementPage.platformExists(platformName)).toBe(true);

      // 删除平台
      const deleteResult = await platformManagementPage.deletePlatform(platformName);
      expect(deleteResult).toBe(true);

      // 验证平台已被删除
      await expect(async () => {
        const exists = await platformManagementPage.platformExists(platformName);
        expect(exists).toBe(false);
      }).toPass({ timeout: TIMEOUTS.DIALOG });
    });
  });
});
