blob: 7a2f9b330625df340c1cb31aa7e80b77fbad51ad [file] [log] [blame]
// export default Recharge;
import React, { useState } from 'react';
import axios from 'axios';
import { useUser } from '../../context/UserContext';
const UserRecharge = () => {
const [amount, setAmount] = useState('');
const [loading, setLoading] = useState(false);
const [message, setMessage] = useState('');
const [showPayDialog, setShowPayDialog] = useState(false);
const [payProcessing, setPayProcessing] = useState(false);
const { user } = useUser();
const userId = user?.userId;
// 点击提交充值,打开模拟支付弹窗
const handleSubmit = () => {
if (!userId) {
setMessage('未登录,无法充值');
return;
}
if (!amount || isNaN(amount) || Number(amount) <= 0) {
setMessage('请输入有效的充值金额');
return;
}
setMessage('');
setShowPayDialog(true);
};
// 模拟支付弹窗点击“确认支付”
const handlePayConfirm = async () => {
setPayProcessing(true);
setMessage('');
// 模拟支付等待 2 秒
setTimeout(async () => {
try {
// 支付成功后调用后端充值接口
const response = await axios.post('/echo/user/recharge', null, {
params: {
userId,
amount: Number(amount),
},
});
setMessage(response.data.message || '充值成功!');
setAmount('');
} catch (error) {
setMessage(error.response?.data?.message || '充值失败,请重试');
} finally {
setPayProcessing(false);
setShowPayDialog(false);
}
}, 2000);
};
// 取消支付弹窗
const handlePayCancel = () => {
setShowPayDialog(false);
setMessage('支付已取消');
};
return (
<div className="recharge-page" style={{ maxWidth: 400, margin: 'auto', padding: 20 }}>
<h2>充值服务</h2>
<div style={{ marginBottom: 12 }}>
<label>
充值金额:
<input
type="number"
min="1"
value={amount}
onChange={(e) => setAmount(e.target.value)}
disabled={loading || payProcessing}
style={{ marginLeft: 8, width: 120 }}
/>
</label>
</div>
<button onClick={handleSubmit} disabled={loading || payProcessing}>
{loading || payProcessing ? '处理中...' : '提交充值'}
</button>
{message && <p style={{ marginTop: 12 }}>{message}</p>}
{/* 模拟支付弹窗 */}
{showPayDialog && (
<div
style={{
position: 'fixed',
top: 0, left: 0, right: 0, bottom: 0,
backgroundColor: 'rgba(0,0,0,0.5)',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
zIndex: 1000,
}}
>
<div
style={{
backgroundColor: '#fff',
padding: 20,
borderRadius: 8,
width: 300,
textAlign: 'center',
boxShadow: '0 0 10px rgba(0,0,0,0.25)',
}}
>
<h3>模拟支付</h3>
<p>支付金额:{amount} 元</p>
{payProcessing ? (
<p>支付处理中,请稍候...</p>
) : (
<>
<button onClick={handlePayConfirm} style={{ marginRight: 10 }}>
确认支付
</button>
<button onClick={handlePayCancel}>取消</button>
</>
)}
</div>
</div>
)}
</div>
);
};
export default UserRecharge;