1+ import React , { useState , useEffect } from 'react' ;
2+ import { getApiBalance } from '../../../services/api/base' ;
3+ import { useLanguage } from '../../../hooks/useLanguage' ;
4+
5+ const KeyBalanceDisplay = ( { apiKey, apiType, proxyUrl } ) => {
6+ const { t } = useLanguage ( ) ;
7+ const [ balanceInfo , setBalanceInfo ] = useState ( null ) ;
8+ const [ loading , setLoading ] = useState ( false ) ;
9+ const [ error , setError ] = useState ( null ) ;
10+
11+ const fetchBalance = async ( ) => {
12+ if ( ! apiKey || ! apiType ) return ;
13+
14+ setLoading ( true ) ;
15+ setError ( null ) ;
16+
17+ try {
18+ const result = await getApiBalance ( apiKey , apiType , proxyUrl ) ;
19+ if ( result . success ) {
20+ setBalanceInfo ( result ) ;
21+ setError ( null ) ;
22+ } else {
23+ setError ( result . error ) ;
24+ setBalanceInfo ( null ) ;
25+ }
26+ } catch ( err ) {
27+ setError ( err . message ) ;
28+ setBalanceInfo ( null ) ;
29+ } finally {
30+ setLoading ( false ) ;
31+ }
32+ } ;
33+
34+ useEffect ( ( ) => {
35+ // 只有当apiType支持余额查询时才自动获取
36+ if ( apiType === 'siliconcloud' && apiKey ) {
37+ fetchBalance ( ) ;
38+ }
39+ // eslint-disable-next-line react-hooks/exhaustive-deps
40+ } , [ apiKey , apiType , proxyUrl ] ) ;
41+
42+ // 如果不是支持余额查询的API类型,则不显示组件
43+ if ( apiType !== 'siliconcloud' ) {
44+ return null ;
45+ }
46+
47+ // 根据状态返回相应的显示内容
48+ if ( loading ) {
49+ return < div className = "key-model" > { t ( 'balance.title' ) } : { t ( 'balance.refreshing' ) } </ div > ;
50+ }
51+
52+ if ( error ) {
53+ return < div className = "key-model" > { t ( 'balance.title' ) } : { t ( 'balance.fetchFailed' ) } </ div > ;
54+ }
55+
56+ if ( balanceInfo ) {
57+ return < div className = "key-model" > { t ( 'balance.title' ) } : ¥{ Number ( balanceInfo . balance ) . toFixed ( 2 ) } </ div > ;
58+ }
59+
60+ return null ;
61+ } ;
62+
63+ export default KeyBalanceDisplay ;
0 commit comments