Files
sundynix-pets/pets-fe/pages/pet-edit/pet-edit.js
T

89 lines
2.1 KiB
JavaScript

const { secure, upload, toast } = require("../../utils/api");
Page({
data: {
id: "",
name: "",
breed: "柯基",
gender: "male",
birth_date: "",
weight_kg: "",
coat: "",
allergies: "",
care_notes: "",
avatar_file_id: "",
avatar_url: "",
},
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 });
},
date(e) {
this.setData({ birth_date: e.detail.value });
},
gender(e) {
this.setData({ gender: e.detail.value });
},
async choose() {
try {
const r = await wx.chooseMedia({ count: 1, mediaType: ["image"] });
const file = await upload(r.tempFiles[0].tempFilePath);
this.setData({ avatar_file_id: file.id, avatar_url: file.url });
} catch (e) {
toast(e);
}
},
async save() {
if (!this.data.name.trim()) {
wx.showToast({ title: "请输入名字", icon: "none" });
return;
}
const body = {
name: this.data.name,
species: "dog",
breed: this.data.breed,
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,
};
try {
await secure(
"/pets" + (this.data.id ? "/" + this.data.id : ""),
this.data.id ? "PUT" : "POST",
body,
);
wx.navigateBack();
} catch (e) {
toast(e);
}
},
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);
}
},
});