import { useEffect, useMemo, useState } from 'react'; import { PlanTagType, PayMethodType } from '@/defines'; import { userConfigModel } from '@/models/userConfigModel'; import { fetchGetUserConfig, fetchPlanList } from '@/services/config'; import { getToken, setToken } from '@/utils/authUtils'; import { currentUnixTimestamp } from '@/utils/timeUtils'; export interface Plan { id: number; title: string; subTitle: string; introduce: string; tag?: string; tagType?: PlanTagType; price: number; } export interface UseServiceReturn { plans: Plan[]; payMethods: PayMethodType[]; } export function useService(): UseServiceReturn { const { setUserConfig } = userConfigModel.useModel(); const [plans, setPlans] = useState([]); useEffect(() => { const userinfo = getToken(); const expired = (userinfo?.accessExpires ?? 0) - currentUnixTimestamp() <= 0; if (expired) return; if (userinfo?.account?.username) return; fetchGetUserConfig({}) .then((res) => { const data = res?.data; if (!data) return; setToken(data); setUserConfig(data); }) .catch(() => {}); }, [setUserConfig]); useEffect(() => { fetchPlanList({}) .then((res) => { const list = res?.data?.list ?? []; const mapped: Plan[] = list.map((item, index) => ({ id: item.ServiceChannelPlanId ?? index, title: item.title ?? '', subTitle: item.subTitle ?? '', introduce: item.introduce ?? '', tag: item.tag, tagType: item.tagType ?? PlanTagType.NONE, price: item.price ?? 0, })); setPlans(mapped); }) .catch(() => {}); }, []); const payMethods = useMemo( () => [ PayMethodType.APPLE_PAY, PayMethodType.GOOGLE_PAY, // PayMethodType.PAYPAL, // PayMethodType.WECHAT, // PayMethodType.ALIPAY, ], [] ); return { plans, payMethods, }; }