Files
mp-vue/src/store/modules/bszx-statistics.ts

142 lines
3.6 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.

/**
* 百色中学统计数据 store
*/
import { defineStore } from 'pinia';
import { bszxOrderTotal } from '@/api/bszx/bszxOrder';
import { safeNumber } from '@/utils/type-guards';
export interface BszxStatisticsState {
// 总营业额
totalPrice: number;
// 加载状态
loading: boolean;
// 最后更新时间
lastUpdateTime: number | null;
// 缓存有效期(毫秒)- 5分钟缓存
cacheExpiry: number;
// 自动刷新定时器
refreshTimer: number | null;
}
export const useBszxStatisticsStore = defineStore({
id: 'bszx-statistics',
state: (): BszxStatisticsState => ({
totalPrice: 0,
loading: false,
lastUpdateTime: null,
// 默认缓存5分钟
cacheExpiry: 5 * 60 * 1000,
refreshTimer: null
}),
getters: {
/**
* 获取总营业额
*/
bszxTotalPrice: (state): number => {
return safeNumber(state.totalPrice);
},
/**
* 检查缓存是否有效
*/
isCacheValid: (state): boolean => {
if (!state.lastUpdateTime) return false;
const now = Date.now();
return (now - state.lastUpdateTime) < state.cacheExpiry;
}
},
actions: {
/**
* 获取百色中学统计数据
* @param forceRefresh 是否强制刷新
*/
async fetchBszxStatistics(forceRefresh = false) {
// 如果缓存有效且不强制刷新,直接返回缓存数据
if (!forceRefresh && this.isCacheValid && this.totalPrice > 0) {
return this.totalPrice;
}
this.loading = true;
try {
const result = await bszxOrderTotal();
// 处理返回的数据 - bszxOrderTotal 返回 ShopOrder[] 数组
let totalPrice = 0;
if (Array.isArray(result)) {
// 累加所有订单的金额
result.forEach((order: any) => {
if (order.payPrice) {
totalPrice += safeNumber(order.payPrice);
} else if (order.totalPrice) {
totalPrice += safeNumber(order.totalPrice);
}
});
} else if (typeof result === 'number') {
totalPrice = result;
} else if (typeof result === 'string') {
totalPrice = safeNumber(result);
} else if (result && typeof result === 'object' && 'totalPrice' in result) {
totalPrice = safeNumber((result as any).totalPrice);
}
this.totalPrice = totalPrice;
this.lastUpdateTime = Date.now();
return totalPrice;
} catch (error) {
console.error('获取百色中学统计数据失败:', error);
// 发生错误时不重置现有数据,只记录错误
throw error;
} finally {
this.loading = false;
}
},
/**
* 更新统计数据
*/
updateStatistics(data: Partial<BszxStatisticsState>) {
Object.assign(this, data);
this.lastUpdateTime = Date.now();
},
/**
* 清除缓存
*/
clearCache() {
this.totalPrice = 0;
this.lastUpdateTime = null;
},
/**
* 设置缓存有效期
*/
setCacheExpiry(expiry: number) {
this.cacheExpiry = expiry;
},
/**
* 开始自动刷新
* @param interval 刷新间隔毫秒默认5分钟
*/
startAutoRefresh(interval = 5 * 60 * 1000) {
this.stopAutoRefresh();
this.refreshTimer = window.setInterval(() => {
this.fetchBszxStatistics(true).catch(console.error);
}, interval);
},
/**
* 停止自动刷新
*/
stopAutoRefresh() {
if (this.refreshTimer) {
clearInterval(this.refreshTimer);
this.refreshTimer = null;
}
}
}
});