user.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { t } from "i18next";
  2. import { create } from "zustand";
  3. import { BusinessUserInfo, getBusinessUserInfo } from "@/api/login";
  4. import { IMSDK } from "@/layout/MainContentWrap";
  5. import router from "@/routes";
  6. import { feedbackToast } from "@/utils/common";
  7. import { clearIMProfile, getLocale, setLocale } from "@/utils/storage";
  8. import { useContactStore } from "./contact";
  9. import { useConversationStore } from "./conversation";
  10. import { AppConfig, AppSettings, IMConnectState, UserStore } from "./type";
  11. import { message } from "@/AntdGlobalComp";
  12. export const useUserStore = create<UserStore>()((set, get) => ({
  13. syncState: "success",
  14. progress: 0,
  15. reinstall: true,
  16. isLogining: false,
  17. connectState: "success",
  18. selfInfo: {} as BusinessUserInfo,
  19. appConfig: {} as AppConfig,
  20. appSettings: {
  21. locale: getLocale(),
  22. closeAction: "miniSize",
  23. },
  24. updateSyncState: (syncState: IMConnectState) => {
  25. set({ syncState });
  26. },
  27. updateProgressState: (progress: number) => {
  28. set({ progress });
  29. },
  30. updateReinstallState: (reinstall: boolean) => {
  31. set({ reinstall });
  32. },
  33. updateIsLogining: (isLogining: boolean) => {
  34. set({ isLogining });
  35. },
  36. updateConnectState: (connectState: IMConnectState) => {
  37. set({ connectState });
  38. },
  39. getSelfInfoByReq: () => {
  40. IMSDK.getSelfUserInfo()
  41. .then(({ data }) => {
  42. set(() => ({ selfInfo: data as unknown as BusinessUserInfo }));
  43. getBusinessUserInfo([data.userID]).then(({ data: { users } }) =>
  44. set((state) => ({ selfInfo: { ...state.selfInfo, ...users[0] } })),
  45. ).catch(error => {
  46. message.error(error.message);
  47. });
  48. })
  49. .catch((error) => {
  50. if(error.message){
  51. message.error(error.message);
  52. } else {
  53. feedbackToast({ msg: t("toast.getSelfInfoFailed") });
  54. }
  55. get().userLogout();
  56. });
  57. },
  58. updateSelfInfo: (info: Partial<BusinessUserInfo>) => {
  59. set((state) => ({ selfInfo: { ...state.selfInfo, ...info } }));
  60. },
  61. updateAppSettings: (settings: Partial<AppSettings>) => {
  62. if (settings.locale) {
  63. setLocale(settings.locale);
  64. }
  65. set((state) => ({ appSettings: { ...state.appSettings, ...settings } }));
  66. },
  67. userLogout: async (force = false) => {
  68. if (!force) await IMSDK.logout();
  69. clearIMProfile();
  70. set({ selfInfo: {} as BusinessUserInfo });
  71. useContactStore.getState().clearContactStore();
  72. useConversationStore.getState().clearConversationStore();
  73. window.electronAPI?.ipcInvoke("updateUnreadCount", 0);
  74. router.navigate("/login");
  75. },
  76. }));