import React, {useState, useEffect, useCallback} from 'react'
import {View, Text, ScrollView} from '@tarojs/components'
import {ArrowDown} from '@nutui/icons-react-taro'
import {Empty, PullToRefresh, DatePicker,Space, Loading} from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro'
import {pageShopDealerCapital} from '@/api/shop/shopDealerCapital'
import {useDealerUser} from '@/hooks/useDealerUser'
import type {ShopDealerCapital} from '@/api/shop/shopDealerCapital/model'
import navTo from "@/utils/common";

const DealerCapital: 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 [capital, setCapital] = useState<ShopDealerCapital[]>([])
  const [currentPage, setCurrentPage] = useState<number>(1)
  const [hasMore, setHasMore] = useState<boolean>(true)

  const {dealerUser} = useDealerUser()

  // 获取订单数据
  const fetchCapital = 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 pageShopDealerCapital({
        page,
        limit: 10,
        month: date,
        userId: Taro.getStorageSync('UserId')
      })

      if (result?.list) {
        const newCapital = result.list.map(item => ({
          ...item,
          orderNo: item.orderNo
        }))

        if (page === 1) {
          setCapital(newCapital)
        } else {
          setCapital(prev => [...prev, ...newCapital])
        }

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

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

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

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

  const getFlowType = (index?: number) => {
    if (index === 10) return '电费收益'
    if (index === 20) return '提现支出'
    if (index === 30) return '转账支出'
    if (index === 40) return '转账收入'
    return 'warning'
  }

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

  const renderCapitalItem = (item: ShopDealerCapital) => (
    <View key={item.id} className="bg-white rounded-lg p-4 mb-3 shadow-sm"
          onClick={() => navTo(`/dealer/capital/detail?id=${item.id}`)}>
      <View className="flex justify-between items-start mb-1">
        <Text className="font-semibold text-gray-800">
          {getFlowType(item.flowType)}
        </Text>
        <Text className="text-lg text-orange-500 font-semibold">
          ¥{Number(item.money).toFixed(2)}
        </Text>
      </View>

      {item.orderNo && (
        <View className="flex justify-between items-center mb-1">
          <Text className="text-sm text-gray-400">
            {item.orderNo}
          </Text>
        </View>
      )}

      <View className="flex justify-between items-center mb-1">
        <Text className="text-sm text-gray-400">
          {item.createTime}
        </Text>
        <Text className="text-sm text-gray-400">
          我的收益：{item.money}
        </Text>
      </View>

    </View>
  )

  return (
    <View className="min-h-screen bg-gray-50">
      <PullToRefresh
        onRefresh={handleRefresh}
        disabled={refreshing}
        pullingText="下拉刷新"
        canReleaseText="释放刷新"
        refreshingText="刷新中..."
        completeText="刷新完成"
      >
        <ScrollView
          scrollY
          className={'h-screen'}
          onScrollToLower={handleLoadMore}
          lowerThreshold={50}
        >
          {/*筛选工具条*/}
          <Space
            className={'px-4 mt-4'}
          >
            <Text className={'text-sm'} onClick={() => setShow1(true)}>{date ? `${date}` : '请选择'}</Text>
            <ArrowDown size={10} className={'text-gray-400'} onClick={() => setShow1(true)}/>
          </Space>
          {/*账单列表*/}
          <View className="p-4">
            {loading && capital.length === 0 ? (
              <View className="text-center py-8">
                <Loading/>
                <Text className="text-gray-500 mt-2">加载中...</Text>
              </View>
            ) : capital.length > 0 ? (
              <>
                {capital.map(renderCapitalItem)}
                {loadingMore && (
                  <View className="text-center py-4">
                    <Loading/>
                    <Text className="text-gray-500 mt-1 text-sm">加载更多...</Text>
                  </View>
                )}
                {!hasMore && capital.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 DealerCapital
