import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import PlatformManagement from '../../src/components/PlatformManagement';
import { platformClientManager } from '../../src/api/platformClient';

// 完整的mock响应对象
const createMockResponse = (status: number, data?: any) => ({
  status,
  ok: status >= 200 && status < 300,
  body: null,
  bodyUsed: false,
  statusText: status === 200 ? 'OK' : status === 201 ? 'Created' : status === 204 ? 'No Content' : 'Error',
  headers: new Headers(),
  url: '',
  redirected: false,
  type: 'basic' as ResponseType,
  json: async () => data || {},
  text: async () => '',
  blob: async () => new Blob(),
  arrayBuffer: async () => new ArrayBuffer(0),
  formData: async () => new FormData(),
  clone: function() { return this; }
});

// Mock API client
vi.mock('../../src/api/platformClient', () => {
  const mockPlatformClient = {
    getAllPlatforms: {
      $get: vi.fn(() => Promise.resolve(createMockResponse(200, {
        data: [
          {
            id: 1,
            platformName: '测试平台',
            contactPerson: '张三',
            contactPhone: '13800138000',
            contactEmail: 'zhangsan@example.com',
            status: 1,
            createTime: '2024-01-01T00:00:00Z',
            updateTime: '2024-01-01T00:00:00Z'
          }
        ],
        total: 1
      }))),
    },
    createPlatform: {
      $post: vi.fn(() => Promise.resolve(createMockResponse(200, {
        id: 2,
        platformName: '新平台',
        contactPerson: '李四',
        contactPhone: '13900139000',
        contactEmail: 'lisi@example.com',
        status: 1
      }))),
    },
    updatePlatform: {
      $post: vi.fn(() => Promise.resolve(createMockResponse(200, {
        id: 1,
        platformName: '更新后的平台',
        contactPerson: '王五',
        contactPhone: '13700137000',
        contactEmail: 'wangwu@example.com',
        status: 1
      }))),
    },
    deletePlatform: {
      $post: vi.fn(() => Promise.resolve(createMockResponse(200, {
        success: true
      }))),
    },
    searchPlatforms: {
      $get: vi.fn(() => Promise.resolve(createMockResponse(200, {
        data: [
          {
            id: 1,
            platformName: '测试平台',
            contactPerson: '张三',
            contactPhone: '13800138000',
            contactEmail: 'zhangsan@example.com',
            status: 1,
            createTime: '2024-01-01T00:00:00Z',
            updateTime: '2024-01-01T00:00:00Z'
          }
        ],
        total: 1
      }))),
    },
  };

  const mockPlatformClientManager = {
    get: vi.fn(() => mockPlatformClient),
  };

  return {
    platformClientManager: mockPlatformClientManager,
    platformClient: mockPlatformClient,
  };
});

// Mock toast
vi.mock('sonner', () => ({
  toast: {
    success: vi.fn(() => {}),
    error: vi.fn(() => {}),
  },
}));

