import React from 'react';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import '@testing-library/jest-dom';
import Administer from './Administer';

// 导入要模拟的API函数
import { 
  getAllUsers, 
  searchUsers, 
  getAllDiscounts,
  getCurrentDiscount
} from '../api/administer';
import { getAnnouncements } from '../api/announcement';

// 模拟API模块
jest.mock('../api/administer');
jest.mock('../api/announcement');

describe('Administer Component', () => {
  beforeEach(() => {
    // 清除所有模拟的调用信息
    jest.clearAllMocks();
    localStorage.setItem('token', 'test-token');
  });

  test('renders user management tab by default', async () => {
    getAllUsers.mockResolvedValue([]);

    render(
      <MemoryRouter>
        <Administer />
      </MemoryRouter>
    );

    expect(screen.getByText('用户管理')).toBeInTheDocument();
    expect(screen.getByText('折扣管理')).toBeInTheDocument();
    expect(screen.getByText('公告管理')).toBeInTheDocument();
  });

  test('fetches and displays users', async () => {
    const mockUsers = [
      {
        username: 'testuser',
        authority: 'USER',
        registTime: '2023-01-01',
        lastLogin: '2023-05-01',
        upload: 1000,
        download: 500,
        shareRate: 2.0,
        magicPoints: 100
      }
    ];

    getAllUsers.mockResolvedValue(mockUsers);

    render(
      <MemoryRouter>
        <Administer />
      </MemoryRouter>
    );

    await waitFor(() => {
      expect(screen.getByText('testuser')).toBeInTheDocument();
    });
  });

  test('handles user search', async () => {
    const mockUsers = [
      {
        username: 'searchuser',
        authority: 'USER',
        registTime: '2023-01-01',
        lastLogin: '2023-05-01',
        upload: 1000,
        download: 500,
        shareRate: 2.0,
        magicPoints: 100
      }
    ];

    searchUsers.mockResolvedValue(mockUsers);

    render(
      <MemoryRouter>
        <Administer />
      </MemoryRouter>
    );

    fireEvent.change(screen.getByPlaceholderText('输入用户名搜索'), {
      target: { value: 'search' }
    });
    fireEvent.click(screen.getByText('搜索'));

    await waitFor(() => {
      expect(screen.getByText('searchuser')).toBeInTheDocument();
    });
  });

  test('switches between tabs', async () => {
    // 设置初始用户数据
    getAllUsers.mockResolvedValue([]);
    // 设置折扣数据
    getAllDiscounts.mockResolvedValue([]);
    getCurrentDiscount.mockResolvedValue(null);
    // 设置公告数据
    getAnnouncements.mockResolvedValue([]);

    render(
      <MemoryRouter>
        <Administer />
      </MemoryRouter>
    );

    // 切换到折扣管理标签
    fireEvent.click(screen.getByText('折扣管理'));

    await waitFor(() => {
      expect(screen.getByText('添加新折扣')).toBeInTheDocument();
      // 可以添加更多断言来验证折扣管理页面的内容
    });
  });
});