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

69 lines
1.7 KiB
JavaScript

const { secure, toast } = require("../../utils/api");
Page({
data: {
pets: [],
selected: [],
tasks: [],
walkCount: 0,
name: "铲屎官",
loading: true,
},
onShow() {
this.load();
},
async load() {
try {
const [pets, tasks, walks, me] = await Promise.all([
secure("/pets"),
secure("/tasks"),
secure("/walks"),
secure("/me"),
]);
const chosen = wx.getStorageSync("walk_pet_ids") || [],
month = new Date().toISOString().slice(0, 7);
this.setData({
pets,
selected: chosen.filter((id) => pets.some((p) => p.id === id)),
tasks: tasks.items,
walkCount: walks.filter((w) => w.started_at.slice(0, 7) === month)
.length,
name: me.nickname || "铲屎官",
loading: false,
});
} catch (e) {
this.setData({ loading: false });
toast(e);
}
},
pick(e) {
this.setData({ selected: e.detail.selected });
wx.setStorageSync("walk_pet_ids", e.detail.selected);
},
start() {
if (!this.data.selected.length) {
wx.showToast({ title: "先选择一起出门的狗狗", icon: "none" });
return;
}
wx.redirectTo({ url: "/pages/walk/walk" });
},
goTasks() {
wx.redirectTo({ url: "/pages/tasks/tasks" });
},
goWalks() {
wx.redirectTo({ url: "/pages/walk/walk" });
},
async complete(e) {
const id = e.currentTarget.dataset.id,
task = this.data.tasks.find((t) => t.id === id);
try {
await secure("/tasks/" + id + "/completion", "PUT", {
date: new Date().toLocaleDateString("sv-SE"),
completed: !task.completed,
});
await this.load();
} catch (err) {
toast(err);
}
},
});