const api = require('../../utils/api') const media = require('../../utils/media') const activityUtil = require('../../utils/activity') const FIELDS = ['nickName', 'name', 'phone', 'company', 'position'] Page({ data: { avatarUrl: '', avatarPreview: '', nickName: '', name: '', phone: '', company: '', position: '', letter: '微', uploading: false, saving: false }, onLoad() { api .profile() .then((profile) => { const next = { avatarUrl: profile.avatarUrl || '', avatarPreview: media.absUrl(profile.avatarUrl), letter: (profile.nickName || profile.name || '微').slice(0, 1) } FIELDS.forEach((key) => { next[key] = profile[key] || '' }) this.setData(next) }) .catch(activityUtil.toast) }, pickAvatar() { if (this.data.uploading) return wx.chooseMedia({ count: 1, mediaType: ['image'], sourceType: ['album', 'camera'], sizeType: ['compressed'], success: (res) => { const file = res.tempFiles && res.tempFiles[0] if (!file || !file.tempFilePath) return this.setData({ uploading: true, avatarPreview: file.tempFilePath }) api .uploadAvatar(file.tempFilePath) .then((data) => this.setData({ avatarUrl: data.url, uploading: false })) .catch((error) => { this.setData({ uploading: false, avatarPreview: media.absUrl(this.data.avatarUrl) }) activityUtil.toast(error) }) } }) }, onInput(event) { const next = {} next[event.currentTarget.dataset.field] = event.detail.value this.setData(next) }, save() { if (this.data.saving) return if (this.data.uploading) { wx.showToast({ title: '头像上传中,请稍候', icon: 'none' }) return } const payload = { avatarUrl: this.data.avatarUrl } FIELDS.forEach((key) => { payload[key] = (this.data[key] || '').trim() }) if (!payload.name && !payload.nickName) { wx.showToast({ title: '请至少填写昵称或姓名', icon: 'none' }) return } if (payload.phone && !/^1\d{10}$/.test(payload.phone)) { wx.showToast({ title: '请填写正确的手机号', icon: 'none' }) return } this.setData({ saving: true }) api .saveProfile(payload) .then(() => { wx.showToast({ title: '已保存', icon: 'success' }) setTimeout(() => wx.navigateBack(), 500) }) .catch((error) => { this.setData({ saving: false }) activityUtil.toast(error) }) } })