// pages/read/read.js const chapterApi = require('../../api/chapter'); const historyApi = require('../../api/history'); const userUtil = require('../../utils/user'); Page({ data: { contentId: null, chapterId: null, chapter: null, chapters: [], currentIndex: 0, fontSize: 32, // 字体大小(rpx) backgroundColor: '#fff', // 背景颜色 loading: true, showSettings: false }, onLoad(options) { const contentId = parseInt(options.contentId); const chapterId = parseInt(options.chapterId); if (!contentId || !chapterId) { wx.showToast({ title: '参数错误', icon: 'none' }); setTimeout(() => { wx.navigateBack(); }, 1500); return; } this.setData({ contentId, chapterId }); this.loadChapters(); this.loadChapter(); }, // 加载章节列表 async loadChapters() { try { const chapters = await chapterApi.getBookChapterList(this.data.contentId); const currentIndex = chapters.findIndex(c => c.chapterId === this.data.chapterId); this.setData({ chapters, currentIndex: currentIndex >= 0 ? currentIndex : 0 }); } catch (error) { console.error('加载章节列表失败:', error); } }, // 加载章节内容 async loadChapter() { this.setData({ loading: true }); try { const chapter = await chapterApi.getBookChapter(this.data.chapterId); this.setData({ chapter }); wx.setNavigationBarTitle({ title: chapter.chapterTitle || '阅读' }); // 保存阅读历史 this.saveHistory(); } catch (error) { wx.showToast({ title: error || '加载失败', icon: 'none' }); } finally { this.setData({ loading: false }); } }, // 保存阅读历史 async saveHistory() { if (!userUtil.isLogin() || !this.data.contentId) { return; } try { await historyApi.addHistory(this.data.contentId); } catch (error) { console.error('保存阅读历史失败:', error); // 静默失败,不影响阅读体验 } }, // 上一章 prevChapter() { if (this.data.currentIndex > 0) { const prevChapter = this.data.chapters[this.data.currentIndex - 1]; this.setData({ chapterId: prevChapter.chapterId, currentIndex: this.data.currentIndex - 1 }); this.loadChapter(); } else { wx.showToast({ title: '已经是第一章了', icon: 'none' }); } }, // 下一章 nextChapter() { if (this.data.currentIndex < this.data.chapters.length - 1) { const nextChapter = this.data.chapters[this.data.currentIndex + 1]; this.setData({ chapterId: nextChapter.chapterId, currentIndex: this.data.currentIndex + 1 }); this.loadChapter(); } else { wx.showToast({ title: '已经是最后一章了', icon: 'none' }); } }, // 显示/隐藏设置 toggleSettings() { this.setData({ showSettings: !this.data.showSettings }); }, // 调整字体大小 adjustFontSize(e) { const size = parseInt(e.detail.value); this.setData({ fontSize: size * 2 + 28 }); // 28-48 }, // 切换背景色 changeBackground(e) { const color = e.currentTarget.dataset.color; this.setData({ backgroundColor: color }); }, // 显示目录 showChapterList() { const itemList = this.data.chapters.map((item, index) => `${index + 1}. ${item.chapterTitle}` ); wx.showActionSheet({ itemList, success: (res) => { const chapter = this.data.chapters[res.tapIndex]; this.setData({ chapterId: chapter.chapterId, currentIndex: res.tapIndex }); this.loadChapter(); } }); } });