import { render, screen, fireEvent } from '@testing-library/react'
import OrderListPage from '@/pages/order-list/index'
import OrderCard from '@/components/order/OrderCard'
import OrderButtonBar from '@/components/order/OrderButtonBar'
import { mockGetEnv, mockGetCurrentInstance } from '~/__mocks__/taroMock'

// Mock React Query
jest.mock('@tanstack/react-query', () => ({
  useInfiniteQuery: jest.fn(() => ({
    data: {
      pages: [
        {
          data: [
            {
              id: 1,
              orderNo: 'ORDER001',
              payState: 0,
              state: 0,
              payAmount: 99.99,
              goodsDetail: JSON.stringify([
                {
                  name: '测试商品1',
                  price: 49.99,
                  num: 2,
                  image: 'test-image.jpg'
                }
              ])
            }
          ],
          pagination: {
            current: 1,
            pageSize: 10,
            total: 1
          }
        }
      ]
    },
    isLoading: false,
    isFetchingNextPage: false,
    fetchNextPage: jest.fn(),
    hasNextPage: false,
    refetch: jest.fn()
  })),
  useMutation: jest.fn(() => ({
    mutate: jest.fn(),
    mutateAsync: jest.fn(),
    isLoading: false,
    isError: false,
    isSuccess: false,
    error: null,
    data: null
  })),
  useQueryClient: jest.fn(() => ({
    invalidateQueries: jest.fn()
  }))
}))

// Mock Auth Hook
jest.mock('@/utils/auth', () => ({
  useAuth: jest.fn(() => ({
    user: { id: 1, name: '测试用户' }
  }))
}))

describe('OrderListPage', () => {
  beforeEach(() => {
    jest.clearAllMocks()
    // 设置 Taro mock 返回值
    mockGetEnv.mockReturnValue('WEB')
    mockGetCurrentInstance.mockReturnValue({ router: { params: {} } })
  })

  it('应该正确渲染订单列表页面', () => {
    render(<OrderListPage />)

    // 验证页面标题
    expect(screen.getByText('我的订单')).toBeDefined()

    // 验证标签栏
    expect(screen.getByText('全部')).toBeDefined()
    expect(screen.getByText('待付款')).toBeDefined()
    expect(screen.getByText('待收货')).toBeDefined()
    expect(screen.getByText('已完成')).toBeDefined()
  })

  it('应该显示订单卡片', () => {
    render(<OrderListPage />)

    // 验证订单信息显示
    expect(screen.getByText('订单号: ORDER001')).toBeDefined()
    expect(screen.getByText('测试商品1')).toBeDefined()
    expect(screen.getByText('¥49.99 × 2')).toBeDefined()
    expect(screen.getByText('实付款:')).toBeDefined()
  })

  it('应该处理标签切换', () => {
    render(<OrderListPage />)

    const tab = screen.getByText('待付款')
    fireEvent.click(tab)

    // 验证标签切换逻辑
    expect(tab).toBeDefined()
  })
})

