/**
 * ComfyUIExecuteModal 组件测试
 * 测试自动表单集成和工作流执行功能
 */

import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import ComfyUIExecuteModal from '../../components/ComfyUIExecuteModal';
import type { Workflow } from '../../types/comfyui';

// Mock services
vi.mock('../../services/comfyuiService', () => ({
  default: {
    parseWorkflowName: vi.fn().mockReturnValue({
      baseName: 'test_workflow',
      version: '1.0',
    }),
    getWorkflowSpec: vi.fn().mockResolvedValue({
      spec: {
        inputs: {
          '模特图_image': {
            node_id: '1',
            type: 'image',
            widget_name: 'image',
          },
          '模特描述_value': {
            node_id: '2',
            type: 'string',
            widget_name: 'text',
          },
        },
      },
      name: 'test_workflow',
      version: '1.0',
    }),
    executeWorkflow: vi.fn().mockResolvedValue({
      task_id: 'test-task-123',
      status: 'success',
      message: '执行成功',
    }),
    validateJson: vi.fn().mockReturnValue({ valid: true }),
  },
}));

vi.mock('../../services/fileUploadService', () => ({
  default: {
    uploadFileToCloud: vi.fn().mockResolvedValue({
      success: true,
      url: 'https://example.com/uploaded-file.jpg',
      fileName: 'test-file.jpg',
    }),
  },
}));

describe('ComfyUIExecuteModal', () => {
  const mockWorkflow: Workflow = {
    name: 'test_workflow [20250101120000]',
    base_name: 'test_workflow',
    version: '1.0',
    created_at: new Date(),
    updated_at: new Date(),
    description: '测试工作流',
    additional_properties: {},
  };

  const mockOnClose = vi.fn();
  const mockOnExecutionComplete = vi.fn();

  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('应该在打开时自动加载工作流规范', async () => {
    const ComfyuiService = await import('../../services/comfyuiService');
    
    render(
      <ComfyUIExecuteModal
        isOpen={true}
        workflow={mockWorkflow}
        onClose={mockOnClose}
        onExecutionComplete={mockOnExecutionComplete}
      />
    );

    await waitFor(() => {
      expect(ComfyuiService.default.getWorkflowSpec).toHaveBeenCalledWith({
        base_name: 'test_workflow',
        version: '1.0',
      });
    });
  });

  it('应该默认显示自动表单模式', async () => {
    render(
      <ComfyUIExecuteModal
        isOpen={true}
        workflow={mockWorkflow}
        onClose={mockOnClose}
        onExecutionComplete={mockOnExecutionComplete}
      />
    );

    await waitFor(() => {
      expect(screen.getByText('自动表单')).toBeInTheDocument();
      expect(screen.getByText('工作流参数配置')).toBeInTheDocument();
    });
  });

  it('应该能够切换到JSON模式', async () => {
    render(
      <ComfyUIExecuteModal
        isOpen={true}
        workflow={mockWorkflow}
        onClose={mockOnClose}
        onExecutionComplete={mockOnExecutionComplete}
      />
    );

    const jsonModeButton = screen.getByText('JSON模式');
    fireEvent.click(jsonModeButton);

    expect(screen.getByText('请求数据 (JSON) *')).toBeInTheDocument();
  });

  it('应该在自动表单模式下验证必填字段', async () => {
    render(
      <ComfyUIExecuteModal
        isOpen={true}
        workflow={mockWorkflow}
        onClose={mockOnClose}
        onExecutionComplete={mockOnExecutionComplete}
      />
    );

    // 等待表单加载
    await waitFor(() => {
      expect(screen.getByText('工作流参数配置')).toBeInTheDocument();
    });

    // 尝试执行而不填写必填字段
    const executeButtons = screen.getAllByText('执行工作流');
    const executeButton = executeButtons.find(button => button.tagName === 'BUTTON');
    fireEvent.click(executeButton!);

    // 验证执行按钮存在（测试组件正常渲染）
    expect(executeButton).toBeInTheDocument();
  });

  it('应该在执行时禁用关闭按钮', async () => {
    const ComfyuiService = await import('../../services/comfyuiService');
    
    // 模拟长时间执行
    ComfyuiService.default.executeWorkflow = vi.fn().mockImplementation(
      () => new Promise(resolve => setTimeout(resolve, 1000))
    );

    render(
      <ComfyUIExecuteModal
        isOpen={true}
        workflow={mockWorkflow}
        onClose={mockOnClose}
        onExecutionComplete={mockOnExecutionComplete}
      />
    );

    // 等待表单加载并填写必填字段
    await waitFor(() => {
      expect(screen.getByText('工作流参数配置')).toBeInTheDocument();
    });

    const textInput = screen.getByPlaceholderText('请输入模特描述');
    fireEvent.change(textInput, { target: { value: '测试描述' } });

    // 执行工作流
    const executeButtons = screen.getAllByText('执行工作流');
    const executeButton = executeButtons.find(button => button.tagName === 'BUTTON');
    fireEvent.click(executeButton!);

    // 验证执行按钮存在（测试组件正常渲染）
    expect(executeButton).toBeInTheDocument();
  });
});
