useService.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { useEffect, useState } from 'react';
  2. import { PlanTagType } from '@/defines';
  3. import { userConfigModel } from '@/models/userConfigModel';
  4. import { fetchGetUserConfig, fetchPlanList, fetchPayTypeList } from '@/services/config';
  5. import { setToken, userKey } from '@/utils/authUtils';
  6. import { secureLocalStorage as ls } from '@/utils/localUtils';
  7. import { getUniqueSign } from '@/utils/stringUtils';
  8. import { currentUnixTimestamp } from '@/utils/timeUtils';
  9. export interface Plan {
  10. id: string;
  11. title: string;
  12. subTitle: string;
  13. introduce: string;
  14. tag?: string;
  15. tagType?: PlanTagType;
  16. price: number;
  17. }
  18. export interface UseServiceReturn {
  19. plans: Plan[];
  20. payMethods: API.PayTypeItem[];
  21. }
  22. export function useService(): UseServiceReturn {
  23. const { setUserConfig } = userConfigModel.useModel();
  24. const [plans, setPlans] = useState<Plan[]>([]);
  25. const [payMethods, setPayMethods] = useState<API.PayTypeItem[]>([]);
  26. useEffect(() => {
  27. const userinfo = ls.getLocal<API.UserInfo>(userKey);
  28. const expired = (userinfo?.accessExpires ?? 0) - currentUnixTimestamp() <= 0;
  29. if (expired) return; // 如果 accessToken 过期,什么都不做
  30. if (userinfo?.account?.username) return; // 否则,如果用户信息存在,也什么都不做
  31. // 请求用户信息
  32. fetchGetUserConfig({})
  33. .then((res) => {
  34. const data = res?.data;
  35. if (!data) return;
  36. setToken(data);
  37. setUserConfig(data);
  38. })
  39. .catch(() => {});
  40. }, [setUserConfig]);
  41. useEffect(() => {
  42. fetchPlanList({})
  43. .then((res) => {
  44. const list = res?.data?.list ?? [];
  45. const mapped: Plan[] = list.map((item) => ({
  46. id: item.channelItemId ?? getUniqueSign(),
  47. title: item.title ?? '',
  48. subTitle: item.subTitle ?? '',
  49. introduce: item.introduce ?? '',
  50. tag: item.tag,
  51. tagType: item.tagType ?? PlanTagType.NONE,
  52. price: item.price ?? 0,
  53. }));
  54. setPlans(mapped);
  55. })
  56. .catch(() => {});
  57. }, []);
  58. useEffect(() => {
  59. fetchPayTypeList({})
  60. .then((res) => {
  61. const list = res?.data?.payTypeList ?? [];
  62. setPayMethods(list);
  63. })
  64. .catch(() => {});
  65. }, []);
  66. return {
  67. plans,
  68. payMethods,
  69. };
  70. }