Page({ data: { userInfo: { name: '', // 用户名 }, oldPassword: '', // 输入的旧密码 newPassword: '', // 输入的新密码 errorMessage: '', // 错误提示信息 isSaveDisabled: true, // 控制保存按钮是否禁用 }, // 页面加载时从缓存获取用户信息 onLoad() { this.loadUserInfo(); // 加载缓存中的用户信息 }, // 页面显示时确保更新按钮状态 onShow() { this.updateSaveButtonState(); // 更新保存按钮的状态 }, // 加载缓存的用户信息 loadUserInfo() { // 从缓存中获取 currentUser(用户名)和 userId(用户ID) const currentUser = wx.getStorageSync('currentUser') || ''; // 获取缓存的用户名,若无则为空 const userId = wx.getStorageSync('userId') || ''; // 获取缓存的用户ID,若无则为空 // 设置用户名和用户ID this.setData({ userInfo: { name: currentUser, // 设置用户名 } }); this.updateSaveButtonState(); // 更新保存按钮状态 }, // 获取用户名输入 inputName(e) { this.setData({ 'userInfo.name': e.detail.value, // 更新用户名 }); this.updateSaveButtonState(); // 更新保存按钮状态 }, // 获取旧密码输入 inputOldPassword(e) { this.setData({ oldPassword: e.detail.value, // 更新旧密码 }); this.updateSaveButtonState(); // 更新保存按钮状态 }, // 获取新密码输入 inputNewPassword(e) { this.setData({ newPassword: e.detail.value, // 更新新密码 }); this.updateSaveButtonState(); // 更新保存按钮状态 }, // 更新保存按钮的状态 updateSaveButtonState() { const { oldPassword, newPassword } = this.data; // 判断如果旧密码和新密码都有值,则启用保存按钮,否则禁用 if (oldPassword.trim() && newPassword.trim()) { this.setData({ isSaveDisabled: false, // 启用保存按钮 }); } else { this.setData({ isSaveDisabled: true, // 禁用保存按钮 }); } }, // 保存修改后的用户名和密码 saveChanges() { const { userInfo, oldPassword, newPassword } = this.data; // 校验用户名 if (!userInfo.name.trim()) { this.setData({ errorMessage: '用户名不能为空' }); return; } // 校验新密码是否为空 if (newPassword && !newPassword.trim()) { this.setData({ errorMessage: '新密码不能为空' }); return; } // 从缓存中获取 userId const userId = wx.getStorageSync('userId'); if (!userId) { this.setData({ errorMessage: '用户ID不可用' }); return; } // 调用后端API来保存用户名和密码 this.updateUserInfo(userId, userInfo.name, oldPassword, newPassword); }, // 调用后端API更新用户信息 updateUserInfo(userId, name, oldPassword, newPassword) { wx.request({ url: 'https://soilgd.com:5000/update_user', // 替换为实际的API地址 method: 'POST', data: { userId: userId, // 传递 userId name: name, oldPassword: oldPassword, newPassword: newPassword, }, header: { 'Content-Type': 'application/json' // 确保 Content-Type 设置为 application/json }, success: (res) => { if (res.data.success) { wx.setStorageSync('currentUser', name); // 更新缓存中的用户名 this.setData({ errorMessage: '' }); // 显示成功提示 wx.showToast({ title: '保存成功', icon: 'success', }); // 修改成功后跳转到 Staff 页面 wx.switchTab({ url: '/pages/Staff/Staff', // 跳转到 Staff 页面 }); } else { this.setData({ errorMessage: res.data.message || '保存失败' }); } }, fail: (err) => { console.error('数据库更新失败', err); this.setData({ errorMessage: '更新失败,请稍后重试' }); } }); } });