fetchData() {
const user = getApp().globalData.currentUser;
if (!user) return Promise.resolve({ categoryTotals: {}, categoryDailyData: {} });
const db = wx.cloud.database();
const collectionName = this.data.statsType === '采购统计' ? 'purchases' : 'consumes';
// 构建基础查询条件,使用数组直接构造 $in
let condition = {
userId: user.nickName,
category: { $in: this.data.selectedCategories }
};
// 根据时间范围添加日期条件(年除外,即查询所有数据)
if (this.data.timeRange !== '年') {
const now = new Date();
let startDate;
switch (this.data.timeRange) {
case '周':
startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7);
break;
case '月':
startDate = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
break;
case '季':
startDate = new Date(now.getFullYear(), now.getMonth() - 3, now.getDate());
break;
default:
startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 365);
}
const startDateStr = `${startDate.getFullYear()}-${(startDate.getMonth()+1).toString().padStart(2,'0')}-${startDate.getDate().toString().padStart(2,'0')}`;
condition.date = { $gte: startDateStr };
}
if (this.data.statsType === '消费统计' && this.data.target === '成员') {
condition.consumer = this.data.member;
}
console.log('查询条件:', condition);
wx.showLoading({ title: '加载数据中' });
// 一次性获取最多1000条记录(110条足够)
return db.collection(collectionName)
.where(condition)
.field({ date: true, category: true, quantity: true, value: true })
.limit(1000)
.get()
.then(res => {
wx.hideLoading();
console.log('查询返回记录数:', res.data.length);
const records = res.data;
const categoryTotals = {};
const categoryDailyData = {};
this.data.selectedCategories.forEach(cat => {
categoryTotals[cat] = { quantity: 0, value: 0 };
categoryDailyData[cat] = new Map();
});
records.forEach(r => {
const cat = r.category;
if (!categoryTotals[cat]) return;
const qty = parseFloat(r.quantity || 0);
const val = parseFloat(r.value || 0);
categoryTotals[cat].quantity += qty;
categoryTotals[cat].value += val;
const date = r.date;
const map = categoryDailyData[cat];
if (!map.has(date)) {
map.set(date, { quantity: 0, value: 0 });
}
const day = map.get(date);
day.quantity += qty;
day.value += val;
});
const finalCategoryDailyData = {};
for (const cat in categoryDailyData) {
const map = categoryDailyData[cat];
const arr = Array.from(map.entries())
.map(([date, totals]) => ({ date, ...totals }))
.sort((a, b) => a.date.localeCompare(b.date));
finalCategoryDailyData[cat] = arr;
}
return { categoryTotals, categoryDailyData: finalCategoryDailyData };
})
.catch(err => {
wx.hideLoading();
console.error('查询失败', err);
wx.showToast({ title: '数据加载失败', icon: 'none' });
return { categoryTotals: {}, categoryDailyData: {} };
});
}
