history.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. // pages/history/history.js
  2. const historyApi = require('../../api/history');
  3. const userUtil = require('../../utils/user');
  4. Page({
  5. data: {
  6. history: [],
  7. loading: false
  8. },
  9. onLoad() {
  10. this.loadHistory();
  11. },
  12. onShow() {
  13. this.loadHistory();
  14. },
  15. // 加载历史记录
  16. async loadHistory() {
  17. if (!userUtil.isLogin()) {
  18. this.setData({ history: [] });
  19. return;
  20. }
  21. this.setData({ loading: true });
  22. try {
  23. const historyList = await historyApi.getHistoryList();
  24. // 格式化时间显示
  25. const formattedHistory = (historyList || []).map(item => {
  26. const readTime = item.readTime || '';
  27. let timeStr = '';
  28. if (readTime) {
  29. try {
  30. const date = new Date(readTime);
  31. const now = new Date();
  32. const diff = now - date;
  33. const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  34. const hours = Math.floor(diff / (1000 * 60 * 60));
  35. const minutes = Math.floor(diff / (1000 * 60));
  36. if (days > 0) {
  37. timeStr = `${days}天前`;
  38. } else if (hours > 0) {
  39. timeStr = `${hours}小时前`;
  40. } else if (minutes > 0) {
  41. timeStr = `${minutes}分钟前`;
  42. } else {
  43. timeStr = '刚刚';
  44. }
  45. } catch (e) {
  46. timeStr = readTime.substring(0, 10);
  47. }
  48. }
  49. return {
  50. ...item,
  51. readTime: timeStr
  52. };
  53. });
  54. this.setData({ history: formattedHistory });
  55. } catch (error) {
  56. console.error('加载历史记录失败:', error);
  57. wx.showToast({
  58. title: error || '加载失败',
  59. icon: 'none'
  60. });
  61. this.setData({ history: [] });
  62. } finally {
  63. this.setData({ loading: false });
  64. }
  65. },
  66. // 跳转到详情
  67. goToDetail(e) {
  68. const contentId = e.currentTarget.dataset.id;
  69. wx.navigateTo({
  70. url: `/pages/detail/detail?id=${contentId}`
  71. });
  72. },
  73. // 清空历史
  74. async clearHistory() {
  75. if (!userUtil.isLogin()) {
  76. wx.showToast({
  77. title: '请先登录',
  78. icon: 'none'
  79. });
  80. return;
  81. }
  82. wx.showModal({
  83. title: '提示',
  84. content: '确定要清空历史记录吗?',
  85. success: async (res) => {
  86. if (res.confirm) {
  87. try {
  88. await historyApi.clearHistory();
  89. this.setData({ history: [] });
  90. wx.showToast({
  91. title: '已清空',
  92. icon: 'success'
  93. });
  94. } catch (error) {
  95. wx.showToast({
  96. title: error || '清空失败',
  97. icon: 'none'
  98. });
  99. }
  100. }
  101. }
  102. });
  103. }
  104. });