import React, { useState } from 'react'
import { View, Text } from '@tarojs/components'
import { Button } from '@nutui/nutui-react-taro'
import { getUserGifts } from '@/api/shop/shopGift'
import Taro from '@tarojs/taro'

const ApiTest: React.FC = () => {
  const [loading, setLoading] = useState(false)
  const [results, setResults] = useState<any[]>([])
  const [logs, setLogs] = useState<string[]>([])

  const addLog = (message: string) => {
    const timestamp = new Date().toLocaleTimeString()
    setLogs(prev => [`[${timestamp}] ${message}`, ...prev])
  }

  const testApiCall = async (status: number, statusName: string) => {
    setLoading(true)
    addLog(`开始测试 status=${status} (${statusName})`)
    
    try {
      const params = {
        page: 1,
        limit: 10,
        userId: Taro.getStorageSync('UserId'),
        status: status
      }
      
      addLog(`API参数: ${JSON.stringify(params)}`)
      
      const res = await getUserGifts(params)
      
      addLog(`API返回: ${res?.list?.length || 0} 条数据`)
      
      if (res?.list && res.list.length > 0) {
        const statusCounts = res.list.reduce((acc: any, item: any) => {
          const itemStatus = item.status
          acc[itemStatus] = (acc[itemStatus] || 0) + 1
          return acc
        }, {})
        
        addLog(`返回数据状态分布: ${JSON.stringify(statusCounts)}`)
        
        // 检查是否所有返回的数据都是期望的状态
        const allCorrectStatus = res.list.every((item: any) => item.status === status)
        if (allCorrectStatus) {
          addLog(`✅ 状态筛选正确: 所有数据都是 status=${status}`)
        } else {
          addLog(`❌ 状态筛选错误: 返回了其他状态的数据`)
        }
      } else {
        addLog(`ℹ️ 无数据返回`)
      }
      
      setResults(prev => [...prev, {
        status,
        statusName,
        count: res?.list?.length || 0,
        data: res?.list || [],
        success: true
      }])
      
    } catch (error) {
      addLog(`❌ API调用失败: ${error}`)
      setResults(prev => [...prev, {
        status,
        statusName,
        count: 0,
        data: [],
        success: false,
        error: String(error)
      }])
    } finally {
      setLoading(false)
    }
  }

  const clearResults = () => {
    setResults([])
    setLogs([])
  }

  const testAllStatus = async () => {
    clearResults()
    await testApiCall(0, '未使用')
    await new Promise(resolve => setTimeout(resolve, 1000)) // 延迟1秒
    await testApiCall(1, '已使用')
    await new Promise(resolve => setTimeout(resolve, 1000)) // 延迟1秒
    await testApiCall(2, '失效')
  }

  return (
    <View className="bg-gray-50 min-h-screen">
      {/* 页面标题 */}
      <View className="bg-white px-4 py-3 border-b border-gray-100">
        <Text className="text-lg font-bold text-center">
          API 状态参数测试
        </Text>
        <Text className="text-sm text-gray-600 text-center mt-1">
          测试 getUserGifts API 的 status 参数传递
        </Text>
      </View>

      {/* 测试按钮 */}
      <View className="bg-white mx-4 mt-4 p-4 rounded-lg">
        <Text className="font-bold mb-3">测试操作：</Text>
        <View className="flex flex-wrap gap-2 mb-3">
          <Button 
            size="small" 
            type="primary"
            loading={loading}
            onClick={() => testApiCall(0, '未使用')}
          >
            测试 status=0
          </Button>
          <Button 
            size="small" 
            type="primary"
            loading={loading}
            onClick={() => testApiCall(1, '已使用')}
          >
            测试 status=1
          </Button>
          <Button 
            size="small" 
            type="primary"
            loading={loading}
            onClick={() => testApiCall(2, '失效')}
          >
            测试 status=2
          </Button>
        </View>
        <View className="flex gap-2">
          <Button 
            size="small" 
            fill="outline"
            loading={loading}
            onClick={testAllStatus}
          >
            测试所有状态
          </Button>
          <Button 
            size="small" 
            fill="outline"
            onClick={clearResults}
          >
            清空结果
          </Button>
        </View>
      </View>

      {/* 测试结果 */}
      {results.length > 0 && (
        <View className="bg-white mx-4 mt-4 p-4 rounded-lg">
          <Text className="font-bold mb-3">测试结果：</Text>
          {results.map((result, index) => (
            <View key={index} className="mb-3 p-3 bg-gray-50 rounded">
              <View className="flex justify-between items-center mb-2">
                <Text className="font-medium">
                  status={result.status} ({result.statusName})
                </Text>
                <Text className={`text-sm ${result.success ? 'text-green-600' : 'text-red-600'}`}>
                  {result.success ? '成功' : '失败'}
                </Text>
              </View>
              <Text className="text-sm text-gray-600">
                返回数据: {result.count} 条
              </Text>
              {result.error && (
                <Text className="text-sm text-red-600 mt-1">
                  错误: {result.error}
                </Text>
              )}
              {result.data.length > 0 && (
                <View className="mt-2">
                  <Text className="text-xs text-gray-500">示例数据:</Text>
                  {result.data.slice(0, 2).map((item: any, idx: number) => (
                    <Text key={idx} className="text-xs text-gray-600 block">
                      ID:{item.id}, status:{item.status}, name:{item.goodsName || item.name}
                    </Text>
                  ))}
                </View>
              )}
            </View>
          ))}
        </View>
      )}

      {/* 调试日志 */}
      <View className="bg-white mx-4 mt-4 mb-4 p-4 rounded-lg">
        <View className="flex justify-between items-center mb-3">
          <Text className="font-bold">调试日志：</Text>
          <Button 
            size="small" 
            fill="outline"
            onClick={() => setLogs([])}
          >
            清空日志
          </Button>
        </View>
        <View className="max-h-60 overflow-y-auto">
          {logs.length > 0 ? (
            logs.map((log, index) => (
              <Text key={index} className="text-xs text-gray-600 block mb-1">
                {log}
              </Text>
            ))
          ) : (
            <Text className="text-xs text-gray-400">暂无日志</Text>
          )}
        </View>
      </View>

      {/* 使用说明 */}
      <View className="bg-yellow-50 mx-4 mb-4 p-4 rounded-lg">
        <Text className="font-bold mb-2 text-yellow-800">使用说明：</Text>
        <View className="space-y-1">
          <Text className="text-sm text-yellow-700">1. 点击测试按钮调用 getUserGifts API</Text>
          <Text className="text-sm text-yellow-700">2. 检查返回的数据状态是否与请求参数一致</Text>
          <Text className="text-sm text-yellow-700">3. 查看调试日志了解详细的API调用过程</Text>
          <Text className="text-sm text-yellow-700">4. 如果状态筛选不正确，说明后端或前端有问题</Text>
        </View>
      </View>
    </View>
  )
}

export default ApiTest