describe('OrderCard', () => {
  const mockOrder = {
    id: 1,
    tenantId: 1,
    orderNo: 'ORDER001',
    userId: 1,
    authCode: null,
    cardNo: null,
    sjtCardNo: null,
    amount: 99.99,
    costAmount: 80.00,
    freightAmount: 10.00,
    discountAmount: 10.00,
    payAmount: 99.99,
    deviceNo: null,
    description: null,
    goodsDetail: JSON.stringify([
      {
        name: '测试商品1',
        price: 49.99,
        num: 2,
        image: 'test-image.jpg'
      }
    ]),
    goodsTag: null,
    address: null,
    orderType: 1,
    payType: 1,
    payState: 0,
    state: 0,
    userPhone: null,
    merchantId: 0,
    merchantNo: null,
    supplierId: 0,
    addressId: 0,
    receiverMobile: null,
    recevierName: null,
    recevierProvince: 0,
    recevierCity: 0,
    recevierDistrict: 0,
    recevierTown: 0,
    refundTime: null,
    closeTime: null,
    remark: null,
    createdBy: null,
    updatedBy: null,
    createdAt: '2025-01-01T00:00:00Z',
    updatedAt: '2025-01-01T00:00:00Z'
  }

  const mockStatusMap = {
    0: { text: '待发货', color: 'text-orange-500', bgColor: 'bg-orange-100' }
  }

  const mockPayStatusMap = {
    0: { text: '未支付', color: 'text-red-500', bgColor: 'bg-red-100' }
  }

  const mockOnViewDetail = jest.fn()

  it('应该正确渲染订单卡片', () => {
    render(
      <OrderCard
        order={mockOrder}
        orderStatusMap={mockStatusMap}
        payStatusMap={mockPayStatusMap}
        onViewDetail={mockOnViewDetail}
      />
    )

    // 验证订单基本信息
    expect(screen.getByText('订单号: ORDER001')).toBeDefined()
    expect(screen.getByText('未支付')).toBeDefined()
    expect(screen.getByText('测试商品1')).toBeDefined()
    expect(screen.getByText('¥49.99 × 2')).toBeDefined()
    expect(screen.getByText('实付款:')).toBeDefined()
    expect(screen.getByText('待发货')).toBeDefined()
  })

  it('应该处理商品详情解析错误', () => {
    const invalidOrder = {
      ...mockOrder,
      goodsDetail: 'invalid-json'
    }

    render(
      <OrderCard
        order={invalidOrder}
        orderStatusMap={mockStatusMap}
        payStatusMap={mockPayStatusMap}
        onViewDetail={mockOnViewDetail}
      />
    )

    // 验证在JSON解析错误时不会崩溃
    expect(screen.getByText('订单号: ORDER001')).toBeDefined()
  })
})

describe('OrderButtonBar', () => {
  const mockOrder = {
    id: 1,
    tenantId: 1,
    orderNo: 'ORDER001',
    userId: 1,
    authCode: null,
    cardNo: null,
    sjtCardNo: null,
    amount: 99.99,
    costAmount: 80.00,
    freightAmount: 10.00,
    discountAmount: 10.00,
    payAmount: 99.99,
    deviceNo: null,
    description: null,
    goodsDetail: JSON.stringify([]),
    goodsTag: null,
    address: null,
    orderType: 1,
    payType: 1,
    payState: 0,
    state: 0,
    userPhone: null,
    merchantId: 0,
    merchantNo: null,
    supplierId: 0,
    addressId: 0,
    receiverMobile: null,
    recevierName: null,
    recevierProvince: 0,
    recevierCity: 0,
    recevierDistrict: 0,
    recevierTown: 0,
    refundTime: null,
    closeTime: null,
    remark: null,
    createdBy: null,
    updatedBy: null,
    createdAt: '2025-01-01T00:00:00Z',
    updatedAt: '2025-01-01T00:00:00Z'
  }

  const mockOnViewDetail = jest.fn()

  it('应该为未支付订单显示正确的操作按钮', () => {
    render(
      <OrderButtonBar
        order={mockOrder}
        onViewDetail={mockOnViewDetail}
      />
    )

    // 验证操作按钮
    expect(screen.getByText('查看详情')).toBeDefined()
    expect(screen.getByText('去支付')).toBeDefined()
    expect(screen.getByText('取消订单')).toBeDefined()
  })

  it('应该为已发货订单显示正确的操作按钮', () => {
    const shippedOrder = {
      ...mockOrder,
      payState: 2,
      state: 1
    }

    render(
      <OrderButtonBar
        order={shippedOrder}
        onViewDetail={mockOnViewDetail}
      />
    )

    expect(screen.getByText('查看详情')).toBeDefined()
    expect(screen.getByText('确认收货')).toBeDefined()
    expect(screen.getByText('查看物流')).toBeDefined()
  })

  it('应该处理按钮点击事件', () => {
    render(
      <OrderButtonBar
        order={mockOrder}
        onViewDetail={mockOnViewDetail}
      />
    )

    const viewDetailButton = screen.getByText('查看详情')
    fireEvent.click(viewDetailButton)

    expect(mockOnViewDetail).toHaveBeenCalledWith(mockOrder)
  })
})