describe('PlatformManagement 集成测试', () => {
  let queryClient: QueryClient;

  beforeEach(() => {
    queryClient = new QueryClient({
      defaultOptions: {
        queries: {
          retry: false,
        },
      },
    });
    vi.clearAllMocks();
  });

  const renderComponent = () => {
    return render(
      <QueryClientProvider client={queryClient}>
        <PlatformManagement />
      </QueryClientProvider>
    );
  };

  it('应该正确渲染平台列表', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 验证表格内容
    expect(screen.getByText('张三')).toBeInTheDocument();
    expect(screen.getByText('13800138000')).toBeInTheDocument();
    expect(screen.getByText('zhangsan@example.com')).toBeInTheDocument();
  });

  it('应该打开创建平台模态框', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 点击创建按钮
    const createButton = screen.getByTestId('create-platform-button');
    fireEvent.click(createButton);

    // 验证模态框打开
    expect(screen.getByTestId('create-platform-dialog-title')).toBeInTheDocument();
  });

  it('应该成功创建平台', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 打开创建模态框
    const createButton = screen.getByTestId('create-platform-button');
    fireEvent.click(createButton);

    // 填写表单
    const platformNameInput = screen.getByTestId('platform-name-input');
    const contactPersonInput = screen.getByTestId('contact-person-input');
    const contactPhoneInput = screen.getByTestId('contact-phone-input');
    const contactEmailInput = screen.getByTestId('contact-email-input');

    fireEvent.change(platformNameInput, { target: { value: '新平台' } });
    fireEvent.change(contactPersonInput, { target: { value: '李四' } });
    fireEvent.change(contactPhoneInput, { target: { value: '13900139000' } });
    fireEvent.change(contactEmailInput, { target: { value: 'lisi@example.com' } });

    // 提交表单
    const submitButton = screen.getByTestId('create-submit-button');
    fireEvent.click(submitButton);

    // 验证API调用
    await waitFor(() => {
      expect(platformClientManager.get().createPlatform.$post).toHaveBeenCalledWith({
        json: {
          platformName: '新平台',
          contactPerson: '李四',
          contactPhone: '13900139000',
          contactEmail: 'lisi@example.com'
        }
      });
    });
  });

  it('应该打开编辑平台模态框', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 点击编辑按钮
    const editButton = screen.getByTestId('edit-button-1');
    fireEvent.click(editButton);

    // 验证模态框打开并预填充数据
    expect(screen.getByText('编辑平台')).toBeInTheDocument();
  });

  it('应该成功更新平台', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 打开编辑模态框
    const editButton = screen.getByTestId('edit-button-1');
    fireEvent.click(editButton);

    // 等待编辑模态框打开
    await waitFor(() => {
      expect(screen.getByTestId('edit-platform-dialog-title')).toBeInTheDocument();
    });

    // 修改表单
    const platformNameInput = screen.getByTestId('platform-name-input');
    fireEvent.change(platformNameInput, { target: { value: '更新后的平台' } });

    // 提交表单
    const submitButton = screen.getByTestId('update-submit-button');
    fireEvent.click(submitButton);

    // 验证API调用
    await waitFor(() => {
      expect(platformClientManager.get().updatePlatform.$post).toHaveBeenCalledWith({
        json: {
          id: 1,
          platformName: '更新后的平台',
          contactPerson: '张三',
          contactPhone: '13800138000',
          contactEmail: 'zhangsan@example.com'
        }
      });
    });
  });

  it('应该打开删除确认对话框', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 点击删除按钮
    const deleteButton = screen.getByTestId('delete-button-1');
    fireEvent.click(deleteButton);

    // 验证确认对话框打开
    expect(screen.getByText('确认删除')).toBeInTheDocument();
  });

  it('应该成功删除平台', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 打开删除确认对话框
    const deleteButton = screen.getByTestId('delete-button-1');
    fireEvent.click(deleteButton);

    // 确认删除
    const confirmButton = screen.getByTestId('confirm-delete-button');
    fireEvent.click(confirmButton);

    // 验证API调用
    await waitFor(() => {
      expect(platformClientManager.get().deletePlatform.$post).toHaveBeenCalledWith({
        json: { id: 1 }
      });
    });
  });

  it('应该处理搜索功能', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 输入搜索关键词
    const searchInput = screen.getByTestId('search-input');
    fireEvent.change(searchInput, { target: { value: '测试' } });

    // 点击搜索按钮
    const searchButton = screen.getByTestId('search-button');
    fireEvent.click(searchButton);

    // 验证API调用
    await waitFor(() => {
      expect(platformClientManager.get().searchPlatforms.$get).toHaveBeenCalledWith({
        query: {
          name: '测试',
          skip: 0,
          take: 10
        }
      });
    });
  });

  it('应该处理API错误', async () => {
    // Mock API错误 - 使用mockImplementationOnce
    const mockGet = platformClientManager.get().getAllPlatforms.$get as any;
    mockGet.mockImplementationOnce(() => Promise.reject(new Error('网络错误')));

    renderComponent();

    // 验证组件不会崩溃，仍然显示标题
    await waitFor(() => {
      expect(screen.getByText('平台管理')).toBeInTheDocument();
    });
  });

  // 邮箱字段优化测试
  it('应该允许邮箱字段为空创建平台', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 打开创建模态框
    const createButton = screen.getByTestId('create-platform-button');
    fireEvent.click(createButton);

    // 填写表单，不填写邮箱字段
    const platformNameInput = screen.getByTestId('platform-name-input');
    const contactPersonInput = screen.getByTestId('contact-person-input');
    const contactPhoneInput = screen.getByTestId('contact-phone-input');

    fireEvent.change(platformNameInput, { target: { value: '新平台（无邮箱）' } });
    fireEvent.change(contactPersonInput, { target: { value: '李四' } });
    fireEvent.change(contactPhoneInput, { target: { value: '13900139000' } });

    // 提交表单
    const submitButton = screen.getByTestId('create-submit-button');
    fireEvent.click(submitButton);

    // 验证API调用，邮箱字段应为undefined
    await waitFor(() => {
      expect(platformClientManager.get().createPlatform.$post).toHaveBeenCalledWith({
        json: {
          platformName: '新平台（无邮箱）',
          contactPerson: '李四',
          contactPhone: '13900139000',
          contactEmail: undefined
        }
      });
    });
  });

  it('应该允许邮箱字段为有效邮箱格式创建平台', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 打开创建模态框
    const createButton = screen.getByTestId('create-platform-button');
    fireEvent.click(createButton);

    // 填写表单，包含有效邮箱
    const platformNameInput = screen.getByTestId('platform-name-input');
    const contactPersonInput = screen.getByTestId('contact-person-input');
    const contactPhoneInput = screen.getByTestId('contact-phone-input');
    const contactEmailInput = screen.getByTestId('contact-email-input');

    fireEvent.change(platformNameInput, { target: { value: '新平台（有邮箱）' } });
    fireEvent.change(contactPersonInput, { target: { value: '王五' } });
    fireEvent.change(contactPhoneInput, { target: { value: '13700137000' } });
    fireEvent.change(contactEmailInput, { target: { value: 'wangwu@example.com' } });

    // 提交表单
    const submitButton = screen.getByTestId('create-submit-button');
    fireEvent.click(submitButton);

    // 验证API调用
    await waitFor(() => {
      expect(platformClientManager.get().createPlatform.$post).toHaveBeenCalledWith({
        json: {
          platformName: '新平台（有邮箱）',
          contactPerson: '王五',
          contactPhone: '13700137000',
          contactEmail: 'wangwu@example.com'
        }
      });
    });
  });

  it('应该显示无效邮箱格式的错误提示', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 打开创建模态框
    const createButton = screen.getByTestId('create-platform-button');
    fireEvent.click(createButton);

    // 填写表单，包含无效邮箱
    const platformNameInput = screen.getByTestId('platform-name-input');
    const contactEmailInput = screen.getByTestId('contact-email-input');

    fireEvent.change(platformNameInput, { target: { value: '测试平台' } });
    fireEvent.change(contactEmailInput, { target: { value: '无效邮箱' } });

    // 提交表单
    const submitButton = screen.getByTestId('create-submit-button');
    fireEvent.click(submitButton);

    // 验证显示中文错误提示
    await waitFor(() => {
      expect(screen.getByText('请输入有效的邮箱地址')).toBeInTheDocument();
    });

    // 验证API没有被调用
    expect(platformClientManager.get().createPlatform.$post).not.toHaveBeenCalled();
  });

  it('应该允许邮箱字段为空更新平台', async () => {
    renderComponent();

    // 等待数据加载
    await waitFor(() => {
      expect(screen.getByText('测试平台')).toBeInTheDocument();
    });

    // 打开编辑模态框
    const editButton = screen.getByTestId('edit-button-1');
    fireEvent.click(editButton);

    // 等待编辑模态框打开
    await waitFor(() => {
      expect(screen.getByTestId('edit-platform-dialog-title')).toBeInTheDocument();
    });

    // 清空邮箱字段
    const contactEmailInput = screen.getByTestId('contact-email-input');
    fireEvent.change(contactEmailInput, { target: { value: '' } });

    // 提交表单
    const submitButton = screen.getByTestId('update-submit-button');
    fireEvent.click(submitButton);

    // 验证API调用，邮箱字段应为undefined
    await waitFor(() => {
      expect(platformClientManager.get().updatePlatform.$post).toHaveBeenCalledWith({
        json: {
          id: 1,
          platformName: '测试平台',
          contactPerson: '张三',
          contactPhone: '13800138000',
          contactEmail: undefined
        }
      });
    });
  });
});