import { defineStore } from 'pinia'; import api from '@/common/api/index.js' export const useUserStore = defineStore('user', { state: () => ({ isRegister: true, // 是否注册成功 isLogin: false, // 用户是否已登录 showLoginModal: false, // 是否显示登录弹框 registerStep: 0, // 注册步骤:0=未注册,1=填写用户信息,2=添加孩子 token:'', userInfo: null, // 用户信息 inpage:false, //是否当前页面 }), getters: { // 方便在模板中直接使用 isLoggedIn: (state) => state.isLogin, }, actions: { // 打开登录弹框 openLoginModal() { this.showLoginModal = true; }, // 关闭登录弹框 closeLoginModal() { this.showLoginModal = false; this.registerStep = 0; }, async register(userFrom) { return new Promise(resolve => { api.post('/wx/register',userFrom).then(({data:res})=>{ if(res.code !== 0){ uni.showToast({ title: res.msg }) resolve(false) return } // 注册成功,进入第二步添加孩子 this.registerStep = 2; resolve(true) }) }); }, // 添加孩子完成后调用,完成整个注册流程 completeRegister() { this.showLoginModal = false; this.isRegister = true; this.isLogin = true; this.registerStep = 0; uni.showToast({ title: '注册成功', icon: 'success' }); }, async login(loginDto) { await new Promise(resolve => { api.get('/wx/login',loginDto).then(({data:res})=>{ if(res.code !== 0){ uni.showModal({ title:'温馨提示', content:res.msg, showCancel:false }) return } this.token = res.data?.token; this.userInfo = res.data; uni.setStorageSync('token',this.userInfo?.token) const currentDate = new Date(); const futureDate = new Date(currentDate); futureDate.setDate(currentDate.getDate() + 7); uni.setStorageSync('expaireTime',Date.parse(futureDate)) uni.setStorageSync('userInfo',JSON.stringify(this.userInfo)) // 新用户(userLevel=0)需要注册流程 if(res.data?.userLevel === 0) { this.isRegister = false; this.registerStep = 1; } else { this.showLoginModal = false; this.isLogin = true; uni.showToast({ title: '登录成功', icon: 'success' }); } }) }); }, // 登出操作 logout() { this.isRegister = false; this.isLogin = false; this.userInfo = null; uni.showToast({ title: '已退出登录', icon: 'none' }); }, }, });