import { I18N_TECHNICAL_TEXT } from '../../i18n/technicalText.js';
import { formatNumber } from '../../helpers/safeDisplay';
import { Check as ActionCheck } from '@/components/common/icons/ActionIcons';
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { timestamp2string } from '../../helpers/utils';
import { useTranslation } from 'react-i18next';
import { useThrottledCallback } from 'use-debounce';
import { Typography, Button, Spin, Table, Tag, Select } from '@/components/ui';
import { CheckCircle, Clock, XCircle } from 'lucide-react';
import { Button as AntButton, Input as AntInput } from 'antd';
import {
MAX_CUSTOM_AMOUNT,
normalizeCustomAmount,
} from './customRechargeAmount';
import {
API,
showError,
showInfo,
showSuccess,
renderQuota,
getQuotaPerUnit,
} from '../../helpers';
import AmountCard from '../Recharge/AmountCard';
import usePayPalQuote from '../../hooks/common/usePayPalQuote';
import WechatQRModal from '../../components/topup/modals/WechatQRModal';
import PaymentConfirmModal from '../../components/topup/modals/PaymentConfirmModal';
import OrgPageHeader from './components/OrgPageHeader';
import '../../styles/org-center.css';
import { orgStatusColor } from './components/orgStatus';
import { usePerm } from '../../authz';
import {
formatPayPalUSD,
getPayPalReturnState,
parsePayPalQuote,
requestPayPalOrder,
removePayPalReturnState,
} from '../../helpers/paypalPayment';
const { Text } = Typography;
const OrgRecharge = ({ orgId }) => {
const { t } = useTranslation();
// 发起充值:本页仅管理员可进(路由守卫),旧判断恒为可操作;已切新体系按 org.recharge.pay 判断
const canPay = usePerm('org.recharge.pay', true);
// 企业信息
const [orgQuota, setOrgQuota] = useState(0);
const [orgGiftQuota, setOrgGiftQuota] = useState(0);
const [orgUsedQuota, setOrgUsedQuota] = useState(0);
// 充值配置
const [presetAmounts, setPresetAmounts] = useState([]);
const [payMethods, setPayMethods] = useState([]);
const [enableWechatTopUp, setEnableWechatTopUp] = useState(false);
const [enableAlipayTopUp, setEnableAlipayTopUp] = useState(false);
const [enablePayPalTopUp, setEnablePayPalTopUp] = useState(false);
const [infoLoading, setInfoLoading] = useState(true);
// 充值交互状态
const [selectedPreset, setSelectedPreset] = useState(null);
const [selectedPresetObj, setSelectedPresetObj] = useState(null);
const [payWay, setPayWay] = useState('');
const [confirmOpen, setConfirmOpen] = useState(false);
const [confirmLoading, setConfirmLoading] = useState(false);
const [amountLoading, setAmountLoading] = useState(false);
// 自定义充值(与预设档位互斥;自定义金额无折扣,原价到账)
const [isCustomMode, setIsCustomMode] = useState(false);
const [customAmount, setCustomAmount] = useState(null);
const [customAmountExceeded, setCustomAmountExceeded] = useState(false);
// Clamp the amount immediately; throttle feedback so payment state never lags.
const reportCustomAmountExceeded = useThrottledCallback(
() => setCustomAmountExceeded(true),
200,
{ leading: false, trailing: true },
);
const clearCustomAmountError = () => {
reportCustomAmountExceeded.cancel();
setCustomAmountExceeded(false);
};
const [customUnit, setCustomUnit] = useState(1000); // 1000=千 / 10000=万
const customEffectiveAmount = useMemo(() => {
if (!customAmount || customAmount < 1) return 0;
return Math.floor(Number(customAmount)) * customUnit;
}, [customAmount, customUnit]);
const customValid =
Number.isInteger(customAmount) &&
customAmount >= 1 &&
customAmount <= MAX_CUSTOM_AMOUNT &&
customEffectiveAmount >= 1000;
// 当前生效的金额/折扣/赠送(自定义优先)
const effectiveAmountYuan = isCustomMode
? customEffectiveAmount
: selectedPresetObj?.value || 0;
const effectiveDiscount = isCustomMode
? 1.0
: selectedPresetObj?.discount || 1.0;
const effectiveBonus = isCustomMode ? 0 : selectedPresetObj?.bonus || 0;
const {
quote: payPalQuote,
setQuote: setPayPalQuote,
loading: quoteLoading,
refresh: refreshPayPalQuote,
} = usePayPalQuote(
'/api/org/topup/paypal/amount',
isCustomMode
? { custom_amount: customEffectiveAmount }
: { amount_option_id: selectedPresetObj?.id },
payWay === 'paypal' &&
effectiveAmountYuan > 0 &&
(!isCustomMode || customValid),
orgId,
);
// 微信二维码
const [wechatQRVisible, setWechatQRVisible] = useState(false);
const [wechatOrderData, setWechatOrderData] = useState(null);
// 充值记录
const [history, setHistory] = useState([]);
const [historyTotal, setHistoryTotal] = useState(0);
const [historyPage, setHistoryPage] = useState(1);
const [historyPageSize, setHistoryPageSize] = useState(10);
const [historyLoading, setHistoryLoading] = useState(false);
const [refreshHistory, setRefreshHistory] = useState(0);
const orgHeaders = useMemo(() => ({ 'X-Org-Id': String(orgId) }), [orgId]);
// 获取企业配额
const fetchOrgQuota = useCallback(async () => {
try {
const res = await API.get('/api/org/quota', { headers: orgHeaders });
if (res.data.success) {
const { quota, gift_quota, used_quota } = res.data.data;
setOrgQuota(quota || 0);
setOrgGiftQuota(gift_quota || 0);
setOrgUsedQuota(used_quota || 0);
}
} catch (e) {
// ignore
}
}, [orgHeaders]);
// 获取充值配置
const fetchTopUpInfo = useCallback(async () => {
setInfoLoading(true);
try {
const res = await API.get('/api/org/topup/info', { headers: orgHeaders });
if (res.data.success) {
const data = res.data.data;
setEnableWechatTopUp(data.enable_wechat_topup || false);
setEnableAlipayTopUp(data.enable_alipay_topup || false);
setEnablePayPalTopUp(data.enable_paypal_topup || false);
setPayMethods(data.pay_methods || []);
if (data.amount_options_v2 && data.amount_options_v2.length > 0) {
const sorted = [...data.amount_options_v2].sort(
(a, b) => (a.sort || 0) - (b.sort || 0),
);
setPresetAmounts(
sorted.map((opt) => ({
id: opt.id,
value: opt.amount,
discount: opt.discount || 1.0,
label: opt.label,
badge: opt.badge,
badgeColor: opt.badge_color,
isRecommend: opt.is_recommend,
isHot: opt.is_hot,
bonus: opt.bonus,
minVipLevel: opt.min_vip_level,
})),
);
}
}
} catch (e) {
showError(t('获取充值配置失败'));
} finally {
setInfoLoading(false);
}
}, [orgHeaders, t]);
// 获取充值记录
const fetchHistory = useCallback(
async (page = 1) => {
setHistoryLoading(true);
try {
const res = await API.get(
`/api/org/topup?p=${page}&page_size=${historyPageSize}`,
{
headers: orgHeaders,
},
);
if (res.data.success) {
const data = res.data.data;
setHistory(data.items || []);
setHistoryTotal(data.total || 0);
} else {
showError(res.data.message);
}
} catch (e) {
showError(e.message);
} finally {
setHistoryLoading(false);
}
},
[historyPageSize, orgHeaders],
);
useEffect(() => {
fetchOrgQuota();
fetchTopUpInfo();
}, [fetchOrgQuota, fetchTopUpInfo]);
useEffect(() => {
fetchHistory(historyPage);
}, [fetchHistory, historyPage, refreshHistory]);
useEffect(() => {
const result = getPayPalReturnState(window.location.search);
if (!result) return;
if (result.status === 'success') showSuccess(t('PayPal 充值成功'));
else if (result.status === 'pending')
showInfo(t('PayPal 支付处理中,请稍后查看充值记录'));
else if (result.status === 'cancelled') showInfo(t('已取消 PayPal 支付'));
else showError(t('PayPal 支付确认失败,请稍后重试'));
fetchOrgQuota();
setRefreshHistory((previous) => previous + 1);
window.history.replaceState(
{},
'',
removePayPalReturnState(window.location.href),
);
// The callback query must be consumed exactly once on page entry.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const selectPreset = (preset) => {
clearCustomAmountError();
setSelectedPreset(preset.id);
setSelectedPresetObj(preset);
setIsCustomMode(false);
setCustomAmount(null);
};
const handleCustomAmountChange = (v) => {
const result = normalizeCustomAmount(v);
if (!result) return;
if (result.exceeded) {
reportCustomAmountExceeded();
} else {
clearCustomAmountError();
}
setCustomAmount(result.value);
if (result.value) {
setIsCustomMode(true);
setSelectedPreset(null);
setSelectedPresetObj(null);
} else {
setIsCustomMode(false);
}
};
const handleCustomUnitChange = (v) => {
setCustomUnit(v);
if (customAmount && Number(customAmount) > 0) {
setIsCustomMode(true);
setSelectedPreset(null);
setSelectedPresetObj(null);
}
};
// 自定义充值快速选择档位
const customQuickPicks = [
{ amount: 1, unit: 1000 },
{ amount: 5, unit: 1000 },
{ amount: 1, unit: 10000 },
{ amount: 5, unit: 10000 },
{ amount: 10, unit: 10000 },
];
const applyCustomQuickPick = (amount, unit) => {
clearCustomAmountError();
setCustomAmount(amount);
setCustomUnit(unit);
setIsCustomMode(true);
setSelectedPreset(null);
setSelectedPresetObj(null);
};
// 自定义充值预览额度(与后端 service.CalculateQuota 一致:originalMoney * QuotaPerUnit + bonus,自定义 bonus=0)
const customPreviewQuota =
customEffectiveAmount > 0
? customEffectiveAmount * (getQuotaPerUnit() || 500000)
: 0;
const handlePreTopUp = async (paymentType) => {
if (isCustomMode) {
if (!customValid) {
showError(t('自定义充值金额最少为 1000 元'));
return;
}
} else if (!selectedPresetObj) {
showError(t('请先选择充值金额'));
return;
}
setPayWay(paymentType);
if (paymentType === 'paypal') {
if (!enablePayPalTopUp) {
showError(t('管理员未开启 PayPal 充值!'));
return;
}
setAmountLoading(true);
try {
if (!(await refreshPayPalQuote())) return;
} catch (error) {
showError(error?.message || t('获取金额失败'));
return;
} finally {
setAmountLoading(false);
}
}
setConfirmOpen(true);
};
const buildPayBody = () =>
isCustomMode
? { custom_amount: customEffectiveAmount }
: { amount_option_id: selectedPresetObj.id };
const isMobile = /iPhone|Android|iPad|Mobile/i.test(navigator.userAgent);
const handleConfirmPay = async () => {
if (!isCustomMode && !selectedPresetObj) return;
if (isCustomMode && !customValid) return;
setConfirmLoading(true);
try {
let res;
const payBody = buildPayBody();
if (payWay === 'wxpay' && enableWechatTopUp) {
const wechatEndpoint = isMobile
? '/api/org/topup/wechat/h5'
: '/api/org/topup/wechat/native';
res = await API.post(wechatEndpoint, payBody, { headers: orgHeaders });
if (res.data.success) {
if (isMobile) {
// H5:直接跳转微信支付页
window.location.href = res.data.data.h5_url;
setConfirmOpen(false);
const onFocus = () => {
fetchOrgQuota();
setRefreshHistory((p) => p + 1);
window.removeEventListener('focus', onFocus);
};
window.addEventListener('focus', onFocus);
} else {
// Native:弹出二维码
setWechatOrderData(res.data.data);
setConfirmOpen(false);
setWechatQRVisible(true);
}
return;
}
} else if (payWay === 'paypal' && enablePayPalTopUp) {
res = await requestPayPalOrder(
API,
'/api/org/topup/paypal',
{ ...payBody, quote_token: payPalQuote?.quoteToken },
{ headers: orgHeaders, skipErrorHandler: true },
);
if (res.data.success && res.data.data?.approval_url) {
setPayPalQuote(parsePayPalQuote(res));
window.location.href = res.data.data.approval_url;
return;
}
if (
res.status === 202 &&
res.data?.message === 'PAYPAL_ORDER_CREATING'
) {
showInfo(t('PayPal 订单创建中,请稍后重试'));
return;
}
} else if (payWay === 'alipay' && enableAlipayTopUp) {
const alipayEndpoint = isMobile
? '/api/org/topup/alipay/wap'
: '/api/org/topup/alipay/pc';
res = await API.post(alipayEndpoint, payBody, { headers: orgHeaders });
if (res.data.success) {
// Safari 会拦截 await 之后的 window.open(用户手势已过期),改为同标签跳转
const isSafari =
navigator.userAgent.indexOf('Safari') > -1 &&
navigator.userAgent.indexOf('Chrome') < 1;
if (isSafari) {
window.location.href = res.data.data.pay_url;
return;
}
window.open(res.data.data.pay_url, '_blank');
setConfirmOpen(false);
// 用户从支付宝标签页切回时自动刷新余额和记录
const onFocus = () => {
fetchOrgQuota();
setRefreshHistory((p) => p + 1);
window.removeEventListener('focus', onFocus);
};
window.addEventListener('focus', onFocus);
return;
}
}
// 失败处理
const msg = res?.data?.message || t('支付请求失败');
showError(msg);
} catch (e) {
const code = e?.response?.data?.message;
if (payWay === 'paypal' && code?.startsWith('PAYPAL_QUOTE_')) {
try {
const response = await API.post(
'/api/org/topup/paypal/amount',
buildPayBody(),
{ headers: orgHeaders },
);
if (!response.data.success) throw new Error(response.data.message);
setPayPalQuote(parsePayPalQuote(response));
showInfo(t('PayPal 报价已更新,请重新确认'));
} catch {
showError(t('获取金额失败'));
}
} else {
showError(e?.response?.data?.message || t('支付请求失败'));
}
} finally {
setConfirmLoading(false);
}
};
const handleWechatComplete = (success) => {
setWechatQRVisible(false);
setWechatOrderData(null);
if (success) {
showSuccess(t('充值成功!'));
fetchOrgQuota();
setRefreshHistory((p) => p + 1);
}
};
const renderAmount = () => {
if (payWay === 'paypal') {
return formatPayPalUSD(payPalQuote?.payAmount);
}
if (effectiveAmountYuan <= 0) return '';
const pay = effectiveAmountYuan * effectiveDiscount;
return `${formatNumber(pay, 2, '0.00')} ${t('元')}`;
};
// 充值记录状态渲染
const renderStatus = (status) => {
const map = {
success: {
icon:
{t('为企业账户补充额度,支持团队持续调用模型。')}
{t('为企业账户充值,额度用于团队模型调用。')}
{customInvalid ? t('当前 ¥{{amount}},未达到最低 ¥1,000', { amount: customEffectiveAmount.toLocaleString(), }) : `${t('最少 1000 元,必须为 1000 元的整倍数')};${t('原价到账,不参与折扣')}`}
{t('暂无可用的支付方式,请联系管理员配置')}
)}{t('暂无充值档位,请联系管理员配置')}
)}