import { getSubscription } from '@/services/user/portal';
import { useQuery } from '@tanstack/react-query';
import { Dialog, DialogContent, DialogTitle } from '@workspace/airo-ui/components/dialog';
import { Tabs, TabsList, TabsTrigger } from '@workspace/airo-ui/components/tabs';
import { unitConversion } from '@workspace/airo-ui/utils';
import { forwardRef, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { TabContent } from './TabContent';
import { ProcessedPlanData } from './types';
// 加载状态组件
const LoadingState = () => {
const t = useTranslations('components.offerDialog');
return (
);
};
// 错误状态组件
const ErrorState = ({ onRetry }: { onRetry: () => void }) => {
const t = useTranslations('components.offerDialog');
return (
{t('loadFailed')}
);
};
// 空状态组件
const EmptyState = ({ message }: { message: string }) => (
);
// 价格显示组件
const PriceDisplay = ({ plan }: { plan: ProcessedPlanData }) => {
const t = useTranslations('components.offerDialog');
return (
{plan.origin_price && (
${plan.origin_price}
)}
${plan.discount_price}
{t('perYear')}
{plan.origin_price && (
{t('yearlyDiscount')}
)}
);
};
import { useLoginDialog } from '@/app/auth/LoginDialogContext';
import { Display } from '@/components/display';
import Modal from '@/components/Modal';
import Purchase from '@/components/subscribe/purchase';
import useGlobalStore from '@/config/use-global';
import { queryUserSubscribe } from '@/services/user/user';
import { useTranslations } from 'next-intl';
// 星级评分组件
const StarRating = ({ rating, maxRating = 5 }: { rating: number; maxRating?: number }) => (
{Array.from({ length: Math.min(rating, maxRating) }, (_, i) => (
✭
))}
);
// 功能列表组件
const FeatureList = ({ plan }: { plan: ProcessedPlanData }) => {
const t = useTranslations('subscribe.detail');
const tOffer = useTranslations('components.offerDialog');
const features = [{ label: tOffer('availableNodes'), value: plan?.server_count }];
return (
);
};
// 套餐卡片组件
const PlanCard = forwardRef<
HTMLDivElement,
{
plan: ProcessedPlanData;
tabValue: string;
onSubscribe?: (plan: ProcessedPlanData) => void;
isFirstCard?: boolean;
}
>(({ plan, onSubscribe }, ref) => {
const { user } = useGlobalStore();
const { openLoginDialog } = useLoginDialog();
const t = useTranslations('components.offerDialog');
const ModalRef = useRef(null);
async function handleSubscribe() {
if (!user) {
// 强制登陆
openLoginDialog(false);
return;
}
// 有生效套餐进行弹窗提示
const { data } = await queryUserSubscribe();
if (data?.data?.list?.[0]?.status === 1) {
ModalRef.current.show();
return;
}
onSubscribe?.(plan);
}
return (
{/* 套餐名称 */}
{plan.name}
{/* 价格区域 */}
{/* 订阅按钮 */}
{/* 功能列表 */}
onSubscribe?.(plan)}
/>
);
});
PlanCard.displayName = 'PlanCard';
// 套餐列表组件
export const PlanList = ({
plans,
tabValue,
isLoading,
error,
onRetry,
emptyMessage,
onSubscribe,
}: {
plans: ProcessedPlanData[];
tabValue: string;
isLoading: boolean;
error: any;
onRetry: () => void;
emptyMessage: string;
onSubscribe?: (plan: ProcessedPlanData) => void;
}) => {
if (isLoading) return ;
if (error) return ;
if (plans.length === 0) return ;
return (
{plans.map((plan, index) => (
))}
);
};
export interface OfferDialogRef {
show: () => void;
hide: () => void;
}
const OfferDialog = forwardRef((props, ref) => {
const t = useTranslations('components.offerDialog');
const [open, setOpen] = useState(false);
const [tabValue, setTabValue] = useState('year');
const dialogRef = useRef(null);
// 使用 useQuery 来管理请求
const {
data = [],
isLoading,
error,
refetch,
} = useQuery({
queryKey: ['subscription'],
queryFn: async () => {
try {
const response = await getSubscription({ skipErrorHandler: true });
// 确保返回有效的数组,避免 undefined
const list = response.data?.data?.list || [];
return list.filter((v) => v.unit_time === 'Month') as API.Subscribe[];
} catch (err) {
// 自定义错误处理
console.error('获取订阅数据失败:', err);
// 返回空数组而不是抛出错误,避免 queryFn 返回 undefined
return [] as API.Subscribe[];
}
},
enabled: true, // 初始不执行,手动控制
retry: 1, // 失败时重试1次
});
useImperativeHandle(ref, () => ({
show: () => {
refetch();
setOpen(true);
},
hide: () => setOpen(false),
}));
const PurchaseRef = useRef<{ show: (subscribe: API.Subscribe) => void; hide: () => void }>(null);
// 处理订阅点击
const handleSubscribe = (plan: ProcessedPlanData) => {
// 这里可以添加订阅逻辑,比如跳转到支付页面或显示确认对话框
PurchaseRef.current.show(plan, tabValue);
};
// 处理套餐数据的工具函数
const processPlanData = (item: API.Subscribe, isYearly: boolean): ProcessedPlanData => {
if (isYearly) {
const discountItem = item.discount?.find((v) => v.quantity === 12);
return {
...item,
origin_price: unitConversion('centsToDollars', item.unit_price * 12).toString(), // 原价
discount_price: unitConversion(
'centsToDollars',
item.unit_price * ((discountItem?.discount || 100) / 100) * 12,
).toString(), // 优惠价格
};
} else {
return {
...item,
origin_price: '', // 月付没有原价
discount_price: unitConversion('centsToDollars', item.unit_price).toString(), // 月付价格
};
}
};
// 使用 useMemo 优化数据处理性能
const yearlyPlans: ProcessedPlanData[] = useMemo(
() => (data || []).map((item) => processPlanData(item, true)),
[data],
);
const monthlyPlans: ProcessedPlanData[] = useMemo(
() => (data || []).map((item) => processPlanData(item, false)),
[data],
);
return (
);
});
export default OfferDialog;