'use client'; import { useEffect, useState } from 'react'; import { CloseIcon, SettingsIcon } from './Icons'; import { Dialog, DialogContent, DialogTitle, } from '@/components/ui/dialog'; export default function HoldingEditModal({ fund, holding, onClose, onSave }) { const [mode, setMode] = useState('amount'); // 'amount' | 'share' const dwjz = fund?.dwjz || fund?.gsz || 0; const [share, setShare] = useState(''); const [cost, setCost] = useState(''); const [amount, setAmount] = useState(''); const [profit, setProfit] = useState(''); useEffect(() => { if (holding) { const s = holding.share || 0; const c = holding.cost || 0; setShare(String(s)); setCost(String(c)); if (dwjz > 0) { const a = s * dwjz; const p = (dwjz - c) * s; setAmount(a.toFixed(2)); setProfit(p.toFixed(2)); } } }, [holding, fund, dwjz]); const handleModeChange = (newMode) => { if (newMode === mode) return; setMode(newMode); if (newMode === 'share') { if (amount && dwjz > 0) { const a = parseFloat(amount); const p = parseFloat(profit || 0); const s = a / dwjz; const principal = a - p; const c = s > 0 ? principal / s : 0; setShare(s.toFixed(2)); setCost(c.toFixed(4)); } } else { if (share && dwjz > 0) { const s = parseFloat(share); const c = parseFloat(cost || 0); const a = s * dwjz; const p = (dwjz - c) * s; setAmount(a.toFixed(2)); setProfit(p.toFixed(2)); } } }; const handleSubmit = (e) => { e.preventDefault(); let finalShare = 0; let finalCost = 0; if (mode === 'share') { if (!share || !cost) return; finalShare = Number(Number(share).toFixed(2)); finalCost = Number(cost); } else { if (!amount || !dwjz) return; const a = Number(amount); const p = Number(profit || 0); const rawShare = a / dwjz; finalShare = Number(rawShare.toFixed(2)); const principal = a - p; finalCost = finalShare > 0 ? principal / finalShare : 0; } onSave({ share: finalShare, cost: finalCost }); onClose(); }; const isValid = mode === 'share' ? (share && cost && !isNaN(share) && !isNaN(cost)) : (amount && !isNaN(amount) && (!profit || !isNaN(profit)) && dwjz > 0); const handleOpenChange = (open) => { if (!open) { onClose?.(); } }; return ( 编辑持仓
设置持仓
{fund?.name}
#{fund?.code}
最新净值:{dwjz}
{mode === 'amount' ? ( <>
setAmount(e.target.value)} placeholder="请输入持有总金额" style={{ width: '100%', border: !amount ? '1px solid var(--danger)' : undefined }} />
setProfit(e.target.value)} placeholder="请输入持有总收益 (可为负)" style={{ width: '100%' }} />
) : ( <>
setShare(e.target.value)} placeholder="请输入持有份额" style={{ width: '100%', border: !share ? '1px solid var(--danger)' : undefined }} />
setCost(e.target.value)} placeholder="请输入持仓成本价" style={{ width: '100%', border: !cost ? '1px solid var(--danger)' : undefined }} />
)}
); }