import { View, Text, Image } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useState } from 'react'
import { distributorOrders } from '../../api'
import './orders.scss'

export default function Orders() {
  const [list, setList] = useState<any[]>([])
  const [loading, setLoading] = useState(true)

  useLoad(() => {
    fetchData()
  })

  const fetchData = async () => {
    try {
      const res: any = await distributorOrders()
      if (res.results) {
        setList(res.results)
      } else if (Array.isArray(res)) {
        setList(res)
      }
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '加载失败', icon: 'none' })
    } finally {
      setLoading(false)
    }
  }

  return (
    <View className='page-container'>
      {list.length > 0 ? (
          list.map((item: any) => (
              <View className='item' key={item.id}>
                  <View className='row'>
                      <Text className='order-no'>订单号: {item.wechat_trade_no || item.id}</Text>
                      <Text className='status'>{item.status === 'paid' ? '已支付' : item.status}</Text>
                  </View>
                  <View className='content'>
                      <Image className='img' src={item.config_image || ''} mode='aspectFill' />
                      <View className='info'>
                          <Text className='title'>{item.config_name || item.course_title || '商品'}</Text>
                          <Text className='price'>¥{item.total_price}</Text>
                      </View>
                  </View>
                  <View className='footer'>
                      <Text className='customer'>买家: {item.customer_name}</Text>
                      <Text className='time'>{item.created_at?.split('T')[0]}</Text>
                  </View>
              </View>
          ))
      ) : (
          <View className='empty'>暂无分销订单</View>
      )}
    </View>
  )
}
