const { secure, upload, toast } = require("../../utils/api"); Page({ data: { id: "", name: "", breed: "", breed_id: "", gender: "male", birth_date: "", weight_kg: "", coat: "", allergies: "", care_notes: "", avatar_file_id: "", avatar_url: "", saving: false, }, onLoad(options) { if (options.id) { this.setData({ id: options.id }); this.load(options.id); } }, async load(id) { try { this.setData(await secure("/pets/" + id)); } catch (e) { toast(e); } }, field(e) { this.setData({ [e.currentTarget.dataset.key]: e.detail.value }); }, breedChange(e) { this.setData({ breed: e.detail.name, breed_id: e.detail.id || "" }); }, date(e) { this.setData({ birth_date: e.detail.value }); }, gender(e) { this.setData({ gender: e.detail.value }); }, async choose() { let selection; try { selection = await wx.chooseMedia({ count: 1, mediaType: ["image"] }); } catch (e) { if (/^chooseMedia:fail cancel\b/i.test((e && e.errMsg) || "")) return; toast(e); return; } const photo = selection && selection.tempFiles && selection.tempFiles[0]; if (!photo || !photo.tempFilePath) return; try { const file = await upload(photo.tempFilePath); this.setData({ avatar_file_id: file.id, avatar_url: file.url }); } catch (e) { toast(e); } }, async save() { if (this.data.saving) return; if (!this.data.name.trim()) { wx.showToast({ title: "请输入名字", icon: "none" }); return; } const body = { name: this.data.name, species: "dog", breed: this.data.breed, breed_id: this.data.breed_id || null, gender: this.data.gender, birth_date: this.data.birth_date || "", weight_kg: Number(this.data.weight_kg) || 0, coat: this.data.coat, allergies: this.data.allergies, care_notes: this.data.care_notes, avatar_file_id: this.data.avatar_file_id || null, }; this.setData({ saving: true }); try { await secure( "/pets" + (this.data.id ? "/" + this.data.id : ""), this.data.id ? "PUT" : "POST", body, ); wx.navigateBack(); } catch (e) { toast(e); } finally { this.setData({ saving: false }); } }, async archive() { const confirm = await wx.showModal({ title: "归档宠物", content: "归档后不会再出现在遛狗和任务中。", }); if (!confirm.confirm) return; try { await secure("/pets/" + this.data.id, "DELETE"); wx.navigateBack(); } catch (e) { toast(e); } }, });