import React, {useState, useEffect, useCallback} from 'react'
import {View, Text, ScrollView} from '@tarojs/components'
import {Empty, PullToRefresh, Space, Loading, DatePicker} from '@nutui/nutui-react-taro'
import {ArrowDown} from '@nutui/icons-react-taro'
import Taro from '@tarojs/taro'
import {pageShopDealerOrder} from '@/api/shop/shopDealerOrder'
import {useDealerUser} from '@/hooks/useDealerUser'
import type {ShopDealerOrder} from '@/api/shop/shopDealerOrder/model'

interface OrderWithDetails extends ShopDealerOrder {
  orderNo?: string
  customerName?: string
  userCommission?: string
}

const DealerOrder: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false)
  const d = new Date()
  const currMonth = `${d.getFullYear()}${d.getMonth() + 1}`;
  const currDate = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
  const [date, setDate] = useState(currMonth)
  const [show1, setShow1] = useState(false)
  const [refreshing, setRefreshing] = useState<boolean>(false)
  const [loadingMore, setLoadingMore] = useState<boolean>(false)
  const [orders, setOrders] = useState<OrderWithDetails[]>([])
  const [currentPage, setCurrentPage] = useState<number>(1)
  const [hasMore, setHasMore] = useState<boolean>(true)

  const {dealerUser} = useDealerUser()

  // 获取订单数据
  const fetchOrders = useCallback(async (page: number = 1, isRefresh: boolean = false) => {
    if (!dealerUser?.userId) return

    try {
      if (isRefresh) {
        setRefreshing(true)
      } else if (page === 1) {
        setLoading(true)
      } else {
        setLoadingMore(true)
      }

      const result = await pageShopDealerOrder({
        isInvalid: 0,
        isSettled: 1,
        resourceId: Taro.getStorageSync('UserId'),
        month: date,
        page,
        limit: 10
      })

      if (result?.list) {
        const newOrders = result.list.map(order => ({
          ...order,
          orderNo: `${order.orderNo}`,
          customerName: `用户${order.userId}`,
          userCommission: order.firstMoney || '0.00'
        }))

        if (page === 1) {
          setOrders(newOrders)
        } else {
          setOrders(prev => [...prev, ...newOrders])
        }

        setHasMore(newOrders.length === 10)
        setCurrentPage(page)
      }

    } catch (error) {
      console.error('获取分销订单失败:', error)
      Taro.showToast({
        title: '获取订单失败',
        icon: 'error'
      })
    } finally {
      setLoading(false)
      setRefreshing(false)
      setLoadingMore(false)
    }
  }, [dealerUser?.userId, date])

  // 下拉刷新
  const handleRefresh = async () => {
    await fetchOrders(1, true)
  }

  // 加载更多
  const handleLoadMore = async () => {
    if (!loadingMore && hasMore) {
      await fetchOrders(currentPage + 1)
    }
  }

  // 初始化加载数据
  useEffect(() => {
    if (dealerUser?.userId) {
      fetchOrders(1)
    }
  }, [fetchOrders, date])

  const getStatusText = (isSettled?: number, isInvalid?: number) => {
    if (isInvalid === 1) return '未签约'
    if (isSettled === 1) return '已结算'
    return '待结算'
  }

  // const getStatusColor = (isSettled?: number, isInvalid?: number) => {
  //   if (isInvalid === 1) return 'danger'
  //   if (isSettled === 1) return 'success'
  //   return 'warning'
  // }

  const renderOrderItem = (order: OrderWithDetails) => (
    <View key={order.id} className="bg-white rounded-lg p-4 mb-3 shadow-sm">
      <View className="flex justify-between items-start mb-1">
        <Text className="font-semibold text-gray-800">
          订单号：{order.orderNo}
        </Text>
      </View>

      <View className="flex justify-between items-center mb-1">
        <Text className="text-sm text-gray-400">
          客户名称：{order.title}
        </Text>
      </View>

      {/* 添加收益用户信息显示 */}
      <View className="flex justify-between items-center mb-1 mt-2">
        <Text className="text-sm text-gray-400">
          收益计算
        </Text>
      </View>
      <View className="mb-1">
        {/* 间推收益用户 */}
        {(order.firstNickname || order.firstUserId) && (
          <Text className="text-sm text-gray-400 block">
            自有收益：{order.firstNickname || `用户${order.firstUserId}`} (¥{order.firstMoney || '0.00'})
          </Text>
        )}

        {/* 一级分销商 */}
        {(order.nickname || order.userId) && (
          <Text className="text-sm text-gray-400 block">
            合作方收益：{order.nickname || `用户${order.userId}`} (¥{order.secondMoney || '0.00'})
          </Text>
        )}

        {/* 三级分销商 */}
        {(order.thirdUserId !== undefined && order.thirdUserId > 0) && (
          <Text className="text-sm text-gray-400 block">
            联盟收益补贴：{order.thirdNickname || `用户${order.thirdUserId}`} (¥{order.thirdMoney || '0.00'})
          </Text>
        )}

        {/* 如果都没有信息 */}
        {!(order.firstNickname || order.firstUserId || order.nickname || order.userId || order.thirdNickname || order.thirdUserId) && (
          <Text className="text-sm text-gray-400 block">
            暂无收益用户
          </Text>
        )}
      </View>

      <View className="flex justify-between items-center mt-2">
        <Text className="text-sm text-gray-400">
          结算电量：{order.degreePrice}
        </Text>
        <Text className="text-sm text-gray-400">
          结算金额：{order.settledPrice}
        </Text>
      </View>

      <View className="flex justify-between items-center mb-1">
        <Text className="text-sm text-gray-400">
          单价：{order.price}
        </Text>
        <Text className="text-sm text-gray-400">
          税费：{order.rate}
        </Text>
      </View>

      <View className="flex justify-between items-center mb-1">
        <Text className="text-sm text-gray-400">
          实发金额：{order.payPrice}
        </Text>
        <Text className="text-sm text-gray-400">
          结算月份：{order.month}
        </Text>
      </View>

      <View className="flex justify-between items-center mb-1">
        <Text className="text-sm text-gray-400">
          结算状态：{getStatusText(order.isSettled, order.isInvalid)}
        </Text>
        <Text className="text-sm text-gray-400">
          {order.settleTime}
        </Text>
      </View>

      {/*<View className="flex justify-between items-center mb-1">*/}
      {/*  <Text className="text-sm text-gray-400">*/}
      {/*    {(order.thirdUserId && order.thirdUserId > 0) ? '获取收益' : '推荐收益'}*/}
      {/*  </Text>*/}
      {/*  <Text className="text-sm text-gray-400">*/}
      {/*    合作方收益：{getStatusText(order.isSettled, order.isInvalid)}*/}
      {/*  </Text>*/}
      {/*</View>*/}

      {/*<View className="flex justify-between items-center mb-1">*/}
      {/*  <Text className="text-sm text-gray-400">*/}
      {/*    {order.settleTime}*/}
      {/*  </Text>*/}
      {/*</View>*/}

    </View>
  )

  return (
    <View className="min-h-screen bg-gray-50">
      <PullToRefresh
        onRefresh={handleRefresh}
        disabled={refreshing}
        pullingText="下拉刷新"
        canReleaseText="释放刷新"
        refreshingText="刷新中..."
        completeText="刷新完成"
      >
        <ScrollView
          scrollY
          onScrollToLower={handleLoadMore}
          lowerThreshold={50}
        >
          {/*筛选工具条*/}
          <Space
            className={'p-4'}
          >
            <Text className={'text-sm'} onClick={() => setShow1(true)}>{date ? `${date}` : '请选择'}</Text>
            <ArrowDown size={10} className={'text-gray-400'} onClick={() => setShow1(true)}/>
          </Space>
          {/*账单列表*/}
          <View className="px-4">
            {loading && orders.length === 0 ? (
              <View className="text-center py-8">
                <Loading/>
                <Text className="text-gray-500 mt-2">加载中...</Text>
              </View>
            ) : orders.length > 0 ? (
              <>
                {orders.map(renderOrderItem)}
                {loadingMore && (
                  <View className="text-center py-4">
                    <Loading/>
                    <Text className="text-gray-500 mt-1 text-sm">加载更多...</Text>
                  </View>
                )}
                {!hasMore && orders.length > 0 && (
                  <View className="text-center py-4">
                    <Text className="text-gray-400 text-sm">没有更多数据了</Text>
                  </View>
                )}
              </>
            ) : (
              <Empty description="暂无电费订单" style={{
                backgroundColor: 'transparent'
              }}/>
            )}
          </View>
        </ScrollView>
      </PullToRefresh>
      <DatePicker
        title="日期选择"
        visible={show1}
        pickerProps={{
          popupProps: {zIndex: 1220},
        }}
        type={'year-month'}
        defaultValue={new Date(`${currDate}`)}
        showChinese
        onCancel={() => setShow1(false)}
        onConfirm={(_, values) => {
          setShow1(false)
          setDate(`${values[0]}${values[1]}`)
        }}
      />
    </View>
  )
}

export default DealerOrder
