// pages/report/report.js
import { initPieChart } from '../../utils/drawPie';
Page({
data: {
cnum: null,
bday: '',
eday: '',
goodsData: [],
brandData: [],
totalFtm: 0,
totalZtm: 0,
saleTM: 0,
isDataLoaded: false,
showBrandModal: true,
showChart: true,
chartData: [],
ec: {
onInit: null
}
},
onLoad(options) {
const app = getApp();
this.setData({
cnum: app.globalData.cnum,
bday: app.DateToStr(new Date()),
eday: app.DateToStr(new Date()),
});
},
onBdayChange: function(event) {
this.setData({
bday: event.detail.value
});
this.fetchData();
},
onEdayChange: function(event) {
this.setData({
eday: event.detail.value
});
this.fetchData();
},
onConfirm: function() {
this.fetchData();
},
fetchData: function() {
const { cnum, bday, eday } = this.data;
const app = getApp();
wx.request({
url: `http://129.204.198.79:5000/PF_HJ/show_data_Ms/khs_Sale/${cnum},${bday},${eday}`,
method: 'GET',
success: (res) => {
console.log('API Response:', res); // 打印整个响应数据
if (res.statusCode === 200) {
if (Array.isArray(res.data) && res.data.length >= 2) {
let goodsData = res.data[0].map(item => ({
...item,
f_tc: Number(item.f_tc),
f_tm: parseFloat(item.f_tm),
z_tc: Number(item.z_tc),
z_tm: parseFloat(item.z_tm)
}));
const totalFtm = goodsData.reduce((sum, item) => sum + item.f_tm, 0);
const totalZtm = goodsData.reduce((sum, item) => sum + item.z_tm, 0);
let brandData = res.data[1].map(item => {
if (item.name && item.tm) {
return {
...item,
tm: parseFloat(item.tm) // 存储原始数字值
};
} else {
console.warn('Invalid brand item:', item); // 打印无效的品牌项
return null; // 返回 null 以便后面过滤掉
}
}).filter(item => item !== null); // 过滤掉无效项
console.log('Parsed brandData:', brandData); // 打印解析后的品牌数据
this.setData({
goodsData: this.formatGoodsData(goodsData),
totalFtm: app.formatCurrency(totalFtm),
totalZtm: app.formatCurrency(totalZtm),
saleTM: app.formatCurrency(totalFtm - totalZtm),
brandData: brandData, // 确保设置 brandData
isDataLoaded: true
});
this.onBrandTap(); // 确保调用
} else {
wx.showToast({
title: '返回数据格式不正确',
icon: 'none'
});
}
} else {
wx.showToast({
title: '获取数据失败',
icon: 'none'
});
}
},
fail: () => {
wx.showToast({
title: '请求失败',
icon: 'none'
});
}
});
},
formatGoodsData: function(goodsData) {
const app = getApp();
return goodsData.map(item => ({
...item,
f_tm: app.formatCurrency(item.f_tm),
z_tm: app.formatCurrency(item.z_tm)
}));
},
onBrandTap: function() {
console.log(this.data.brandData); // 确保使用 this.data.brandData
const chartData = this.data.brandData.map(item => ({
value: item.tm, // 使用新的数字字段
name: item.name.trim() // 去除多余空格
})).filter(item => item.value > 0); // 过滤掉零值
console.log('Chart Data:', chartData); // 调试信息,确保数据正确
if (chartData.length === 0) {
console.warn('No valid data for chart');
return; // 如果没有有效数据,则不进行图表绘制
}
this.setData({
ec: {
onInit: (canvas, width, height, dpr) => {
console.log('Canvas:', canvas); // 调试信息
return initPieChart(canvas, width, height, dpr, '品牌销售占比', chartData);
}
}
});
},
});