Files
2026-04-28 10:36:51 +08:00

109 lines
3.1 KiB
JavaScript

import request from '../../../utils/request';
Page({
data: {
plantId: '',
recordType: 'growth',
content: '',
image: ''
},
onLoad(options) {
if (options.plantId) {
this.setData({ plantId: options.plantId });
}
},
setRecordType(e) {
const type = e.currentTarget.dataset.type;
this.setData({ recordType: type });
},
onContentInput(e) {
this.setData({ content: e.detail.value });
},
handleChooseImage() {
wx.chooseMedia({
count: 1,
mediaType: ['image'],
sourceType: ['album', 'camera'],
success: (res) => {
this.setData({
image: res.tempFiles[0].tempFilePath
});
}
});
},
handleRemoveImage() {
this.setData({ image: '' });
},
async handleAddRecord() {
if (!this.data.content.trim()) {
wx.showToast({ title: '请填写备注', icon: 'none' });
return;
}
if (!this.data.plantId) {
wx.showToast({ title: '缺少植物ID', icon: 'none' });
return;
}
wx.showLoading({ title: '保存中...', mask: true });
try {
let ossIds = [];
// 1. Upload Image if exists
if (this.data.image) {
const uploadRes = await request.upload(this.data.image);
// Correctly extract ID from nested 'file' object based on API response
if (uploadRes && uploadRes.file && uploadRes.file.id) {
ossIds.push(uploadRes.file.id);
} else if (uploadRes && uploadRes.id) {
// Fallback just in case
ossIds.push(uploadRes.id);
} else {
console.warn('Upload response structure mismatch:', uploadRes);
}
}
// 2. Prepare payload
const mapTitle = {
growth: '生长记录', flower: '开花记录', repot: '换盆记录',
prune: '修剪记录', fertilize: '施肥记录', soil: '换土记录',
pest: '病虫害记录', medicine: '用药记录', move: '移位记录',
other: '日常记录'
};
const title = mapTitle[this.data.recordType] || '日常记录';
const payload = {
plantId: this.data.plantId,
ossIds: ossIds,
name: title,
tag: this.data.recordType,
desc: this.data.content.substring(0, 100),
content: this.data.content
};
// 3. Call Add API
await request.post('/plant/growth/add', payload);
wx.hideLoading();
wx.showToast({ title: '保存成功', icon: 'success' });
// 4. Navigate back, detail page will refresh in onShow
setTimeout(() => {
wx.navigateBack();
}, 1000);
} catch (err) {
wx.hideLoading();
console.error('Add record failed', err);
}
}
});