const store = require('../../utils/store.js'); const api = require('../../utils/api.js'); const { toastErr } = require('../../utils/ui.js'); // key 要和后端 service.UserThemes 一致,色值只在 profile-head 的 wxss 里 const THEMES = [ { key: 'warm', label: '暖橙' }, { key: 'mint', label: '薄荷' }, { key: 'sky', label: '天青' }, { key: 'violet', label: '藕紫' }, { key: 'ink', label: '墨灰' }, ]; Page({ data: { themes: THEMES, form: { bio: '', bg_url: '', bg_file_id: '', theme: 'warm', show_pets: true }, bioLen: 0, preview: null, saving: false, }, onLoad() { store .ready() .then(() => this.loadCard()) .catch((e) => toastErr(e)); }, loadCard() { const uid = (store.getUser() || {}).id; if (!uid) return; api .userCard(uid) .then((card) => { this.setData({ form: { bio: card.bio || '', bg_url: card.bg_url || '', bg_file_id: '', // 没重新上传就不带这个字段,避免把已有头图覆盖成空 theme: card.theme || 'warm', show_pets: card.show_pets !== false, }, bioLen: (card.bio || '').length, }); this._card = card; this.syncPreview(); }) .catch((e) => toastErr(e)); }, // 预览喂给 profile-head 的就是一份改过的 card,组件那边不用知道自己在被预览 syncPreview() { const f = this.data.form; this.setData({ preview: Object.assign({}, this._card || {}, { bio: f.bio, bg_url: f.bg_url, theme: f.theme, show_pets: f.show_pets, }), }); }, pickBg() { wx.chooseMedia({ count: 1, mediaType: ['image'], sizeType: ['compressed'], success: (res) => { const path = res.tempFiles[0].tempFilePath; // 先用本地路径顶上,别让用户对着转圈等上传 this.setData({ 'form.bg_url': path }); this.syncPreview(); wx.showLoading({ title: '上传中…' }); api .uploadFile(path) .then((file) => { wx.hideLoading(); this.setData({ 'form.bg_file_id': file.id, 'form.bg_url': file.url }); this.syncPreview(); }) .catch((e) => { wx.hideLoading(); this.setData({ 'form.bg_url': (this._card && this._card.bg_url) || '' }); this.syncPreview(); toastErr(e, '上传失败'); }); }, }); }, clearBg() { // 空字符串是「清掉头图」的显式信号,和「没传」不是一回事 this.setData({ 'form.bg_url': '', 'form.bg_file_id': '' }); this.syncPreview(); }, pickTheme(e) { this.setData({ 'form.theme': e.currentTarget.dataset.key }); this.syncPreview(); }, onBio(e) { this.setData({ 'form.bio': e.detail.value, bioLen: e.detail.value.length }); this.syncPreview(); }, onShowPets(e) { this.setData({ 'form.show_pets': e.detail.value }); this.syncPreview(); }, save() { if (this.data.saving) return; const f = this.data.form; const body = { bio: f.bio, theme: f.theme, show_pets: f.show_pets }; // 只有真的动过头图才带 bg_file_id:新上传带新 id,点了「恢复默认渐变」带空串, // 两者都没有就不传,让后端保持原样 const had = (this._card && this._card.bg_url) || ''; if (f.bg_file_id) body.bg_file_id = f.bg_file_id; else if (had && !f.bg_url) body.bg_file_id = ''; this.setData({ saving: true }); api .updateDecoration(body) .then((user) => { this.setData({ saving: false }); store.setUser(user); // 返回的就是改完的 user,别再多请求一次 wx.showToast({ title: '已保存', icon: 'success' }); setTimeout(() => wx.navigateBack(), 600); }) .catch((e) => { this.setData({ saving: false }); toastErr(e, '保存失败'); }); }, });