'use client'; import { useState, useEffect, useCallback,useRef } from 'react'; import { RefreshCw } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { getCaptchaApiV1AuthCaptchaGet } from '@/lib/api/sdk.gen'; import type { CaptchaResponse } from '@/lib/api/types.gen'; interface CaptchaInputProps { value: string; onChange: (value: string) => void; onCaptchaChange?: (captchaData: CaptchaResponse | null) => void; className?: string; instanceId?: string; } export function CaptchaInput({ value, onChange, onCaptchaChange, className = '', instanceId = 'default' }: CaptchaInputProps) { const [captchaData, setCaptchaData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(''); const isInitialized = useRef(false); // 初始化验证码 useEffect(() => { if (!isInitialized.current) { isInitialized.current = true; const initialFetch = async () => { console.log(`[CaptchaInput-${instanceId}] 初始化获取验证码...`); setLoading(true); setError(''); try { const response = await getCaptchaApiV1AuthCaptchaGet(); console.log(`[CaptchaInput-${instanceId}] API验证码获取成功:`, response); setCaptchaData(response.data); if (onCaptchaChange) { onCaptchaChange(response.data); } } catch (err) { console.error(`[CaptchaInput-${instanceId}] 验证码获取失败:`, err); setError('获取验证码失败,请重试'); } finally { setLoading(false); } }; initialFetch(); } }, [instanceId, onCaptchaChange]); const fetchCaptcha = useCallback(async () => { console.log(`[CaptchaInput-${instanceId}] 刷新验证码...`); setLoading(true); setError(''); try { const response = await getCaptchaApiV1AuthCaptchaGet(); console.log(`[CaptchaInput-${instanceId}] API验证码获取成功:`, response); setCaptchaData(response.data); if (onCaptchaChange) { onCaptchaChange(response.data); } } catch (err) { console.error(`[CaptchaInput-${instanceId}] 验证码获取失败:`, err); setError('获取验证码失败,请重试'); } finally { setLoading(false); } }, [instanceId, onCaptchaChange]); const handleRefresh = () => { onChange(''); // 清空验证码输入 fetchCaptcha(); }; const handleCaptchaChange = (inputValue: string) => { onChange(inputValue); }; return (
handleCaptchaChange(e.target.value.toUpperCase())} maxLength={4} className="flex-1" disabled={loading} />
{loading ? (
) : error ? (
获取失败
) : (
{captchaData && ( 验证码 { // 如果图片加载失败,隐藏错误图片 e.currentTarget.style.display = 'none'; setError('图片加载失败'); }} /> )}
)}
); }