import { describe, it, expect, vi, beforeEach } from 'vitest';
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';

// 捕获 navigate 调用
const navigateSpy = vi.fn();
vi.mock('react-router-dom', async () => {
  const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom');
  return { ...actual, useNavigate: () => navigateSpy };
});

// 捕获 message 调用：保留 antd 其余真实导出，仅桩 App.useApp 返回的 message
const messageSpy = { success: vi.fn(), error: vi.fn() };
vi.mock('antd', async () => {
  const actual = await vi.importActual<typeof import('antd')>('antd');
  return {
    ...actual,
    App: Object.assign(actual.App, { useApp: () => ({ message: messageSpy }) }),
  };
});

vi.mock('../../src/api/usrApi', () => ({
  fetchCompanies: vi.fn(),
  login: vi.fn(),
}));

import { fetchCompanies, login } from '../../src/api/usrApi';
import LoginPage from '../../src/pages/usr/Login/LoginPage';
import { TOKEN_STORAGE_KEY } from '../../src/api/request';
import { renderWithProviders } from './renderLogin';

const mockedFetch = fetchCompanies as unknown as ReturnType<typeof vi.fn>;
const mockedLogin = login as unknown as ReturnType<typeof vi.fn>;

describe('LoginPage 登录成功', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    localStorage.clear();
    mockedFetch.mockResolvedValue([{ id: 1, sCompanyName: '甲公司', sVersion: '标准版' }]);
  });

  async function submitLogin() {
    const user = userEvent.setup();
    await user.type(screen.getByPlaceholderText('请输入你的用户名'), 'admin');
    await user.type(screen.getByPlaceholderText('请输入你的密码'), 'secret');
    await user.click(screen.getByRole('button', { name: /登\s*录/ }));
  }

  it('dispatches setCredentials and persists token on success', async () => {
    mockedLogin.mockResolvedValue({
      token: 'tk',
      user: { id: 1, sUserName: 'admin', sUserType: '超级管理员', sLanguage: '中文' },
    });
    const { getState } = renderWithProviders(<LoginPage />);
    expect(await screen.findByText('甲公司（标准版）')).toBeInTheDocument();
    await submitLogin();
    await waitFor(() => expect(getState().auth.token).toBe('tk'));
    expect(getState().auth.user).toEqual({
      id: 1,
      sUserName: 'admin',
      sUserType: '超级管理员',
      sLanguage: '中文',
    });
    expect(localStorage.getItem(TOKEN_STORAGE_KEY)).toBe('tk');
  });

  it('shows success message and navigates to / with replace', async () => {
    mockedLogin.mockResolvedValue({
      token: 'tk',
      user: { id: 1, sUserName: 'admin', sUserType: '超级管理员', sLanguage: '中文' },
    });
    renderWithProviders(<LoginPage />);
    expect(await screen.findByText('甲公司（标准版）')).toBeInTheDocument();
    await submitLogin();
    await waitFor(() => expect(messageSpy.success).toHaveBeenCalledWith('登录成功'));
    expect(navigateSpy).toHaveBeenCalledWith('/', { replace: true });
  });
});
