import React from 'react'
import { render, screen, fireEvent } from '@testing-library/react'
import Taro from '@tarojs/taro'
import OrderDetailPage from '@/pages/order-detail/index'

// Mock Taro API
jest.mock('@tarojs/taro', () => ({
  getCurrentInstance: jest.fn(() => ({
    router: {
      params: {
        id: '123'
      }
    }
  })),
  navigateBack: jest.fn(),
  showToast: jest.fn(),
  showModal: jest.fn(),
  setClipboardData: jest.fn(),
  navigateTo: jest.fn(),
  getEnv: jest.fn(() => 'h5'),
  getSystemInfoSync: jest.fn(() => ({
    statusBarHeight: 44,
    screenWidth: 375,
    windowWidth: 375
  })),
  getMenuButtonBoundingClientRect: jest.fn(() => ({
    height: 32,
    width: 87,
    top: 48,
    right: 362,
    bottom: 80,
    left: 275
  })),
  ENV_TYPE: {
    WEAPP: 'weapp',
    H5: 'h5'
  }
}))

// Mock React Query
jest.mock('@tanstack/react-query', () => ({
  useQuery: jest.fn(() => ({
    data: {
      id: 123,
      orderNo: 'ORDER202411220001',
      payState: 0,
      state: 0,
      recevierName: '张三',
      receiverMobile: '13800138000',
      address: '北京市朝阳区某某街道123号',
      amount: 299.99,
      freightAmount: 10.00,
      discountAmount: 20.00,
      payAmount: 289.99,
      createdAt: '2024-11-22T10:00:00Z',
      orderGoods: [
        {
          id: 1,
          goodsId: 1,
          goodsName: '测试商品1',
          price: 149.99,
          num: 2,
          imageFile: {
            id: 1,
            fullUrl: 'https://example.com/image1.jpg'
          }
        }
      ]
    },
    isLoading: false
  })),
  useMutation: jest.fn(() => ({
    mutate: jest.fn()
  })),
  useQueryClient: jest.fn(() => ({
    invalidateQueries: jest.fn()
  }))
}))

// Mock API client
jest.mock('@/api', () => ({
  orderClient: {
    ':id': {
      $get: jest.fn()
    },
    cancelOrder: {
      $post: jest.fn()
    }
  }
}))

describe('OrderDetailPage', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  it('应该正确渲染订单详情页面', () => {
    render(<OrderDetailPage />)

    // 检查页面标题
    expect(screen.getByText('订单详情')).toBeDefined()

    // 检查订单状态
    expect(screen.getByText('待付款')).toBeDefined()
    expect(screen.getByText('请尽快完成支付')).toBeDefined()

    // 检查收货信息
    expect(screen.getByText('收货信息')).toBeDefined()
    expect(screen.getByText('张三 13800138000')).toBeDefined()
    expect(screen.getByText('北京市朝阳区某某街道123号')).toBeDefined()

    // 检查商品信息
    expect(screen.getByText('商品信息')).toBeDefined()
    expect(screen.getByText('测试商品1')).toBeDefined()
    expect(screen.getByText('默认规格')).toBeDefined()
    expect(screen.getByText('¥149.99')).toBeDefined()
    expect(screen.getByText('×2')).toBeDefined()

    // 检查支付详情
    expect(screen.getByText('支付详情')).toBeDefined()
    expect(screen.getByText('商品总价')).toBeDefined()
    expect(screen.getByText('¥299.99')).toBeDefined()
    expect(screen.getByText('运费')).toBeDefined()
    expect(screen.getByText('¥10.00')).toBeDefined()
    expect(screen.getByText('优惠')).toBeDefined()
    expect(screen.getByText('-¥20.00')).toBeDefined()
    expect(screen.getByText('实付款')).toBeDefined()
    expect(screen.getByText('¥289.99')).toBeDefined()

    // 检查订单信息
    expect(screen.getByText('订单信息')).toBeDefined()
    expect(screen.getByText('订单编号')).toBeDefined()
    expect(screen.getByText('ORDER202411220001')).toBeDefined()
    expect(screen.getByText('创建时间')).toBeDefined()
  })

  it('应该正确显示不同订单状态', () => {
    // 测试待发货状态
    const useQueryMock = require('@tanstack/react-query').useQuery as jest.Mock
    useQueryMock.mockReturnValueOnce({
      data: {
        id: 123,
        orderNo: 'ORDER202411220001',
        payState: 2,
        state: 0,
        recevierName: '张三',
        receiverMobile: '13800138000',
        address: '北京市朝阳区某某街道123号',
        amount: 299.99,
        freightAmount: 10.00,
        discountAmount: 20.00,
        payAmount: 289.99,
        createdAt: '2024-11-22T10:00:00Z',
        orderGoods: [
          {
            id: 1,
            goodsId: 1,
            goodsName: '测试商品1',
            price: 149.99,
            num: 2,
            imageFile: {
              id: 1,
              fullUrl: 'https://example.com/image1.jpg'
            }
          }
        ]
      },
      isLoading: false
    })

    render(<OrderDetailPage />)

    expect(screen.getByText('待发货')).toBeDefined()
    expect(screen.getByText('商家正在备货中')).toBeDefined()
  })

  it('应该支持订单编号复制功能', () => {
    render(<OrderDetailPage />)

    const copyButton = screen.getByText('复制')
    fireEvent.click(copyButton)

    expect(Taro.setClipboardData).toHaveBeenCalledWith({
      data: 'ORDER202411220001',
      success: expect.any(Function)
    })
  })

  it('应该显示加载状态', () => {
    const useQueryMock = require('@tanstack/react-query').useQuery as jest.Mock
    useQueryMock.mockReturnValueOnce({
      data: null,
      isLoading: true
    })

    render(<OrderDetailPage />)

    // 应该显示加载状态
    expect(screen.queryByText('订单详情')).toBeNull()
  })

  it('应该显示订单不存在状态', () => {
    const useQueryMock = require('@tanstack/react-query').useQuery as jest.Mock
    useQueryMock.mockReturnValueOnce({
      data: null,
      isLoading: false
    })

    render(<OrderDetailPage />)

    expect(screen.getByText('订单不存在')).toBeDefined()
  })

  it('应该支持下拉刷新功能', () => {
    const mockInvalidateQueries = jest.fn()
    const useQueryClientMock = require('@tanstack/react-query').useQueryClient as jest.Mock
    useQueryClientMock.mockReturnValueOnce({
      invalidateQueries: mockInvalidateQueries
    })

    render(<OrderDetailPage />)

    // 验证下拉刷新逻辑 - 检查页面是否包含刷新容器类
    const refreshContainer = document.querySelector('.refresh-container')
    expect(refreshContainer).toBeDefined()

    // 验证useQueryClient被正确调用
    expect(useQueryClientMock).toHaveBeenCalled()
  })

  it('应该正确显示地址修改按钮', () => {
    render(<OrderDetailPage />)

    const editButton = screen.getByText('修改')
    fireEvent.click(editButton)

    expect(Taro.showToast).toHaveBeenCalledWith({
      title: '地址修改功能开发中',
      icon: 'none'
    })
  })
})