import { useState, useEffect, useCallback } from 'react';
import { UserOrderStats } from '@/api/user';
import Taro from '@tarojs/taro';
import {pageShopOrder} from "@/api/shop/shopOrder";

/**
 * 订单统计Hook
 * 用于管理用户订单各状态的数量统计
 */
export const useOrderStats = () => {
  const [orderStats, setOrderStats] = useState<UserOrderStats>({
    pending: 0,    // 待付款
    paid: 0,       // 待发货
    shipped: 0,    // 待收货
    completed: 0,  // 已完成
    refund: 0,     // 退货/售后
    total: 0       // 总订单数
  });

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  /**
   * 获取订单统计数据
   */
  const fetchOrderStats = useCallback(async (showToast = false) => {
    try {
      setLoading(true);
      setError(null);

      // TODO 读取订单数量
      const pending = await pageShopOrder({ page: 1, limit: 1, userId: Taro.getStorageSync('UserId'), statusFilter: 0})
      const paid = await pageShopOrder({ page: 1, limit: 1, userId: Taro.getStorageSync('UserId'), statusFilter: 1})
      const shipped = await pageShopOrder({ page: 1, limit: 1, userId: Taro.getStorageSync('UserId'), statusFilter: 3})
      const completed = await pageShopOrder({ page: 1, limit: 1, userId: Taro.getStorageSync('UserId'), statusFilter: 5})
      const refund = await pageShopOrder({ page: 1, limit: 1, userId: Taro.getStorageSync('UserId'), statusFilter: 6})
      const total = await pageShopOrder({ page: 1, limit: 1, userId: Taro.getStorageSync('UserId')})
      setOrderStats({
        pending: pending?.count || 0,
        paid: paid?.count || 0,
        shipped: shipped?.count || 0,
        completed: completed?.count || 0,
        refund: refund?.count || 0,
        total: total?.count || 0
      })

      if (showToast) {
        Taro.showToast({
          title: '数据已更新',
          icon: 'success',
          duration: 1500
        });
      }
    } catch (err: any) {
      const errorMessage = err.message || '获取订单统计失败';
      setError(errorMessage);

      console.error('获取订单统计失败:', err);

      if (showToast) {
        Taro.showToast({
          title: errorMessage,
          icon: 'error',
          duration: 2000
        });
      }
    } finally {
      setLoading(false);
    }
  }, []);

  /**
   * 刷新订单统计数据
   */
  const refreshOrderStats = useCallback(() => {
    return fetchOrderStats(true);
  }, [fetchOrderStats]);

  /**
   * 获取指定状态的订单数量
   */
  const getOrderCount = useCallback((status: keyof UserOrderStats) => {
    return orderStats[status] || 0;
  }, [orderStats]);

  /**
   * 检查是否有待处理的订单
   */
  const hasPendingOrders = useCallback(() => {
    return orderStats.pending > 0 || orderStats.paid > 0 || orderStats.shipped > 0;
  }, [orderStats]);

  /**
   * 获取总的待处理订单数量
   */
  const getTotalPendingCount = useCallback(() => {
    return orderStats.pending + orderStats.paid + orderStats.shipped;
  }, [orderStats]);

  // 组件挂载时自动获取数据
  useEffect(() => {
    fetchOrderStats();
  }, [fetchOrderStats]);

  return {
    orderStats,
    loading,
    error,
    fetchOrderStats,
    refreshOrderStats,
    getOrderCount,
    hasPendingOrders,
    getTotalPendingCount
  };
};

export default useOrderStats;
