| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import { useEffect, useState } from 'react';
- import { PlanTagType } from '@/defines';
- import { userConfigModel } from '@/models/userConfigModel';
- import { fetchGetUserConfig, fetchPlanList, fetchPayTypeList } from '@/services/config';
- import { setToken, userKey } from '@/utils/authUtils';
- import { secureLocalStorage as ls } from '@/utils/localUtils';
- import { getUniqueSign } from '@/utils/stringUtils';
- import { currentUnixTimestamp } from '@/utils/timeUtils';
- export interface Plan {
- id: string;
- title: string;
- subTitle: string;
- introduce: string;
- tag?: string;
- tagType?: PlanTagType;
- price: number;
- }
- export interface UseServiceReturn {
- plans: Plan[];
- payMethods: API.PayTypeItem[];
- }
- export function useService(): UseServiceReturn {
- const { setUserConfig } = userConfigModel.useModel();
- const [plans, setPlans] = useState<Plan[]>([]);
- const [payMethods, setPayMethods] = useState<API.PayTypeItem[]>([]);
- useEffect(() => {
- const userinfo = ls.getLocal<API.UserInfo>(userKey);
- const expired = (userinfo?.accessExpires ?? 0) - currentUnixTimestamp() <= 0;
- if (expired) return; // 如果 accessToken 过期,什么都不做
- 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) => ({
- id: item.channelItemId ?? getUniqueSign(),
- title: item.title ?? '',
- subTitle: item.subTitle ?? '',
- introduce: item.introduce ?? '',
- tag: item.tag,
- tagType: item.tagType ?? PlanTagType.NONE,
- price: item.price ?? 0,
- }));
- setPlans(mapped);
- })
- .catch(() => {});
- }, []);
- useEffect(() => {
- fetchPayTypeList({})
- .then((res) => {
- const list = res?.data?.payTypeList ?? [];
- setPayMethods(list);
- })
- .catch(() => {});
- }, []);
- return {
- plans,
- payMethods,
- };
- }
|