import React, { useEffect, useState, useContext } from 'react'; import { API, showError, showInfo, showSuccess } from '../../helpers'; import { renderQuota, renderQuotaWithAmount, stringToColor, } from '../../helpers/render'; import { Layout, Typography, Card, Button, Modal, Toast, Input, InputNumber, Banner, Skeleton, } from '@douyinfe/semi-ui'; import { IconCreditCard, IconGift, IconPlus, IconLink, } from '@douyinfe/semi-icons'; import { SiAlipay, SiWechat } from 'react-icons/si'; import { useTranslation } from 'react-i18next'; import { UserContext } from '../../context/User'; import { StatusContext } from '../../context/Status/index.js'; const { Text } = Typography; const TopUp = () => { const { t } = useTranslation(); const [userState, userDispatch] = useContext(UserContext); const [statusState] = useContext(StatusContext); const [redemptionCode, setRedemptionCode] = useState(''); const [topUpCode, setTopUpCode] = useState(''); const [amount, setAmount] = useState(0.0); const [minTopUp, setMinTopUp] = useState(statusState?.status?.min_topup || 1); const [topUpCount, setTopUpCount] = useState(statusState?.status?.min_topup || 1); const [topUpLink, setTopUpLink] = useState(statusState?.status?.top_up_link || ''); const [enableOnlineTopUp, setEnableOnlineTopUp] = useState(statusState?.status?.enable_online_topup || false); const [userQuota, setUserQuota] = useState(0); const [isSubmitting, setIsSubmitting] = useState(false); const [open, setOpen] = useState(false); const [payWay, setPayWay] = useState(''); const [userDataLoading, setUserDataLoading] = useState(true); const [amountLoading, setAmountLoading] = useState(false); const [paymentLoading, setPaymentLoading] = useState(false); const [confirmLoading, setConfirmLoading] = useState(false); const getUsername = () => { if (userState.user) { return userState.user.username; } else { return 'null'; } }; const getUserRole = () => { if (!userState.user) return t('普通用户'); switch (userState.user.role) { case 100: return t('超级管理员'); case 10: return t('管理员'); case 0: default: return t('普通用户'); } }; const topUp = async () => { if (redemptionCode === '') { showInfo(t('请输入兑换码!')); return; } setIsSubmitting(true); try { const res = await API.post('/api/user/topup', { key: redemptionCode, }); const { success, message, data } = res.data; if (success) { showSuccess(t('兑换成功!')); Modal.success({ title: t('兑换成功!'), content: t('成功兑换额度:') + renderQuota(data), centered: true, }); setUserQuota((quota) => { return quota + data; }); if (userState.user) { const updatedUser = { ...userState.user, quota: userState.user.quota + data }; userDispatch({ type: 'login', payload: updatedUser }); } setRedemptionCode(''); } else { showError(message); } } catch (err) { showError(t('请求失败')); } finally { setIsSubmitting(false); } }; const openTopUpLink = () => { if (!topUpLink) { showError(t('超级管理员未设置充值链接!')); return; } window.open(topUpLink, '_blank'); }; const preTopUp = async (payment) => { if (!enableOnlineTopUp) { showError(t('管理员未开启在线充值!')); return; } setPaymentLoading(true); try { await getAmount(); if (topUpCount < minTopUp) { showError(t('充值数量不能小于') + minTopUp); return; } setPayWay(payment); setOpen(true); } catch (error) { showError(t('获取金额失败')); } finally { setPaymentLoading(false); } }; const onlineTopUp = async () => { if (amount === 0) { await getAmount(); } if (topUpCount < minTopUp) { showError('充值数量不能小于' + minTopUp); return; } setConfirmLoading(true); setOpen(false); try { const res = await API.post('/api/user/pay', { amount: parseInt(topUpCount), top_up_code: topUpCode, payment_method: payWay, }); if (res !== undefined) { const { message, data } = res.data; if (message === 'success') { let params = data; let url = res.data.url; let form = document.createElement('form'); form.action = url; form.method = 'POST'; let isSafari = navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Chrome') < 1; if (!isSafari) { form.target = '_blank'; } for (let key in params) { let input = document.createElement('input'); input.type = 'hidden'; input.name = key; input.value = params[key]; form.appendChild(input); } document.body.appendChild(form); form.submit(); document.body.removeChild(form); } else { showError(data); } } else { showError(res); } } catch (err) { console.log(err); showError(t('支付请求失败')); } finally { setConfirmLoading(false); } }; const getUserQuota = async () => { setUserDataLoading(true); let res = await API.get(`/api/user/self`); const { success, message, data } = res.data; if (success) { setUserQuota(data.quota); userDispatch({ type: 'login', payload: data }); } else { showError(message); } setUserDataLoading(false); }; useEffect(() => { if (userState?.user?.id) { setUserDataLoading(false); setUserQuota(userState.user.quota); } else { getUserQuota().then(); } }, []); useEffect(() => { if (statusState?.status) { setMinTopUp(statusState.status.min_topup || 1); setTopUpCount(statusState.status.min_topup || 1); setTopUpLink(statusState.status.top_up_link || ''); setEnableOnlineTopUp(statusState.status.enable_online_topup || false); } }, [statusState?.status]); const renderAmount = () => { return amount + ' ' + t('元'); }; const getAmount = async (value) => { if (value === undefined) { value = topUpCount; } setAmountLoading(true); try { const res = await API.post('/api/user/amount', { amount: parseFloat(value), top_up_code: topUpCode, }); if (res !== undefined) { const { message, data } = res.data; if (message === 'success') { setAmount(parseFloat(data)); } else { setAmount(0); Toast.error({ content: '错误:' + data, id: 'getAmount' }); } } else { showError(res); } } catch (err) { console.log(err); } setAmountLoading(false); }; const handleCancel = () => { setOpen(false); }; return (
{t('充值确认')}
} visible={open} onOk={onlineTopUp} onCancel={handleCancel} maskClosable={false} size={'small'} centered={true} confirmLoading={confirmLoading} >
{t('充值数量')}: {topUpCount}
{t('实付金额')}: {amountLoading ? ( ) : ( {renderAmount()} )}
{userDataLoading ? ( ) : (
{t('尊敬的')} {getUsername()}
)}
{t('当前余额')}
{userDataLoading ? ( ) : (
{renderQuota(userState?.user?.quota || userQuota)}
)}
{t('历史消耗')}
{userDataLoading ? ( ) : (
{renderQuota(userState?.user?.used_quota || 0)}
)}
{t('用户分组')}
{userDataLoading ? ( ) : (
{userState?.user?.group || t('默认')}
)}
{t('用户角色')}
{userDataLoading ? ( ) : (
{getUserRole()}
)}
{userDataLoading ? ( ) : (
ID: {userState?.user?.id || '---'}
)}
{t('兑换余额')}
{t('使用兑换码充值余额')}
{t('兑换码')} setRedemptionCode(value)} size="large" className="!rounded-lg" prefix={} />
{topUpLink && ( )}
{t('在线充值')}
{t('支持多种支付方式')}
{t('充值数量')} {amountLoading ? ( ) : ( {t('实付金额:') + ' ' + renderAmount()} )}
{ if (value && value >= 1) { setTopUpCount(value); await getAmount(value); } }} onBlur={(e) => { const value = parseInt(e.target.value); if (!value || value < 1) { setTopUpCount(1); getAmount(1); } }} size="large" className="!rounded-lg w-full" prefix={} formatter={(value) => value ? `${value}` : ''} parser={(value) => value ? parseInt(value.replace(/[^\d]/g, '')) : 0} />
{!enableOnlineTopUp && ( {t('在线充值功能未开启')}
} description={
{t('管理员未开启在线充值功能,请联系管理员开启或使用兑换码充值。')}
} /> )}
); }; export default TopUp;