Files
WXProgram/miniprogram/services/statisticsService.ts
2025-12-10 22:49:22 +08:00

244 lines
6.9 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 统计服务 - 处理系统统计数据获取和缓存
import apiService from './apiService';
/**
* 统计数据接口
*/
export interface StatisticsData {
employeeCount: number; // 员工总数
orderCount: number; // 订单总数
warehouseCount: number; // 仓库总数
pendingOrders: number; // 待处理订单数
activeOrders: number; // 进行中订单数
completedOrders: number; // 已完成订单数
timestamp: number; // 数据时间戳
}
/**
* 工作统计数据接口
*/
export interface WorkStats {
todayOrders: number; // 今日订单数
completedOrders: number; // 已完成订单数
pendingOrders: number; // 待处理订单数
timestamp: number; // 数据时间戳
}
/**
* 个人统计数据接口
*/
export interface PersonalStats {
totalOrders: number; // 总订单数
completedOrders: number; // 已完成订单数
pendingOrders: number; // 待处理订单数
averageDeliveryTime: number; // 平均配送时间(分钟)
timestamp: number; // 数据时间戳
}
/**
* 统计服务类
* 提供系统统计数据的获取和缓存功能
*/
class StatisticsService {
// 数据缓存
private cache: StatisticsData | null = null;
// 缓存超时时间5分钟
private readonly cacheTimeout = 5 * 60 * 1000;
/**
* 构造函数
*/
constructor() {
// 不需要初始化HTTP客户端直接使用apiService
}
/**
* 获取系统统计数据
* 采用一个API请求获取三个统计数据后续操作客户端自行统计
* @param forceRefresh 是否强制刷新,不使用缓存
*/
async getSystemStats(forceRefresh: boolean = false): Promise<StatisticsData> {
// 检查缓存是否有效,且不强制刷新
if (!forceRefresh && this.cache && Date.now() - this.cache.timestamp < this.cacheTimeout) {
console.log('使用缓存的统计数据');
return this.cache;
}
console.log('重新获取统计数据');
try {
// 使用系统统计API获取三个统计数据
const systemStats = await this.getSystemStatsFromAPI();
this.cache = {
...systemStats,
timestamp: Date.now()
};
return this.cache;
} catch (error) {
console.warn('系统统计API不可用使用默认值:', error);
// 如果API不可用返回默认值
this.cache = {
employeeCount: 0,
orderCount: 0,
warehouseCount: 0,
pendingOrders: 0,
activeOrders: 0,
completedOrders: 0,
timestamp: Date.now()
};
return this.cache;
}
}
/**
* 从API获取系统统计数据
*/
private async getSystemStatsFromAPI(): Promise<StatisticsData> {
try {
// 调用系统统计API
const response = await apiService.getSystemStats();
console.log('API返回的统计数据:', response);
// API返回的数据结构是 { data: { ... }, success: true }
// 需要提取data字段中的数据
const stats = (response as any).data || response;
console.log('提取的统计数据:', stats);
// 转换API响应格式为StatisticsData格式
// 根据API实际返回的字段进行映射
const result = {
employeeCount: stats.totalEmployees || stats.totalDeliveryPersons || 0,
orderCount: stats.totalOrders || (stats.pendingOrders || 0) + (stats.activeOrders || 0),
warehouseCount: stats.totalWarehouses || 0,
pendingOrders: stats.pendingOrders || 0,
activeOrders: stats.activeOrders || 0,
completedOrders: 0, // 需要从其他接口获取
timestamp: Date.now()
};
console.log('转换后的统计数据:', result);
return result;
} catch (error) {
console.error('获取系统统计数据失败:', error);
throw error;
}
}
/**
* 获取工作统计数据
*/
async getWorkStats(): Promise<WorkStats> {
try {
// 使用apiService的getOrderStats方法获取今日订单统计
const response = await apiService.getOrderStats('today');
// 转换API响应格式为WorkStats格式
return {
todayOrders: response.totalOrders || 0,
completedOrders: response.completedOrders || 0,
pendingOrders: response.inProgressOrders || 0,
timestamp: Date.now()
};
} catch (error) {
console.error('获取工作统计数据失败:', error);
// 如果API调用失败返回默认值
return {
todayOrders: 0,
completedOrders: 0,
pendingOrders: 0,
timestamp: Date.now()
};
}
}
/**
* 获取个人统计数据
* 由于API中没有直接的个人统计接口这里返回默认值
* 实际应用中应该从订单服务中获取当前用户的订单统计
*/
async getPersonalStats(): Promise<PersonalStats> {
try {
// 在实际应用中,这里应该调用订单服务获取当前用户的订单统计
// 由于API限制暂时返回默认值
console.warn('个人统计API不可用返回默认值');
return {
totalOrders: 0,
completedOrders: 0,
pendingOrders: 0,
averageDeliveryTime: 0,
timestamp: Date.now()
};
} catch (error) {
console.error('获取个人统计数据失败:', error);
// 如果API调用失败返回默认值
return {
totalOrders: 0,
completedOrders: 0,
pendingOrders: 0,
averageDeliveryTime: 0,
timestamp: Date.now()
};
}
}
/**
* 手动刷新统计数据(清除缓存)
*/
refreshStats(): void {
this.cache = null;
console.log('统计数据缓存已清除');
}
/**
* 获取缓存状态
*/
getCacheStatus(): { hasCache: boolean; isExpired: boolean; age: number } {
if (!this.cache) {
return { hasCache: false, isExpired: true, age: 0 };
}
const age = Date.now() - this.cache.timestamp;
const isExpired = age > this.cacheTimeout;
return { hasCache: true, isExpired, age };
}
/**
* 客户端更新统计数据(直接传值更新)
* @param type 数据类型:'employee' | 'order' | 'warehouse'
* @param count 对应的数量值
*/
updateStats(type: 'employee' | 'order' | 'warehouse', count: number): void {
if (!this.cache) {
console.warn('没有缓存数据,无法更新统计');
return;
}
switch (type) {
case 'employee':
this.cache.employeeCount = Math.max(0, count);
break;
case 'order':
this.cache.orderCount = Math.max(0, count);
break;
case 'warehouse':
this.cache.warehouseCount = Math.max(0, count);
break;
}
this.cache.timestamp = Date.now();
console.log(`统计数据已更新: ${type} = ${count}`);
}
}
/**
* 统计服务单例实例
* 导出供应用程序全局使用
*/
export default new StatisticsService();