const app = getApp() function flattenSections(bookData) { if (!bookData || !Array.isArray(bookData)) return [] const out = [] bookData.forEach(part => { if (!part.chapters || !Array.isArray(part.chapters)) return part.chapters.forEach(ch => { if (!ch.sections || !Array.isArray(ch.sections)) return ch.sections.forEach(sec => { out.push({ id: sec.id, title: sec.title || sec.id }) }) }) }) return out } Page({ data: { statusBarHeight: 44, navBarHeight: 88, isLoggedIn: false, user: null, hasFullBook: false, purchasedSections: [], purchasedSectionList: [], purchasedCount: 0, totalSections: 62, sectionList: [], loading: true }, onLoad() { const statusBarHeight = app.globalData.statusBarHeight || 44 const navBarHeight = app.globalData.navBarHeight || (statusBarHeight + 44) this.setData({ statusBarHeight, navBarHeight }) this.syncUser() this.loadBookData() }, onShow() { this.syncUser() }, syncUser() { const isLoggedIn = !!app.globalData.isLoggedIn const user = app.globalData.userInfo || null const hasFullBook = !!app.globalData.hasFullBook const purchasedSections = app.globalData.purchasedSections || [] const total = this.data.totalSections || 62 const purchasedCount = hasFullBook ? total : purchasedSections.length const sectionList = this.data.sectionList || [] const purchasedSectionList = sectionList.filter(s => purchasedSections.indexOf(s.id) >= 0) this.setData({ isLoggedIn, user, hasFullBook, purchasedSections, purchasedCount, purchasedSectionList }) }, loadBookData() { const bookData = app.globalData.bookData if (bookData && Array.isArray(bookData)) { const sectionList = flattenSections(bookData) const totalSections = sectionList.length || 62 this.setData({ sectionList, totalSections, loading: false }) this.syncUser() return } app.request('/api/book/all-chapters').then(res => { const raw = (res && res.data) ? res.data : (res && res.chapters) ? res.chapters : [] const totalSections = res.totalSections || res.total || raw.length || 62 let sectionList = [] if (Array.isArray(raw)) { raw.forEach(s => { sectionList.push({ id: s.id, title: s.sectionTitle || s.title || s.section_title || s.id }) }) } if (sectionList.length === 0 && raw.length > 0) { sectionList = raw.map(s => ({ id: s.id, title: s.sectionTitle || s.title || s.id })) } this.setData({ sectionList, totalSections, loading: false }) this.syncUser() }).catch(() => this.setData({ loading: false })) }, goBack() { wx.navigateBack({ fail: () => wx.switchTab({ url: '/pages/my/my' }) }) }, goChapters() { wx.switchTab({ url: '/pages/chapters/chapters' }) }, goToRead(e) { const id = e.currentTarget.dataset.id if (id) wx.navigateTo({ url: '/pages/read/read?id=' + encodeURIComponent(id) }) } })