/**
 * 调试课程创建 - 追踪 currentStep 和按钮点击
 */
import { test, expect } from '@playwright/test';
import { loginAsAdmin } from './helpers';

test.describe('课程创建调试 - currentStep 追踪', () => {
  test('追踪 currentStep 和 handleSave 调用', async ({ page }) => {
    test.setTimeout(180000);

    const courseName = '调试测试课程包-' + Date.now();
    console.log('=== 测试开始 ===');

    // 注入监控代码
    await page.addInitScript(() => {
      (window as any).logs = [];

      const originalConsoleLog = console.log;
      console.log = function(...args) {
        originalConsoleLog.apply(console, args);
        (window as any).logs.push(args.join(' '));
      };
    });

    // 步骤 1: 登录
    console.log('=== 步骤 1: 登录 ===');
    await loginAsAdmin(page);
    await page.waitForTimeout(1000);

    // 步骤 2: 进入课程创建页面
    console.log('=== 步骤 2: 进入课程创建页面 ===');
    await page.goto('/admin/courses/create', { timeout: 30000, waitUntil: 'networkidle' });
    await page.waitForTimeout(3000);

    // 检查当前步骤
    const step0Visible = await page.getByText('创建课程包').isVisible();
    console.log('创建页面标题可见:', step0Visible);

    // 步骤 3: 填写基本信息
    console.log('=== 步骤 3: 填写基本信息 ===');
    await page.getByPlaceholder('请输入课程包名称').fill(courseName);

    console.log('选择主题...');
    await page.locator('.ant-select-selector').first().click();
    await page.waitForTimeout(500);
    await page.getByText('社会认知', { exact: true }).first().click();
    await page.waitForTimeout(300);

    console.log('选择年级...');
    await page.getByRole('checkbox', { name: '小班' }).check();
    await page.waitForTimeout(300);

    console.log('填写核心内容...');
    await page.getByPlaceholder('请输入课程包核心内容').fill('调试测试课程内容');
    await page.waitForTimeout(500);

    // 步骤 4: 点击下一步，记录每次点击后的步骤
    console.log('=== 步骤 4: 点击下一步 ===');
    for (let i = 0; i < 6; i++) {
      const nextButton = page.getByRole('button', { name: '下一步' });
      const nextVisible = await nextButton.isVisible().catch(() => false);
      const nextDisabled = await nextButton.isDisabled().catch(() => false);

      console.log(`第 ${i + 1} 次：下一步按钮可见=${nextVisible}, 禁用=${nextDisabled}`);

      if (nextVisible && !nextDisabled) {
        console.log(`  点击第 ${i + 1} 次"下一步"`);
        await nextButton.click();
        await page.waitForTimeout(1000);

        // 检查当前步骤指示器
        const currentStepElement = page.locator('.ant-steps-item-active').first();
        const stepIndex = await currentStepElement.locator('.ant-steps-icon').textContent().catch(() => '?');
        console.log(`  当前步骤索引：${stepIndex}`);

        // 检查当前页面的标题
        const stepTitle = await page.locator('.ant-steps-item-title').nth(i).textContent().catch(() => '?');
        console.log(`  当前步骤标题：${stepTitle}`);
      } else {
        console.log(`  第 ${i + 1} 次：按钮不可见或已禁用，停止点击`);
        break;
      }
    }

    await page.waitForTimeout(1000);

    // 步骤 5: 检查是否到达最后一步
    console.log('=== 步骤 5: 检查最后一步 ===');

    // 检查创建按钮
    const submitButton = page.getByRole('button', { name: '创建' });
    const submitVisible = await submitButton.isVisible().catch(() => false);
    const submitDisabled = await submitButton.isDisabled().catch(() => false);
    console.log('创建按钮可见:', submitVisible);
    console.log('创建按钮禁用:', submitDisabled);

    // 检查下一步按钮是否还存在
    const nextButtonAfterLoop = page.getByRole('button', { name: '下一步' });
    const nextStillExists = await nextButtonAfterLoop.count() > 0;
    console.log('下一步按钮还存在:', nextStillExists);

    if (!submitVisible) {
      console.log('创建按钮不可见，截图...');
      await page.screenshot({ path: 'test-results/debug-no-submit.png' });

      // 尝试点击下一步看看是否能到达最后一步
      console.log('尝试额外点击一次下一步...');
      const extraNext = page.getByRole('button', { name: '下一步' });
      if (await extraNext.isVisible().catch(() => false)) {
        await extraNext.click();
        await page.waitForTimeout(1000);

        const submitVisibleAfter = await submitButton.isVisible().catch(() => false);
        console.log('额外点击后创建按钮可见:', submitVisibleAfter);
      }
    }

    // 步骤 6: 点击创建按钮
    console.log('=== 步骤 6: 点击创建 ===');
    if (await submitButton.isVisible().catch(() => false) && !submitDisabled) {
      console.log('点击创建按钮...');

      // 在点击前记录网络请求数量
      const requestCountBefore = await page.evaluate(() => performance.getEntriesByType('resource').filter(r => r.name.includes('/api/')).length);
      console.log('点击前 API 请求数量:', requestCountBefore);

      await submitButton.click();
      console.log('已点击创建按钮');

      // 等待网络请求
      try {
        const response = await page.waitForResponse(
          res => res.url().includes('/api/v1/admin/courses') && res.request().method() === 'POST',
          { timeout: 10000 }
        );
        console.log('捕获到课程创建 API 响应:', response.status());
      } catch {
        console.log('未捕获到课程创建 API 请求');
      }

      await page.waitForTimeout(5000);

      // 检查消息
      const successMsg = await page.locator('.ant-message-success').count();
      const errorMsg = await page.locator('.ant-message-error').count();
      console.log('成功消息:', successMsg);
      console.log('错误消息:', errorMsg);

      // 检查 URL
      console.log('当前 URL:', page.url());
    } else {
      console.log('创建按钮不可用，跳过点击');
    }

    // 截图
    await page.screenshot({ path: 'test-results/debug-final-state.png' });

    // 获取注入的日志
    const logs = await page.evaluate(() => (window as any).logs || []);
    console.log('=== 浏览器日志 ===');
    console.log(logs.join('\n'));
  });
});
