user.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. // src/store/user.ts
  2. import { defineStore } from 'pinia'
  3. import { ref, computed} from 'vue'
  4. import { generateDefaultAvatar } from '@/utils/defaultUtils'
  5. import { getUserProfileApi, updateUserProfileApi } from '@/api/user' // 【新增】导入API
  6. // 定义 user info 的接口,以便后续的修改
  7. interface IUserInfo {
  8. id: string | number;
  9. name: string;
  10. officialEmail: string | null;
  11. officialNumber: string | null;
  12. role: 'STUDENT' | 'TEACHER' | 'ADMIN' | null;
  13. userAvatar: string | null;
  14. createTime: string | null;
  15. englishName: string | null;
  16. gender: 'MAN' | 'WOMAN' | null;
  17. birthday: string | null;
  18. phone: string | null;
  19. contentEmail: string | null;
  20. pid: string | number;
  21. openid: string | null;
  22. unionid: string | null;
  23. isWechatBound: boolean;
  24. }
  25. const defaultUserInfo: IUserInfo = {
  26. id: '',
  27. name: '',
  28. officialEmail: null,
  29. officialNumber: null,
  30. role: 'STUDENT',
  31. userAvatar: null,
  32. createTime: null,
  33. englishName: null,
  34. gender: null,
  35. birthday: null,
  36. phone: null,
  37. contentEmail: null,
  38. pid: 0,
  39. openid: null,
  40. unionid: null,
  41. isWechatBound: false
  42. }
  43. export const useUserStore = defineStore('user', () => {
  44. const userInfo = ref<IUserInfo>({ ...defaultUserInfo })
  45. const isLoggedIn = ref<boolean>(false)
  46. const token = ref<string | null>(null);
  47. const displayAvatar = computed(() => {
  48. // return userInfo.value.userAvatar || generateDefaultAvatar(userInfo.value)
  49. return generateDefaultAvatar(userInfo.value);
  50. })
  51. const isUsingDefaultAvatar = computed(() => {
  52. return !userInfo.value.userAvatar
  53. })
  54. const setUserInfo = (info: Partial<any>, userToken?: string) => { // 将info的类型改为any,以便兼容后端返回的number
  55. // 将后端返回的数字角色和性别转换为字符串
  56. const roleMap = { 0: 'ADMIN', 1: 'STUDENT', 2: 'TEACHER' };
  57. const genderMap = { 0: 'MAN', 1: 'WOMAN' };
  58. if (typeof info.role === 'number') {
  59. info.role = roleMap[info.role];
  60. }
  61. if (typeof info.gender === 'number') {
  62. info.gender = genderMap[info.gender];
  63. }
  64. userInfo.value = { ...userInfo.value, ...info as Partial<IUserInfo> }
  65. isLoggedIn.value = true
  66. if (userToken) {
  67. token.value = userToken;
  68. }
  69. }
  70. // 用于更新用户信息的方法
  71. const updateUserProfile = async (updates: Partial<IUserInfo>) => {
  72. try {
  73. // 确保只发送有更新的字段
  74. const payload: any = {};
  75. Object.keys(updates).forEach(key => {
  76. payload[key] = updates[key];
  77. });
  78. if (Object.keys(payload).length > 0) {
  79. await updateUserProfileApi(payload);
  80. // API调用成功后,才更新本地状态
  81. setUserInfo(updates);
  82. uni.showToast({ title: '修改成功', icon: 'success', duration: 1500 });
  83. }
  84. } catch (error) {
  85. console.error("更新用户信息失败:", error);
  86. uni.showToast({ title: '修改失败,请稍后重试', icon: 'none' });
  87. throw error; // 向上抛出错误,让调用方知道失败了
  88. }
  89. };
  90. // 获取用户信息的 action
  91. const fetchUserProfile = async () => {
  92. const officialNumber = userInfo.value.officialNumber;
  93. if (!officialNumber) {
  94. console.error("未获取到学号,无法查询个人信息");
  95. uni.showToast({title: '获取个人信息失败', icon: 'none'});
  96. return;
  97. }
  98. try {
  99. const res = await getUserProfileApi(officialNumber);
  100. setUserInfo(res);
  101. } catch (error) {
  102. console.error("获取个人信息失败:", error);
  103. uni.showToast({title: '获取个人信息失败', icon: 'none'});
  104. }
  105. };
  106. // 更新用户信息
  107. const updateUserInfo = (info: Partial<IUserInfo>) => {
  108. userInfo.value = { ...userInfo.value, ...info }
  109. }
  110. const setCustomAvatar = (avatarUrl: string) => {
  111. userInfo.value.userAvatar = avatarUrl
  112. }
  113. const resetToDefaultAvatar = () => {
  114. userInfo.value.userAvatar = null;
  115. }
  116. const clearUserInfo = () => {
  117. console.log('【登出】执行 clearUserInfo...');
  118. userInfo.value = { ...defaultUserInfo };
  119. isLoggedIn.value = false;
  120. token.value = null;
  121. uni.removeStorageSync('user-store');
  122. uni.reLaunch({
  123. url: '/pages/login/index'
  124. });
  125. }
  126. const resetUserInfo = () => {
  127. userInfo.value = { ...defaultUserInfo }
  128. }
  129. const checkLoginStatus = () => {
  130. return !!token.value && isLoggedIn.value
  131. }
  132. const loadUserFromStorage = () => {
  133. try {
  134. const persistedState = uni.getStorageSync('user-store');
  135. if (persistedState) {
  136. const parsedState = JSON.parse(persistedState);
  137. if (parsedState.token && parsedState.isLoggedIn) {
  138. userInfo.value = parsedState.userInfo;
  139. isLoggedIn.value = parsedState.isLoggedIn;
  140. token.value = parsedState.token;
  141. console.log('【UserStore】状态从本地存储恢复成功。');
  142. } else {
  143. uni.removeStorageSync('user-store');
  144. }
  145. }
  146. } catch (e) {
  147. console.error('【UserStore】加载本地存储失败:', e);
  148. uni.removeStorageSync('user-store');
  149. }
  150. };
  151. return {
  152. userInfo,
  153. isLoggedIn,
  154. token,
  155. displayAvatar,
  156. isUsingDefaultAvatar,
  157. setUserInfo,
  158. fetchUserProfile,
  159. updateUserInfo, // 这个方法在profile页面中不再被直接使用,但保留
  160. updateUserProfile,
  161. setCustomAvatar,
  162. resetToDefaultAvatar,
  163. clearUserInfo,
  164. resetUserInfo,
  165. checkLoginStatus,
  166. loadUserFromStorage,
  167. }
  168. }, {
  169. persist: {
  170. key: 'user-store',
  171. storage: {
  172. getItem(key: string) { return uni.getStorageSync(key) },
  173. setItem(key: string, value: string) { uni.setStorageSync(key, value) }
  174. },
  175. paths: ['userInfo', 'isLoggedIn', 'token'],
  176. }
  177. })