/**
 * 调试课程创建流程 - 检查创建 API 的响应
 */
import { test, expect } from '@playwright/test';
import { loginAsAdmin } from './helpers';

test.describe('课程创建调试', () => {
  test('检查课程创建 API 的响应', async ({ page }) => {
    test.setTimeout(180000);

    const courseName = '调试课程-' + Date.now();
    console.log('=== 课程创建调试开始 ===');
    console.log('课程名称:', courseName);

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

    // 步骤 2: 进入课程管理页面
    console.log('=== 步骤 2: 进入课程管理页面 ===');
    await page.goto('/admin/courses', { timeout: 30000, waitUntil: 'commit' });
    await page.waitForLoadState('networkidle', { timeout: 30000 }).catch(() => {});
    await page.waitForTimeout(3000);

    // 步骤 3: 点击新建课程包按钮
    console.log('=== 步骤 3: 点击新建课程包 ===');
    const createButton = page.getByRole('button', { name: '新建课程包' });
    await createButton.click();
    await page.waitForTimeout(1000);

    // 验证进入创建页面
    console.log('=== 验证进入创建页面 ===');
    await expect(page.getByText('创建课程包')).toBeVisible({ timeout: 5000 });
    console.log('已进入创建页面');

    // ==================== 步骤 1: 基本信息 ====================
    console.log('=== 步骤 4: 填写基本信息 ===');
    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);

    // ==================== 逐步点击下一步 ====================
    console.log('=== 步骤 5: 点击下一步 ===');
    for (let i = 0; i < 6; i++) {
      const nextButton = page.getByRole('button', { name: '下一步' });
      const isVisible = await nextButton.isVisible().catch(() => false);
      if (isVisible) {
        console.log(`点击第 ${i + 1} 次下一步`);
        await nextButton.click();
        await page.waitForTimeout(1000);
      } else {
        console.log(`第 ${i + 1} 次下一步不可见，停止点击`);
        break;
      }
    }

    // ==================== 检查当前步骤和按钮 ====================
    console.log('=== 步骤 6: 检查当前步骤 ===');
    const currentStep = await page.evaluate(() => {
      const app = document.querySelector('#app') as any;
      if (app && app.__vue_app__) {
        // 尝试获取组件实例
        const courseEditView = document.querySelector('.course-edit-view');
        if (courseEditView) {
          const comp = (courseEditView as any).__vueParentComponent;
          return comp?.ctx?.currentStep;
        }
      }
      return null;
    });
    console.log('当前步骤:', currentStep);

    // 检查 step-actions 容器内的按钮
    console.log('=== 检查提交按钮 ===');
    const submitButton = page.locator('.step-actions .ant-btn-primary').last();
    const submitVisible = await submitButton.isVisible().catch(() => false);
    console.log('提交按钮可见:', submitVisible);

    if (!submitVisible) {
      console.log('提交按钮不可见，尝试查找其他按钮');
      const buttons = page.locator('.step-actions button');
      const count = await buttons.count();
      for (let i = 0; i < count; i++) {
        const btn = buttons.nth(i);
        const text = await btn.textContent();
        const visible = await btn.isVisible();
        console.log(`按钮 ${i}: 文本="${text?.trim()}", 可见=${visible}`);
      }
    }

    // ==================== 提交并监控 API 请求 ====================
    console.log('=== 步骤 7: 提交表单并监控 API ===');

    // 设置请求监听
    let requestPostData = null;
    let responseStatus = null;
    let responseData = null;

    page.on('request', request => {
      if (request.url().includes('/api/v1/admin/courses') && request.method() === 'POST') {
        console.log('捕获到课程创建请求');
        console.log('请求 URL:', request.url());
        requestPostData = request.postData();
      }
    });

    page.on('response', response => {
      if (response.url().includes('/api/v1/admin/courses') && response.request().method() === 'POST') {
        console.log('捕获到课程创建响应');
        console.log('响应状态:', response.status());
        responseStatus = response.status();
        response.text().then(text => {
          console.log('响应体:', text);
          try {
            responseData = JSON.parse(text);
          } catch {
            responseData = text;
          }
        }).catch(() => {});
      }
    });

    // 点击提交按钮
    console.log('点击提交按钮...');
    await submitButton.click();
    await page.waitForTimeout(5000);

    // 打印捕获的数据
    console.log('=== 请求数据 ===');
    if (requestPostData) {
      try {
        const json = JSON.parse(requestPostData);
        console.log(JSON.stringify(json, null, 2));
      } catch {
        console.log(requestPostData);
      }
    } else {
      console.log('未捕获到请求数据');
    }

    console.log('=== 响应数据 ===');
    console.log('状态码:', responseStatus);
    console.log('响应体:', JSON.stringify(responseData, null, 2));

    // 检查成功/失败消息
    console.log('=== 检查结果提示 ===');
    const successMsg = await page.locator('.ant-message-success').count();
    const errorMsg = await page.locator('.ant-message-error').count();
    console.log('成功消息数量:', successMsg);
    console.log('错误消息数量:', errorMsg);

    if (errorMsg > 0) {
      const errorText = await page.locator('.ant-message-error').first().textContent();
      console.log('错误消息:', errorText);
    }

    // 检查页面跳转
    console.log('=== 检查页面 URL ===');
    console.log('当前 URL:', page.url());

    // 截图
    await page.screenshot({ path: 'test-results/debug-course-create.png' });
    console.log('截图已保存');

    // 尝试在列表中查找课程
    if (page.url().includes('/admin/courses')) {
      console.log('=== 检查课程列表 ===');
      const table = page.locator('.ant-table').first();
      const tableVisible = await table.isVisible().catch(() => false);
      console.log('表格可见:', tableVisible);

      if (tableVisible) {
        const courseVisible = await table.getByText(courseName).isVisible().catch(() => false);
        console.log('新课程包在列表中可见:', courseVisible);
      }
    }

    console.log('=== 调试完成 ===');
  });
});
