// pages/history/history.js const historyApi = require('../../api/history'); const userUtil = require('../../utils/user'); Page({ data: { history: [], loading: false }, onLoad() { this.loadHistory(); }, onShow() { this.loadHistory(); }, // 加载历史记录 async loadHistory() { if (!userUtil.isLogin()) { this.setData({ history: [] }); return; } this.setData({ loading: true }); try { const historyList = await historyApi.getHistoryList(); // 格式化时间显示 const formattedHistory = (historyList || []).map(item => { const readTime = item.readTime || ''; let timeStr = ''; if (readTime) { try { const date = new Date(readTime); const now = new Date(); const diff = now - date; const days = Math.floor(diff / (1000 * 60 * 60 * 24)); const hours = Math.floor(diff / (1000 * 60 * 60)); const minutes = Math.floor(diff / (1000 * 60)); if (days > 0) { timeStr = `${days}天前`; } else if (hours > 0) { timeStr = `${hours}小时前`; } else if (minutes > 0) { timeStr = `${minutes}分钟前`; } else { timeStr = '刚刚'; } } catch (e) { timeStr = readTime.substring(0, 10); } } return { ...item, readTime: timeStr }; }); this.setData({ history: formattedHistory }); } catch (error) { console.error('加载历史记录失败:', error); wx.showToast({ title: error || '加载失败', icon: 'none' }); this.setData({ history: [] }); } finally { this.setData({ loading: false }); } }, // 跳转到详情 goToDetail(e) { const contentId = e.currentTarget.dataset.id; wx.navigateTo({ url: `/pages/detail/detail?id=${contentId}` }); }, // 清空历史 async clearHistory() { if (!userUtil.isLogin()) { wx.showToast({ title: '请先登录', icon: 'none' }); return; } wx.showModal({ title: '提示', content: '确定要清空历史记录吗?', success: async (res) => { if (res.confirm) { try { await historyApi.clearHistory(); this.setData({ history: [] }); wx.showToast({ title: '已清空', icon: 'success' }); } catch (error) { wx.showToast({ title: error || '清空失败', icon: 'none' }); } } } }); } });