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, channelManagementPage }) => {
    // 以管理员身份登录后台
    await adminLoginPage.goto();
    await adminLoginPage.login(testUsers.admin.username, testUsers.admin.password);
    await adminLoginPage.expectLoginSuccess();
    await channelManagementPage.goto();
  });

  test.describe('基本创建流程测试', () => {
    test('应该成功创建渠道（填写所有字段）', async ({ channelManagementPage }) => {
      // 生成唯一渠道名称
      const timestamp = Date.now();
      const channelName = `测试渠道_${timestamp}`;
      const channelType = `小程序_${timestamp}`;
      const contactPerson = `测试联系人_${timestamp}`;
      const contactPhone = '13800138000';
      const description = `测试描述_${timestamp}`;

      // 创建渠道（填写所有字段）
      const result = await channelManagementPage.createChannel({
        channelName,
        channelType,
        contactPerson,
        contactPhone,
        description,
      });

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

      // 验证渠道出现在列表中（这是最可靠的验证方式）
      await expect(async () => {
        const exists = await channelManagementPage.channelExists(channelName);
        expect(exists).toBe(true);
      }).toPass({ timeout: TIMEOUTS.DIALOG });

      // 清理测试数据
      const deleteResult = await channelManagementPage.deleteChannel(channelName);
      expect(deleteResult).toBe(true);

      // 验证渠道已被删除
      const existsAfterDelete = await channelManagementPage.channelExists(channelName);
      expect(existsAfterDelete).toBe(false);
    });

    test('创建后渠道应该出现在列表中', async ({ channelManagementPage }) => {
      const timestamp = Date.now();
      const channelName = `测试渠道_列表_${timestamp}`;
      const channelType = `网站_${timestamp}`;
      const contactPerson = `联系人_${timestamp}`;
      const contactPhone = '13900139000';

      // 创建渠道
      await channelManagementPage.createChannel({
        channelName,
        channelType,
        contactPerson,
        contactPhone,
      });

      // 等待列表更新（刷新页面确保数据同步）
      await channelManagementPage.page.reload();
      await channelManagementPage.page.waitForLoadState('domcontentloaded');
      await channelManagementPage.page.waitForTimeout(TIMEOUTS.LONG);

      // 验证渠道出现在列表中
      await expect(async () => {
        const exists = await channelManagementPage.channelExists(channelName);
        expect(exists).toBe(true);
      }).toPass({ timeout: TIMEOUTS.TABLE_LOAD });

      // 清理
      await channelManagementPage.deleteChannel(channelName);
    });
  });

  test.describe('完整表单字段测试', () => {
    test('应该保存所有填写的字段数据', async ({ channelManagementPage }) => {
      // 生成唯一数据
      const timestamp = Date.now();
      const channelName = `完整测试渠道_${timestamp}`;
      const channelType = `社交媒体_${timestamp}`;
      const contactPerson = `测试联系人_${timestamp}`;
      const contactPhone = '13800138000';
      const description = `这是测试渠道描述_${timestamp}`;

      // 创建渠道（填写所有字段）
      const result = await channelManagementPage.createChannel({
        channelName,
        channelType,
        contactPerson,
        contactPhone,
        description,
      });

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

      // 验证渠道出现在列表中
      await expect(async () => {
        const exists = await channelManagementPage.channelExists(channelName);
        expect(exists).toBe(true);
      }).toPass({ timeout: TIMEOUTS.DIALOG });

      // 清理测试数据
      await channelManagementPage.deleteChannel(channelName);
    });

    test('应该支持不同的渠道类型', async ({ channelManagementPage }) => {
      const timestamp = Date.now();
      const channelName = `渠道类型测试_${timestamp}`;
      const channelType = `线下推广_${timestamp}`;

      // 创建渠道
      const result = await channelManagementPage.createChannel({
        channelName,
        channelType,
      });

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

      // 验证渠道存在于列表中
      const exists = await channelManagementPage.channelExists(channelName);
      expect(exists).toBe(true);

      // 清理
      await channelManagementPage.deleteChannel(channelName);
    });

    test('应该支持不同的联系人信息', async ({ channelManagementPage }) => {
      const timestamp = Date.now();
      const channelName = `联系人测试渠道_${timestamp}`;
      const contactPerson = `张三_${timestamp}`;
      const contactPhone = '15011112222';

      // 创建渠道
      const result = await channelManagementPage.createChannel({
        channelName,
        contactPerson,
        contactPhone,
      });

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

      // 等待列表更新后验证渠道存在
      await channelManagementPage.page.waitForTimeout(TIMEOUTS.VERY_LONG);
      const exists = await channelManagementPage.channelExists(channelName);
      expect(exists).toBe(true);

      // 清理
      await channelManagementPage.deleteChannel(channelName);
    });
  });

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

      // 不填写任何字段，直接尝试提交
      await channelManagementPage.createSubmitButton.click();

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

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

    test('应该能取消创建渠道操作', async ({ channelManagementPage }) => {
      const timestamp = Date.now();
      const channelName = `取消测试渠道_${timestamp}`;

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

      // 填写渠道名称
      await channelManagementPage.fillChannelForm({
        channelName,
      });

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

      // 验证渠道没有出现在列表中
      const exists = await channelManagementPage.channelExists(channelName);
      expect(exists).toBe(false);
    });

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

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

      // 填写渠道名称
      await channelManagementPage.fillChannelForm({
        channelName,
      });

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

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

      // 验证渠道没有出现在列表中
      const exists = await channelManagementPage.channelExists(channelName);
      expect(exists).toBe(false);
    });
  });

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

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

      // 验证渠道名称输入框存在（必填字段）
      await expect(channelManagementPage.channelNameInput).toBeVisible();

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

      // 验证按钮存在
      await expect(channelManagementPage.createSubmitButton).toBeVisible();
      await expect(channelManagementPage.cancelButton).toBeVisible();

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

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

      // 创建第一个渠道
      await channelManagementPage.createChannel({
        channelName: channelName1,
        channelType: `渠道类型A_${timestamp}`,
        contactPerson: `联系人A_${timestamp}`,
        contactPhone: '13800001111',
      });

      expect(await channelManagementPage.channelExists(channelName1)).toBe(true);

      // 创建第二个渠道
      await channelManagementPage.createChannel({
        channelName: channelName2,
        channelType: `渠道类型B_${timestamp}`,
        contactPerson: `联系人B_${timestamp}`,
        contactPhone: '13800002222',
      });

      expect(await channelManagementPage.channelExists(channelName2)).toBe(true);

      // 清理两个渠道
      await channelManagementPage.deleteChannel(channelName1);
      await channelManagementPage.deleteChannel(channelName2);

      // 验证清理成功
      expect(await channelManagementPage.channelExists(channelName1)).toBe(false);
      expect(await channelManagementPage.channelExists(channelName2)).toBe(false);
    });
  });

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

      // 创建渠道
      await channelManagementPage.createChannel({
        channelName,
        channelType: `测试类型_${timestamp}`,
        contactPerson: `清理联系人_${timestamp}`,
        contactPhone: '13800003333',
      });

      // 验证渠道存在
      expect(await channelManagementPage.channelExists(channelName)).toBe(true);

      // 删除渠道
      const deleteResult = await channelManagementPage.deleteChannel(channelName);
      expect(deleteResult).toBe(true);

      // 验证渠道已被删除
      await expect(async () => {
        const exists = await channelManagementPage.channelExists(channelName);
        expect(exists).toBe(false);
      }).toPass({ timeout: TIMEOUTS.DIALOG });
    });
  });
});
