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, }; });