Files
sundynix-pets/pets-fe/pages/tasks/tasks.js
T

105 lines
2.5 KiB
JavaScript

const { secure, toast } = require("../../utils/api");
const today = () => new Date().toLocaleDateString("sv-SE");
Page({
data: {
pets: [],
tasks: [],
date: today(),
showForm: false,
title: "",
petIndex: 0,
category: "food",
time_of_day: "08:30",
repeat_rule: "daily",
done: 0,
},
onShow() {
this.load();
},
async load() {
try {
const [pets, result] = await Promise.all([
secure("/pets"),
secure("/tasks?date=" + this.data.date),
]);
const tasks = result.items.map((t) => ({
...t,
petName: (pets.find((p) => p.id === t.pet_id) || {}).name || "宠物",
}));
this.setData({
pets,
tasks,
done: tasks.filter((t) => t.completed).length,
});
} catch (e) {
toast(e);
}
},
async toggle(e) {
const t = this.data.tasks[e.currentTarget.dataset.index];
try {
await secure("/tasks/" + t.id + "/completion", "PUT", {
date: this.data.date,
completed: !t.completed,
});
this.load();
} catch (err) {
toast(err);
}
},
open() {
this.setData({ showForm: true });
},
close() {
this.setData({ showForm: false });
},
field(e) {
this.setData({ [e.currentTarget.dataset.key]: e.detail.value });
},
petChange(e) {
this.setData({ petIndex: Number(e.detail.value) });
},
timeChange(e) {
this.setData({ time_of_day: e.detail.value });
},
categoryChange(e) {
this.setData({ category: e.detail.value });
},
repeatChange(e) {
this.setData({ repeat_rule: e.detail.value });
},
async save() {
if (!this.data.pets.length || !this.data.title.trim()) {
wx.showToast({ title: "请选择宠物并填写任务名", icon: "none" });
return;
}
try {
await secure("/tasks", "POST", {
pet_id: this.data.pets[this.data.petIndex].id,
title: this.data.title,
category: this.data.category,
time_of_day: this.data.time_of_day,
repeat_rule: this.data.repeat_rule,
});
this.setData({ showForm: false, title: "" });
this.load();
} catch (e) {
toast(e);
}
},
async remove(e) {
const t = this.data.tasks[e.currentTarget.dataset.index];
const result = await wx.showModal({
title: "删除任务",
content: "确定删除「" + t.title + "」吗?",
});
if (!result.confirm) return;
try {
await secure("/tasks/" + t.id, "DELETE");
this.load();
} catch (err) {
toast(err);
}
},
});