2025-12-16 19:27:20 +08:00
|
|
|
|
import { defineStore } from "pinia";
|
2025-11-27 13:19:45 +08:00
|
|
|
|
|
2025-12-16 19:27:20 +08:00
|
|
|
|
export const useUserStore = defineStore("user", {
|
|
|
|
|
|
state: () => ({
|
|
|
|
|
|
userName: "",
|
|
|
|
|
|
mobile: "",
|
|
|
|
|
|
userAvatar: "",
|
|
|
|
|
|
isLoggedIn: false,
|
|
|
|
|
|
}),
|
|
|
|
|
|
actions: {
|
|
|
|
|
|
async fetchUserInfo() {
|
|
|
|
|
|
const { data, error } = await useApiFetch("/user/detail")
|
|
|
|
|
|
.get()
|
|
|
|
|
|
.json();
|
|
|
|
|
|
if (data.value && !error.value) {
|
|
|
|
|
|
if (data.value.code === 200) {
|
|
|
|
|
|
const userinfo = data.value.data.userInfo;
|
|
|
|
|
|
this.userName = userinfo.mobile || "";
|
|
|
|
|
|
this.mobile = userinfo.mobile || "";
|
|
|
|
|
|
this.userAvatar = userinfo.userAvatar;
|
|
|
|
|
|
this.isLoggedIn = true;
|
2025-11-27 13:19:45 +08:00
|
|
|
|
|
2025-12-16 19:27:20 +08:00
|
|
|
|
// 保存到localStorage
|
|
|
|
|
|
localStorage.setItem(
|
|
|
|
|
|
"userInfo",
|
|
|
|
|
|
JSON.stringify({
|
|
|
|
|
|
nickName: this.userName,
|
|
|
|
|
|
avatar: this.userAvatar,
|
|
|
|
|
|
})
|
|
|
|
|
|
);
|
|
|
|
|
|
} else if (data.value.code === 100009) {
|
|
|
|
|
|
// Token 无效或用户不存在,清除数据但不 reload
|
|
|
|
|
|
// reload 会导致无限循环
|
|
|
|
|
|
console.warn(
|
|
|
|
|
|
"User not found or token invalid (100009), clearing auth data"
|
|
|
|
|
|
);
|
|
|
|
|
|
localStorage.removeItem("token");
|
|
|
|
|
|
localStorage.removeItem("refreshAfter");
|
|
|
|
|
|
localStorage.removeItem("accessExpire");
|
|
|
|
|
|
localStorage.removeItem("userInfo");
|
|
|
|
|
|
localStorage.removeItem("agentInfo");
|
2025-11-27 13:19:45 +08:00
|
|
|
|
|
2025-12-16 19:27:20 +08:00
|
|
|
|
this.resetUser();
|
2025-11-27 13:19:45 +08:00
|
|
|
|
|
2025-12-16 19:27:20 +08:00
|
|
|
|
// 不要 reload,让调用者处理错误
|
|
|
|
|
|
throw new Error("User not found or token invalid");
|
|
|
|
|
|
} else {
|
|
|
|
|
|
// 其他错误
|
|
|
|
|
|
console.error("Unexpected response code:", data.value.code);
|
|
|
|
|
|
throw new Error(
|
|
|
|
|
|
`Unexpected response code: ${data.value.code}`
|
|
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
} else {
|
|
|
|
|
|
console.error("API error:", error.value);
|
|
|
|
|
|
throw error.value || new Error("Unknown error");
|
|
|
|
|
|
}
|
|
|
|
|
|
},
|
|
|
|
|
|
|
|
|
|
|
|
// 更新用户信息
|
|
|
|
|
|
updateUserInfo(userInfo) {
|
|
|
|
|
|
if (userInfo) {
|
|
|
|
|
|
this.userName = userInfo.mobile || userInfo.nickName || "";
|
|
|
|
|
|
this.userAvatar = userInfo.avatar || "";
|
|
|
|
|
|
this.isLoggedIn = true;
|
|
|
|
|
|
}
|
|
|
|
|
|
},
|
2025-11-27 13:19:45 +08:00
|
|
|
|
|
2025-12-16 19:27:20 +08:00
|
|
|
|
// 重置用户信息
|
|
|
|
|
|
resetUser() {
|
|
|
|
|
|
this.userName = "";
|
|
|
|
|
|
this.userAvatar = "";
|
|
|
|
|
|
this.isLoggedIn = false;
|
|
|
|
|
|
},
|
2025-11-27 13:19:45 +08:00
|
|
|
|
},
|
2025-12-16 19:27:20 +08:00
|
|
|
|
});
|