import React, { useEffect, useState, useRef } from "react"; import { RefreshCw, AlertCircle } from "lucide-react"; import { usageApi, type AppType } from "@/lib/api"; import { UsageResult, UsageData } from "../types"; interface UsageFooterProps { providerId: string; appType: AppType; usageEnabled: boolean; // 是否启用了用量查询 } const UsageFooter: React.FC = ({ providerId, appType, usageEnabled, }) => { const [usage, setUsage] = useState(null); const [loading, setLoading] = useState(false); // 记录上次请求的关键参数,防止重复请求 const lastFetchParamsRef = useRef(""); const fetchUsage = async () => { // 防止并发请求 if (loading) return; setLoading(true); try { const result = await usageApi.query(providerId, appType); setUsage(result); } catch (error: any) { console.error("查询用量失败:", error); setUsage({ success: false, error: error?.message || "查询失败", }); } finally { setLoading(false); } }; useEffect(() => { if (usageEnabled) { // 生成当前参数的唯一标识(包含 usageEnabled 状态) const currentParams = `${providerId}-${appType}-${usageEnabled}`; // 只有参数真正变化时才发起请求 if (currentParams !== lastFetchParamsRef.current) { lastFetchParamsRef.current = currentParams; fetchUsage(); } } else { // 如果禁用了,清空记录和数据 lastFetchParamsRef.current = ""; setUsage(null); } }, [providerId, usageEnabled, appType]); // 只在启用用量查询且有数据时显示 if (!usageEnabled || !usage) return null; // 错误状态 if (!usage.success) { return (
{usage.error || "查询失败"}
{/* 刷新按钮 */}
); } const usageDataList = usage.data || []; // 无数据时不显示 if (usageDataList.length === 0) return null; return (
{/* 标题行:包含刷新按钮 */}
套餐用量
{/* 套餐列表 */}
{usageDataList.map((usageData, index) => ( ))}
); }; // 单个套餐数据展示组件 const UsagePlanItem: React.FC<{ data: UsageData }> = ({ data }) => { const { planName, extra, isValid, invalidMessage, total, used, remaining, unit, } = data; // 判断套餐是否失效(isValid 为 false 或未定义时视为有效) const isExpired = isValid === false; return (
{/* 标题部分:25% */}
{planName ? ( 💰 {planName} ) : ( )}
{/* 扩展字段:30% */}
{extra && ( {extra} )} {isExpired && ( {invalidMessage || "已失效"} )}
{/* 用量信息:45% */}
{/* 总额度 */} {total !== undefined && ( <> 总: {total === -1 ? "∞" : total.toFixed(2)} | )} {/* 已用额度 */} {used !== undefined && ( <> 使用: {used.toFixed(2)} | )} {/* 剩余额度 - 突出显示 */} {remaining !== undefined && ( <> 剩余: {remaining.toFixed(2)} )} {unit && ( {unit} )}
); }; export default UsageFooter;