You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

128 lines
3.6 KiB

// app.js
const api = require('./utils/api');
App({
globalData: {
userInfo: null,
currentTab: 'index',
sessionStartTime: null,
// 缓存相关
cachedData: {
userInfo: null,
personnelInfo: null
},
cacheExpireTime: {
userInfo: 0, // 时间戳,0表示无缓存
personnelInfo: 0 // 时间戳,0表示无缓存
}
},
// 事件总线,用于页面间通信
eventBus: {
on(event, callback) {
if (!this.handlers) this.handlers = {};
if (!this.handlers[event]) this.handlers[event] = [];
this.handlers[event].push(callback);
},
off(event, callback) {
if (!this.handlers || !this.handlers[event]) return;
this.handlers[event] = this.handlers[event].filter(handler => handler !== callback);
},
emit(event, data) {
if (!this.handlers || !this.handlers[event]) return;
this.handlers[event].forEach(handler => {
try {
handler(data);
} catch (error) {
console.error('事件处理函数执行错误:', error);
}
});
}
},
// 更新当前选中的tab
updateCurrentTab(tabName) {
this.globalData.currentTab = tabName;
},
// 缓存管理方法
setCache(key, data, expireTime = 3600000) { // 默认缓存1小时
this.globalData.cachedData[key] = data;
this.globalData.cacheExpireTime[key] = Date.now() + expireTime;
},
getCache(key) {
const now = Date.now();
if (this.globalData.cacheExpireTime[key] > now) {
return this.globalData.cachedData[key];
}
// 缓存过期,清除缓存
this.globalData.cachedData[key] = null;
this.globalData.cacheExpireTime[key] = 0;
return null;
},
// 获取业务员信息(带缓存)
getPersonnelInfo(phoneNumber) {
return new Promise((resolve, reject) => {
// 检查缓存
const cachedData = this.getCache('personnelInfo');
if (cachedData) {
console.log('使用缓存的业务员信息');
resolve(cachedData);
return;
}
// 从服务器获取
api.request('/api/personnel/get', 'POST', { phone: phoneNumber })
.then(res => {
console.log('从服务器获取业务员信息成功:', res);
// 设置缓存,缓存1小时
this.setCache('personnelInfo', res, 3600000);
resolve(res);
})
.catch(err => {
console.error('获取业务员信息失败:', err);
reject(err);
});
});
},
// 记录用户踪迹
recordUserTrace(action, additionalData = {}) {
const traceData = {
action: action,
timestamp: new Date().toISOString(),
...additionalData
};
api.addUserTrace(traceData);
},
onLaunch() {
console.log('App launched');
// 记录用户进入小程序
this.recordUserTrace('app_launch');
this.globalData.sessionStartTime = new Date().toISOString();
},
onShow() {
console.log('App shown');
// 记录用户显示小程序
this.recordUserTrace('app_show');
if (!this.globalData.sessionStartTime) {
this.globalData.sessionStartTime = new Date().toISOString();
}
},
onHide() {
console.log('App hidden');
// 记录用户隐藏小程序,包含会话时长
const sessionEndTime = new Date().toISOString();
this.recordUserTrace('app_hide', {
sessionStartTime: this.globalData.sessionStartTime,
sessionEndTime: sessionEndTime,
sessionDuration: new Date(sessionEndTime) - new Date(this.globalData.sessionStartTime)
});
this.globalData.sessionStartTime = null;
}
});