WXL
3 天以前 2cc85c64f1c64a2dbaeae276a3e2ca8420de76b7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { defineStore } from "pinia";
import { ref, computed } from "vue";
 
export const useUserStore = defineStore("user", () => {
  // 状态
  const token = ref(null);
  const userInfo = ref(null);
  const roleKeyInfo = ref(null);
  // const baseUrlHt =  ref(window.location.origin+'/api');
  const baseUrlHt =  ref('http://localhost:8080');
 
  // getters
  const isLoggedIn = computed(() => !!token.value);
  const userName = computed(() => userInfo.value?.name || "");
 
  // 配置项
  const ADMIN_ROLES = ["admin", "medical_admin"];
  const USER_ROLES = ["user", "patient"];
  const DOCTOR_ROLES = ["doctor", "specialist"];
 
  // actions
  function setToken(newToken) {
    token.value = newToken;
    uni.setStorageSync("token", newToken);
  }
  function setUserInfo(info) {
    userInfo.value = info;
    uni.setStorageSync("userInfo", info);
  }
  function setroleKey(roleKey) {    
    // 更灵活的角色权限映射
    if (ADMIN_ROLES.includes(roleKey)) {
      roleKeyInfo.value = 1; // 管理员权限
    } else if (DOCTOR_ROLES.includes(roleKey)) {
      roleKeyInfo.value = 2; // 医生权限
    } else if (USER_ROLES.includes(roleKey)) {
      roleKeyInfo.value = 0; // 普通用户权限
    } else {
      roleKeyInfo.value = 0; // 默认权限
    }
    uni.setStorageSync("roleKeyInfo", roleKeyInfo.value); 
  }
  function clearUser() {
    token.value = null;
    userInfo.value = null;
    roleKeyInfo.value = null;
    uni.removeStorageSync("token");
    uni.removeStorageSync("roleKeyInfo");
    uni.removeStorageSync("userInfo");
  }
 
  // 初始化时从本地存储恢复
  function initFromStorage() {
    const localToken = uni.getStorageSync("token");
    const localUser = uni.getStorageSync("userInfo");
    const localroleKey = uni.getStorageSync("roleKeyInfo");
    if (localToken) token.value = localToken;
    if (localUser) userInfo.value = localUser;
    if (localroleKey) roleKeyInfo.value = localroleKey;
  }
 
  return {
    token,
    userInfo,
    roleKeyInfo,
    isLoggedIn,
    userName,
    baseUrlHt,
    setToken,
    setUserInfo,
    clearUser,
    initFromStorage,
    setroleKey,
  };
});