/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import { Trans } from 'react-i18next';
import {
Check as ActionCheck,
ArrowUpRight as ActionArrowUpRight,
} from '@/components/common/icons/ActionIcons';
import React, { useEffect, useState, useContext } from 'react';
import { Segmented } from 'antd';
import {
Typography,
Tag,
Modal,
Spin,
Empty,
Banner,
Progress,
} from '@/components/ui';
import { Crown, Zap, Clock } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { UserContext } from '../../context/User';
import { API, showError, showSuccess, renderQuota } from '../../helpers';
import MembershipHistoryModal from '../../components/membership/MembershipHistoryModal';
const { Text } = Typography;
// 方案时长(原型分段固定展示周卡/月卡/季卡)
const planTypeConfig = {
weekly: { label: '周卡' },
monthly: { label: '月卡' },
quarterly: { label: '季卡' },
};
const MembershipPanel = () => {
const { t, i18n } = useTranslation();
const [, userDispatch] = useContext(UserContext);
const [loading, setLoading] = useState(true);
const [membershipEnabled, setMembershipEnabled] = useState(false);
const [plans, setPlans] = useState([]);
const [, setTitle] = useState('会员订阅');
const [description, setDescription] = useState('');
// 当前会员信息
const [membershipInfo, setMembershipInfo] = useState(null);
const [infoLoading, setInfoLoading] = useState(true);
// 购买相关
const [selectedPlan, setSelectedPlan] = useState(null);
const [purchaseModalVisible, setPurchaseModalVisible] = useState(false);
const [purchasing, setPurchasing] = useState(false);
// 升级相关
const [upgradeModalVisible, setUpgradeModalVisible] = useState(false);
const [upgradeInfo, setUpgradeInfo] = useState(null);
const [upgradeLoading, setUpgradeLoading] = useState(false);
const [upgrading, setUpgrading] = useState(false);
// 选中的方案类型 tab
const [activeType, setActiveType] = useState('monthly');
// 会员购买历史弹窗
const [historyModalVisible, setHistoryModalVisible] = useState(false);
// 获取方案列表
const fetchPlans = async () => {
setLoading(true);
try {
const res = await API.get('/api/user/membership/plans');
const { success, data } = res.data;
if (success) {
setMembershipEnabled(data.membership_enabled);
setPlans(data.plans || []);
setTitle(data.title || '会员订阅');
setDescription(data.description || '');
}
} catch (err) {
console.error('获取会员方案失败:', err);
} finally {
setLoading(false);
}
};
// 获取当前会员信息
const fetchMembershipInfo = async () => {
setInfoLoading(true);
try {
const res = await API.get('/api/user/membership/info');
const { success, data } = res.data;
if (success) {
setMembershipInfo(data);
}
} catch (err) {
console.error('获取会员信息失败:', err);
} finally {
setInfoLoading(false);
}
};
// 购买会员
const handlePurchase = async () => {
if (!selectedPlan) return;
setPurchasing(true);
try {
const res = await API.post('/api/user/membership/purchase', {
plan_id: selectedPlan.id,
payment_method: 'balance',
});
const { success, message } = res.data;
if (success) {
showSuccess(t('购买成功!'));
setPurchaseModalVisible(false);
setSelectedPlan(null);
fetchMembershipInfo();
// 刷新用户信息
try {
const userRes = await API.get('/api/user/self');
if (userRes.data.success) {
userDispatch({ type: 'login', payload: userRes.data.data });
}
} catch (e) {}
} else {
showError(message);
}
} catch (err) {
showError(t('购买失败'));
} finally {
setPurchasing(false);
}
};
// 检查是否为升级场景并获取差价
const checkUpgrade = async (plan) => {
if (!membershipInfo?.has_membership) return false;
if (plan.daily_quota <= membershipInfo.daily_quota) return false;
if (plan.plan_type !== membershipInfo.plan_type) return false; // 只能同类型内升级
setUpgradeLoading(true);
try {
const res = await API.get(
`/api/user/membership/upgrade/cost?plan_id=${plan.id}`,
);
const { success, data } = res.data;
if (success && data.can_upgrade) {
setUpgradeInfo(data);
return true;
}
} catch (err) {
console.error('查询升级信息失败:', err);
} finally {
setUpgradeLoading(false);
}
return false;
};
// 判断是否为当前正在使用的同款方案(匹配 tier + plan_type,可续费但不可升级)
const isCurrentPlanCheck = (plan) => {
return (
membershipInfo?.has_membership &&
membershipInfo?.daily_quota === plan.daily_quota &&
membershipInfo?.tier === plan.tier &&
membershipInfo?.plan_type === plan.plan_type
);
};
// 判断是否可以升级(同一时长类型内,更高档位)
const canUpgradeCheck = (plan) => {
return (
membershipInfo?.has_membership &&
plan.daily_quota > (membershipInfo?.daily_quota || 0) &&
plan.plan_type === membershipInfo?.plan_type
);
};
// 判断是否为降级(同一时长类型内,更低档位)
const isDowngradeCheck = (plan) => {
return (
membershipInfo?.has_membership &&
plan.plan_type === membershipInfo?.plan_type &&
plan.daily_quota < (membershipInfo?.daily_quota || 0)
);
};
// 判断该方案是否已有未来待生效的续费
const hasFutureForPlan = (plan) => {
return (
membershipInfo?.has_future_membership &&
membershipInfo?.future_plan_type === plan.plan_type &&
membershipInfo?.future_tier === plan.tier
);
};
// 点击方案卡片
const handlePlanClick = async (plan) => {
setSelectedPlan(plan);
// 判断是否为升级场景(同一时长类型内,且每日额度更高)
if (canUpgradeCheck(plan)) {
const isUpgrade = await checkUpgrade(plan);
if (isUpgrade) {
setUpgradeModalVisible(true);
return;
}
}
// 普通购买 / 续期(包括同款方案续费)
setPurchaseModalVisible(true);
};
// 执行升级
const handleUpgrade = async () => {
if (!selectedPlan) return;
setUpgrading(true);
try {
const res = await API.post('/api/user/membership/upgrade', {
plan_id: selectedPlan.id,
});
const { success, message } = res.data;
if (success) {
showSuccess(message || t('升级成功!'));
setUpgradeModalVisible(false);
setSelectedPlan(null);
setUpgradeInfo(null);
fetchMembershipInfo();
// 刷新用户信息
try {
const userRes = await API.get('/api/user/self');
if (userRes.data.success) {
userDispatch({ type: 'login', payload: userRes.data.data });
}
} catch (e) {}
} else {
showError(message);
}
} catch (err) {
showError(t('升级失败'));
} finally {
setUpgrading(false);
}
};
useEffect(() => {
fetchPlans();
fetchMembershipInfo();
}, []);
if (loading) {
return (
);
}
if (!membershipEnabled) {
return (
);
}
// 按类型分组方案
const plansByType = {};
plans.forEach((plan) => {
if (!plansByType[plan.plan_type]) {
plansByType[plan.plan_type] = [];
}
plansByType[plan.plan_type].push(plan);
});
const typeKeys = Object.keys(plansByType);
// 格式化日期
const formatDate = (timestamp) => {
return new Date(timestamp * 1000).toLocaleDateString(i18n.language);
};
// 原型展示固定的周卡/月卡/季卡三个时长,没有方案的时长显示“待补充”空态
const periodKeys = [
...Object.keys(planTypeConfig),
...typeKeys.filter((type) => !planTypeConfig[type]),
];
const currentPeriod = periodKeys.includes(activeType)
? activeType
: periodKeys[0];
const periodPlans = plansByType[currentPeriod] || [];
return (
{/* 当前会员状态 */}
{!infoLoading && membershipInfo?.has_membership && (
{t('当前会员')}
{membershipInfo.plan_name}
{' '}
{t('今日剩余额度')}
{renderQuota(membershipInfo.membership_quota)}
{t('每日额度')}
{renderQuota(membershipInfo.daily_quota)}
{membershipInfo.daily_quota > 0 && (
)}
{t('到期日')}: {formatDate(membershipInfo.end_date)}
{t('剩余 {{n}} 天', {
n: membershipInfo.remaining_days,
count: membershipInfo.remaining_days,
})}
{/* 已续费提示 */}
{membershipInfo.has_future_membership && (
)}
)}
{/* 方案时长切换 */}
({
value: type,
label: t(planTypeConfig[type]?.label || type),
}))}
/>
{t('选择适合你的会员')}
{description ||
t(
'会员额度每日重置,优先消耗;用完后切换账户余额,不自动续费。',
)}
{plans.length === 0 ? (
) : periodPlans.length === 0 ? (
{t('价格与权益待补充')}
) : (
{periodPlans.map((plan) => {
const isSelected = selectedPlan?.id === plan.id;
const isCurrentPlan = isCurrentPlanCheck(plan);
const canUpgrade = canUpgradeCheck(plan);
const isDowngrade = isDowngradeCheck(plan);
const hasFuture = hasFutureForPlan(plan);
// 按钮文案沿用原有续费/升级/到期生效判断
let btnText = t('立即订阅');
let subText = '';
if (isCurrentPlan) {
btnText = hasFuture ? t('再次续费') : t('续费');
} else if (canUpgrade) {
btnText = t('立即升级');
subText = t('立即生效,补差价');
} else if (isDowngrade) {
subText = t('到期后生效');
} else if (membershipInfo?.has_membership) {
subText = t('到期后生效');
}
return (
);
})}
)}
{/* 购买确认弹窗 */}
{selectedPlan && isCurrentPlanCheck(selectedPlan)
? t('确认续费会员')
: t('确认购买会员')}
}
visible={purchaseModalVisible}
onOk={handlePurchase}
onCancel={() => {
setPurchaseModalVisible(false);
setSelectedPlan(null);
}}
confirmLoading={purchasing}
okText={
selectedPlan && isCurrentPlanCheck(selectedPlan)
? t('确认续费')
: t('确认购买')
}
cancelText={t('取消')}
centered
maskClosable={false}
>
{selectedPlan && (
{selectedPlan.name}
{t('{{days}} 天', { days: selectedPlan.duration_days })}
{t('每日到账额度')}
{renderQuota(selectedPlan.daily_quota)}
{t('总计到账')}
{renderQuota(
selectedPlan.daily_quota * selectedPlan.duration_days,
)}
{t('支付方式')}
{t('账户余额抵扣')}
{t('需支付')}
¥{selectedPlan.price}
{/* 场景化提示 */}
{(() => {
if (!membershipInfo?.has_membership) {
// 新用户,无会员
return (
);
}
const isRenewal = isCurrentPlanCheck(selectedPlan);
const isDowngrade = isDowngradeCheck(selectedPlan);
return (
<>
{/* 续费同款方案 */}
{isRenewal && (
)}
{/* 购买不同类型的方案(非升级、非同款) */}
{!isRenewal && !isDowngrade && (
)}
{/* 降级方案提示 */}
{isDowngrade && (
)}
{/* 同类型升级提示(用户通过购买而非升级入口来的) */}
{!isRenewal &&
!isDowngrade &&
canUpgradeCheck(selectedPlan) && (
)}
{/* 已有未来待生效的续费 */}
{membershipInfo.has_future_membership && (
)}
>
);
})()}
)}
{/* 升级确认弹窗 */}
{t('确认升级会员')}
}
visible={upgradeModalVisible}
onOk={handleUpgrade}
onCancel={() => {
setUpgradeModalVisible(false);
setSelectedPlan(null);
setUpgradeInfo(null);
}}
confirmLoading={upgrading}
okText={t('确认升级')}
cancelText={t('取消')}
centered
maskClosable={false}
>
{selectedPlan && upgradeInfo && (
{/* 升级对比 */}
{t('当前方案')}
{upgradeInfo.current_plan}
{t('每日')} {renderQuota(upgradeInfo.current_daily)}
{t('升级')}
{t('升级方案')}
{upgradeInfo.new_plan}
{t('每日')} {renderQuota(upgradeInfo.new_daily)}
{/* 差价明细 */}
{t('剩余会员天数')}
{t('{{days}} 天', { days: upgradeInfo.remaining_days })}
{t('升级差价')}
¥{upgradeInfo.upgrade_cost}
{t('需补缴额度')}
{renderQuota(upgradeInfo.quota_needed)}
{t('支付方式')}
{t('账户余额抵扣')}
{t('需支付')}
¥{upgradeInfo.upgrade_cost}
)}
{upgradeLoading && (
)}
{/* 会员购买历史弹窗 */}
setHistoryModalVisible(false)}
t={t}
/>
);
};
export default MembershipPanel;