// app/static/js/user_activity.js
document.addEventListener('DOMContentLoaded', function() {
let activityChart = null;
// 初始加载
loadUserActivity();
function loadUserActivity() {
// 显示加载状态
document.getElementById('user-table-body').innerHTML = `
| 加载中... |
`;
// 调用API获取数据
fetch('/statistics/api/user-activity')
.then(response => response.json())
.then(data => {
updateUserTable(data);
updateUserChart(data);
})
.catch(error => {
console.error('加载用户活跃度数据失败:', error);
document.getElementById('user-table-body').innerHTML = `
| 加载数据失败,请稍后重试 |
`;
});
}
function updateUserTable(data) {
const tableBody = document.getElementById('user-table-body');
if (data.length === 0) {
tableBody.innerHTML = `
| 暂无数据 |
`;
return;
}
let tableHtml = '';
data.forEach((user, index) => {
tableHtml += `
| ${index + 1} |
${user.username} |
${user.nickname} |
${user.borrow_count} |
`;
});
tableBody.innerHTML = tableHtml;
}
function updateUserChart(data) {
// 销毁旧图表
if (activityChart) {
activityChart.destroy();
}
if (data.length === 0) {
return;
}
// 准备图表数据
const labels = data.map(user => user.nickname || user.username);
const borrowCounts = data.map(user => user.borrow_count);
// 创建图表
const ctx = document.getElementById('user-activity-chart').getContext('2d');
activityChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: '借阅次数',
data: borrowCounts,
backgroundColor: 'rgba(153, 102, 255, 0.6)',
borderColor: 'rgba(153, 102, 255, 1)',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: '借阅次数'
}
},
x: {
title: {
display: true,
text: '用户'
}
}
},
plugins: {
legend: {
display: false
},
title: {
display: true,
text: '最活跃用户排行'
}
}
}
});
}
});