useService.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { useEffect, useMemo, useState } from 'react';
  2. import { PlanTagType, PayMethodType } from '@/defines';
  3. import { userConfigModel } from '@/models/userConfigModel';
  4. import { fetchGetUserConfig, fetchPlanList } from '@/services/config';
  5. import { getToken, setToken } from '@/utils/authUtils';
  6. import { currentUnixTimestamp } from '@/utils/timeUtils';
  7. export interface Plan {
  8. id: number;
  9. title: string;
  10. subTitle: string;
  11. introduce: string;
  12. tag?: string;
  13. tagType?: PlanTagType;
  14. price: number;
  15. }
  16. export interface UseServiceReturn {
  17. plans: Plan[];
  18. payMethods: PayMethodType[];
  19. }
  20. export function useService(): UseServiceReturn {
  21. const { setUserConfig } = userConfigModel.useModel();
  22. const [plans, setPlans] = useState<Plan[]>([]);
  23. useEffect(() => {
  24. const userinfo = getToken();
  25. const expired = (userinfo?.accessExpires ?? 0) - currentUnixTimestamp() <= 0;
  26. if (expired) return;
  27. if (userinfo?.account?.username) return;
  28. fetchGetUserConfig({})
  29. .then((res) => {
  30. const data = res?.data;
  31. if (!data) return;
  32. setToken(data);
  33. setUserConfig(data);
  34. })
  35. .catch(() => {});
  36. }, [setUserConfig]);
  37. useEffect(() => {
  38. fetchPlanList({})
  39. .then((res) => {
  40. const list = res?.data?.list ?? [];
  41. const mapped: Plan[] = list.map((item, index) => ({
  42. id: item.ServiceChannelPlanId ?? index,
  43. title: item.title ?? '',
  44. subTitle: item.subTitle ?? '',
  45. introduce: item.introduce ?? '',
  46. tag: item.tag,
  47. tagType: item.tagType ?? PlanTagType.NONE,
  48. price: item.price ?? 0,
  49. }));
  50. setPlans(mapped);
  51. })
  52. .catch(() => {});
  53. }, []);
  54. const payMethods = useMemo<PayMethodType[]>(
  55. () => [
  56. PayMethodType.APPLE_PAY,
  57. PayMethodType.GOOGLE_PAY,
  58. // PayMethodType.PAYPAL,
  59. // PayMethodType.WECHAT,
  60. // PayMethodType.ALIPAY,
  61. ],
  62. []
  63. );
  64. return {
  65. plans,
  66. payMethods,
  67. };
  68. }