// index.js const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0' const testCover = '/assets/images/bg-book.png' import { getBannerList, getCardNovels, getBrowsingHistory, getNovelDetail } from '../../api/api' import { goToBookDetail, SendEvent } from '../../utils/util' import { apple } from '../../config/config' const app = getApp() let interstitialAd = null Page({ data: { isLoggedIn: false, // 轮播配置 indicatorDots: true, autoplay: true, interval: 3000, duration: 500, cardNovels: [], bannerList: [], // 添加banner列表数据 // 性别选项 gender: 'male', // male or female // 主编推荐数据 recommendBooks: [], // 主编推荐数据 // 推荐书籍列表 bookList: [], // 全网热推 hotBooks: [], // 全网热推数据 // 强力推荐 showStrongRecommend: false, // 控制强力推荐模块显示/隐藏 strongBooks: [], // 最近阅读书籍 recentBook: null, // 最近阅读的书籍 showRecentBook: false, // 是否显示最近阅读 isRecentBookHidden: false, // 最近阅读是否隐藏 recentBookAnimation: {}, // 最近阅读动画数据 motto: 'Hello World', userInfo: { avatarUrl: defaultAvatarUrl, nickName: '', }, hasUserInfo: false, canIUseGetUserProfile: wx.canIUse('getUserProfile'), canIUseNicknameComp: wx.canIUse('input.type.nickname'), share_count: 1, }, onLoad(options) { console.log('入参options:', options) const promotionid = options.promotionId; console.log('传入promotionid:', promotionid) this.interstitalLoad() this.autoLogin(promotionid); // 创建动画实例 this.recentBookAnimator = wx.createAnimation({ duration: 300, timingFunction: 'ease', }); const scene = wx.getStorageSync('scene'); const bookId = parseInt(options.novelId); const jump = options.jump;// 跳转类型 1-不进阅读器 console.log('传入jump:', jump) console.log('scene:', scene) console.log('传入novelId:', bookId) if (bookId && this.data.share_count === 1 && (scene === 1008 || scene === 1007) && jump !== 1) { getNovelDetail(bookId).then(res => { this.setData({ share_count: 2 }) goToBookDetail({ bookId, wxBookId: res.wxBookId }) }) } else if (bookId && this.data.share_count === 2) { setTimeout(() => { this.interstitalPlayFn() }, 1000) } }, onShow() { // 每次页面显示时检查是否需要更新数据 if (this.data.isLoggedIn) { this.checkAndUpdateGender(); // 每次页面显示时获取最近阅读 this.getRecentReadBook(); } }, onTabItemTap(item) { console.log(item.index) setTimeout(() => { this.interstitalPlayFn() }, 1000) // tabBar 点击时检查是否需要更新数据 if (this.data.isLoggedIn) { this.checkAndUpdateGender(); } }, // 插屏广告加载 interstitalLoad() { let adId = apple.ads.insertAdId interstitialAd = wx.createInterstitialAd({ adUnitId: adId }) interstitialAd.onLoad(() => { console.log('书城页插屏广告onLoad') }) interstitialAd.onError((err) => { console.log('书城页插屏广告onError', err) }) interstitialAd.onClose(() => { console.log('书城页插屏广告onClose') }) }, // 插屏广告展示 interstitalPlayFn() { if (interstitialAd) { interstitialAd.show().catch((err) => { console.error('书城页插屏显示错误', err) }) } }, // 页面滚动触发 onPageScroll(e) { // 清除之前的定时器 if (this.scrollTimer) { clearTimeout(this.scrollTimer); this.scrollTimer = null; } // 滚动时隐藏最近阅读 if (e.scrollTop > 300 && !this.data.isRecentBookHidden && this.data.showRecentBook) { this.hideRecentBook(); } // 设置滑动停止后的定时器 this.lastScrollTop = e.scrollTop; this.scrollTimer = setTimeout(() => { // 2秒后检查是否已经停止滚动 if (this.lastScrollTop === e.scrollTop && this.data.isRecentBookHidden && this.data.showRecentBook) { this.showRecentBook(); } }, 1500); // 2秒后执行 }, // 隐藏最近阅读 hideRecentBook() { // 计算移动距离,只漏出10px const windowWidth = wx.getSystemInfoSync().windowWidth; const rpxToPx = windowWidth / 750; // rpx到px的转换比例 const btnWidth = 90 * rpxToPx; // 悬浮按钮宽度,90rpx转换为px const moveX = -(btnWidth + 35); // 只漏出10px this.recentBookAnimator.translateX(moveX).step(); this.setData({ recentBookAnimation: this.recentBookAnimator.export(), isRecentBookHidden: true }); }, // 显示最近阅读 showRecentBook() { this.recentBookAnimator.translateX(0).step(); this.setData({ recentBookAnimation: this.recentBookAnimator.export(), isRecentBookHidden: false }); }, // 点击隐藏的最近阅读 toggleRecentBook() { if (this.data.isRecentBookHidden) { // 隐藏状态点击展开 this.showRecentBook(); } else { // 展开状态点击跳转 this.goToRecentBook(); } }, // 自动登录 async autoLogin(promotionid) { try { // 检查是否已经登录 const token = wx.getStorageSync('accessToken'); if (token) { this.setData({ isLoggedIn: true }); // 获取性别设置并加载数据 this.initGenderAndLoadData(); // 获取最近阅读记录 this.getRecentReadBook(); return; } // 未登录,执行登录 const res = await getApp().login(promotionid); this.setData({ isLoggedIn: true }); // 登录成功后获取性别设置并加载数据 this.initGenderAndLoadData(); // 获取最近阅读记录 this.getRecentReadBook(); } catch (error) { console.error('登录失败:', error); // 登录失败也尝试加载数据,使用默认性别 this.initGenderAndLoadData(); } }, // 初始化性别设置并加载数据 initGenderAndLoadData() { // 获取保存的性别设置,如果没有则使用默认值 const gender = wx.getStorageSync('gender') || 'male'; this.setData({ gender }); // 加载所有数据 this.loadAllData(); }, // 检查并更新性别,如果有变化则重新加载数据 checkAndUpdateGender() { const savedGender = wx.getStorageSync('gender') || 'male'; if (savedGender !== this.data.gender) { this.setData({ gender: savedGender }); this.loadAllData(); } }, // 获取最近阅读的书籍 async getRecentReadBook() { try { const historyList = await getBrowsingHistory(); if (Array.isArray(historyList) && historyList.length > 0) { // 取第一本作为最近阅读 const recentBook = historyList[0]; this.setData({ recentBook: recentBook, showRecentBook: true, isRecentBookHidden: false }); // 重置动画 if (this.recentBookAnimator) { this.recentBookAnimator.translateX(0).step(); this.setData({ recentBookAnimation: this.recentBookAnimator.export() }); } } else { this.setData({ showRecentBook: false }); } } catch (error) { console.error('获取最近阅读失败:', error); this.setData({ showRecentBook: false }); } }, // 跳转到最近阅读的书籍 goToRecentBook() { if (this.data.recentBook) { SendEvent('click_bookmall_recently_read', { "video_id": this.data.recentBook.novelId, "wx_book_id": this.data.recentBook.wxBookId, "chapter_no": this.data.recentBook.novelChapterId, "uuid": app.globalData.uuid }); goToBookDetail({ bookId: this.data.recentBook.novelId, wxBookId: this.data.recentBook.wxBookId, chapterId: this.data.recentBook.novelChapterId }); } }, // 加载所有数据 loadAllData() { wx.showLoading({ title: '加载中...' }); // 并行请求数据 Promise.all([ this.getBannerList(), this.getCardNovels() ]).finally(() => { wx.hideLoading(); }); }, // 切换性别分类 switchGender: function (e) { const { gender } = e.detail; // 如果性别没有改变,直接返回 if (this.data.gender === gender) { return; } // 保存性别设置到本地存储 wx.setStorageSync('gender', gender); this.setData({ gender }); SendEvent('click_bookmall_classify', { "gender": gender, "uuid": app.globalData.uuid }); // 重新加载数据 this.loadAllData(); }, // 跳转到搜索页面 goToSearch: function () { // SendEvent('click_bookmall_classify', {}); wx.navigateTo({ url: '/pages/search/search', }); }, // 跳转到书籍详情页 goToBookDetail: function (e) { const bookId = e.currentTarget.dataset.bookId; const wxBookId = e.currentTarget.dataset.wxBookId; const chapterId = e.currentTarget.dataset.chapterId; console.log('bookId', bookId); console.log('wxBookId', wxBookId); console.log('chapterId', chapterId); goToBookDetail({ bookId, wxBookId, chapterId }); }, // 跳转到功能页面 goToFeature: function (e) { const feature = e.currentTarget.dataset.feature; switch (feature) { case 'recent': // 修改为跳转到书架页面的阅读历史标签 SendEvent('click_shelf_tab', { 'uuid': app.globalData.uuid }) wx.switchTab({ url: '/pages/bookshelf/bookshelf' }); break; case 'user': // 修改为跳转到我的页面 SendEvent('click_mine_tab', { 'uuid': app.globalData.uuid }) wx.switchTab({ url: '/pages/mine/mine' }); break; case 'category': // 修改为跳转到分类页面 SendEvent('click_classify_tab', { 'uuid': app.globalData.uuid }) wx.switchTab({ url: '/pages/category/category' }); break; case 'hot': SendEvent('click_bookmall_classify', { 'uuid': app.globalData.uuid }) wx.navigateTo({ url: '/pages/book/list?type=hot' }); break; case 'recommend': SendEvent('click_bookmall_classify', { 'uuid': app.globalData.uuid }) wx.navigateTo({ url: '/pages/book/list?type=recommend' }); break; default: break; } }, bindViewTap() { wx.navigateTo({ url: '../logs/logs' }) }, onChooseAvatar(e) { const { avatarUrl } = e.detail const { nickName } = this.data.userInfo this.setData({ "userInfo.avatarUrl": avatarUrl, hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl, }) }, onInputChange(e) { const nickName = e.detail.value const { avatarUrl } = this.data.userInfo this.setData({ "userInfo.nickName": nickName, hasUserInfo: nickName && avatarUrl && avatarUrl !== defaultAvatarUrl, }) }, getUserProfile(e) { // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认,开发者妥善保管用户快速填写的头像昵称,避免重复弹窗 wx.getUserProfile({ desc: '展示用户信息', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 success: (res) => { console.log(res) this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } }) }, // 获取banner列表 async getBannerList() { try { const channel = this.data.gender === 'male' ? 1 : 2; const bannerList = await getBannerList(channel); this.setData({ bannerList }); return bannerList; } catch (error) { console.error('获取banner失败:', error); wx.showToast({ title: '获取banner失败', icon: 'none' }); return []; } }, async getCardNovels() { try { const channel = this.data.gender === 'male' ? 1 : 2; const cardNovels = await getCardNovels(channel); this.setData({ cardNovels }); // 处理主编推荐数据 if (cardNovels[0]) { const [firstBook, ...restBooks] = cardNovels[0].novelList; this.setData({ recommendBooks: firstBook ? [{ id: firstBook.id, title: firstBook.title, desc: firstBook.brief, stats: `近期收藏${firstBook.readingNumber}`, cover: firstBook.cover, wxBookId: firstBook.wxBookId, chapterId: firstBook.chapterId }] : [], bookList: restBooks.slice(0, 4).map(novel => ({ id: novel.id, title: novel.title, cover: novel.cover, wxBookId: novel.wxBookId, chapterId: novel.chapterId })), editorTitle: cardNovels[0].name // 设置实际的标题 }); } // 处理全网热推数据 if (cardNovels[1]) { this.setData({ hotBooks: cardNovels[1].novelList.map(novel => ({ id: novel.id, title: novel.title, desc: novel.brief, stats: `${novel.readingNumber}人看过`, cover: novel.cover, wxBookId: novel.wxBookId, chapterId: novel.chapterId })), hotTitle: cardNovels[1].name // 设置实际的标题 }); } // 处理强力推荐数据 if (cardNovels[2] && cardNovels[2].novelList.length > 0) { this.setData({ strongBooks: cardNovels[2].novelList.slice(0, 4).map(novel => ({ id: novel.id, title: novel.title, cover: novel.cover, wxBookId: novel.wxBookId, chapterId: novel.chapterId })), showStrongRecommend: true }); } else { // 如果没有第三组数据,隐藏强力推荐模块 this.setData({ strongBooks: [], showStrongRecommend: false }); } return cardNovels; } catch (error) { console.error('获取卡片小说失败:', error); wx.showToast({ title: '获取卡片小说失败', icon: 'none' }); return []; } }, // 处理banner点击 onBannerTap(e) { const banner = e.currentTarget.dataset.item; if (banner.linkUrl) { SendEvent('banner_click', { "banner_id": banner.id, "banner_title": banner.title, "uuid": app.globalData.uuid }); wx.navigateTo({ url: banner.linkUrl }); } }, })