// pages/video/video.js import { getVideoList, getTemplateConfig, getUuid, userLogin } from '../../api/api' import { rnd, deepCopy, goToBookDetail, goToVideoDetail, SendEvent } from '../../utils/util' import { apple } from '../../config/config' const app = getApp() let interstitialAd = null Page({ data: { videoList: [], originVideoList: [], loading: false, hasMore: true, page: 1, size: 10, // 状态栏高度 statusBarHeight: 20, navHeight: 64, // 导航栏高度 = 状态栏 + 44 navStyle: '', listStyle: '', // 添加防抖时间戳 lastLoadTime: 0, ads: null, globalConfig: null, // 视频分类列表 categoryList: [], // 当前选中的分类ID currentCategoryId: null, share_count: 1, hasLoadAdConfig: false, templateAdId: '', adErrorField: { videoError: false, bannerError: false, templateError: false }, }, onLoad(options) { console.log('打开视频页面--------------------------') wx.setStorageSync('jump', parseInt(options.jump)) // 是否跳转阅读器 if (!app.globalData.uuid) { this.getUUID().then(uuid => { // getApp().globalData.uuid = uuid console.log('登录成功') }) } this.handleEntrace(options); this.setData({ templateAdId: apple.ads.templateAdId, hasLoadAdConfig: true }) this.interstitalLoad() getTemplateConfig({ box_type: 67, uuid: app.globalData.uuid }).then(res => { this.setData({ globalConfig: res.globalConfig }); app.globalData.ads_config = res.globalConfig; // 获取视频分类 this.getVideoCategories() }) // 获取状态栏高度 this.getSystemInfo() // this.handleEntrace(options); }, onShow() { console.log('页面显示--------------------------') this.rewardVideoLoad() // 每次显示页面时刷新列表 if (this.data.videoList.length === 0) { this.setData({ page: 1 }) // this.loadVideoList() } // 获取当前页面的参数 const pages = getCurrentPages(); const currentPage = pages[pages.length - 1]; const options = currentPage.options; const jump = parseInt(options.jump); // 是否跳转阅读器 1-不跳转 const scene = wx.getStorageSync('scene'); console.log('scene场景值:', scene); console.log('jump阅读器:', jump); console.log('shared_video_id:', options.shared_video_id); console.log('share_count:', options.share_count); console.log('isEnterVideoDetail:', app.globalData.isEnterVideoDetail); if (options.shared_video_id) { // 处理分享进入的情况 if (!app.globalData.isEnterVideoDetail) { // 延迟跳转,确保列表页已经加载完成 setTimeout(() => { wx.navigateTo({ url: `/pages/video/detail?id=${options.shared_video_id}&title=${options.title || ''}&tag_id=${options.tag_id || ''}`, fail: (err) => { console.error('跳转到视频详情页失败:', err); wx.showToast({ title: '打开视频失败', icon: 'none' }); } }); }, 500); } else { // 第二次进入把isEnterVideoDetail恢复默认值 app.globalData.isEnterVideoDetail = true; } } // if (options.shared_video_id) { // if (+options.share_count === 1 && this.data.share_count === 1) { // this.setData({ // share_count: 2 // }); // console.log('share_count1:', this.data.share_count) // if (jump === 1) { // console.log('jump为1直接跳转到视频详情页') // // 延迟跳转 // setTimeout(() => { // this.goToVideoDetail(options.shared_video_id, options.tag_id) // }, 500); // } else { // if (scene === 1007 || scene === 1008) { // console.log('scene为1007或1008且jump不为1,跳转到书详情页') // this.goToBookDetail(); // } else { // console.log('scene不为1007,1008且jump不为1,跳转到视频详情页') // // 延迟跳转 // setTimeout(() => { // this.goToVideoDetail(options.shared_video_id, options.tag_id) // }, 500); // } // } // // if ((scene === 1007 || scene === 1008) && jump != 1) { // // this.goToBookDetail(); // // } else { // // this.goToVideoDetail(options.shared_video_id, options.tag_id); // // } // // this.goToBookDetail(); // } else if (+options.share_count === 1 && this.data.share_count === 2) { // this.setData({ // share_count: 3 // }); // console.log('share_count2:', this.data.share_count) // // 延迟跳转,确保列表页已经加载完成 // setTimeout(() => { // wx.navigateTo({ // url: `/pages/video/detail?id=${options.shared_video_id}&title=${options.title || ''}&tag_id=${options.tag_id || ''}`, // fail: (err) => { // console.error('跳转到视频详情页失败:', err); // wx.showToast({ // title: '打开视频失败', // icon: 'none' // }); // } // }); // }, 500); // } // } }, handleEntrace(options) { console.log('点击入口按钮') if (!options || Object.keys(options).length === 0) { return } console.log('入口:', options) try { let { type, jump, shared_video_id, tag_id } = options const scene = wx.getStorageSync('scene'); console.log('入口:', type, jump, scene, shared_video_id) if ((type === 'share' || type === 'tuiguang') && shared_video_id) { if (jump === "1") { console.log('jump为1直接跳转到视频详情页') // 延迟跳转,确保列表页已经加载完成 setTimeout(() => { this.goToVideoDetail(shared_video_id, tag_id) }, 500); } else { if (scene === 1007 || scene === 1008) { console.log('scene为1007或1008且jump不为1,跳转到书详情页') // 延迟跳转,确保列表页已经加载完成 setTimeout(() => { this.goToBookDetail() }, 500); } else { console.log('scene不为1007,1008且jump不为1,跳转到视频详情页') // 延迟跳转,确保列表页已经加载完成 setTimeout(() => { this.goToVideoDetail(shared_video_id, tag_id) }, 500); } } } } catch (e) { console.log('处理不同场景进入小程序出错', error) } }, onTabItemTap(item) { console.log(item.index) setTimeout(() => { this.interstitalPlayFn() }, 1000) }, // 插屏广告加载 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) }) } }, /** * 获取uuid */ getUUID() { return new Promise((resolve, reject) => { wx.login({ success: res => { console.log('wxlogin:', res); let body = { code: res.code, source_type: 1, source_id: '' } getUuid(body).then(async uuidres => { console.log('登录成功:', uuidres); app.globalData.uuid = uuidres.uuid; app.globalData.openId = uuidres.open_id; // 直接从视频链接进入,同时登录IAA小说用户 // userLogin({ // "appid": apple.appid, // "channel": 1, // "srcType": "0", // "srcAppId": "", // "srcId": "", // "cusId": "", // "inviter": "", // "promotionId": "", // "inviterPromotionId": "", // "system": "pc", // "type": "inner", // "inner": 1, // code: res.code, // }).then(logres => { // console.log('userLogin', logres); // wx.setStorageSync('accessToken', logres.accessToken); // app.globalData.isLogin = true; // app.globalData.userCode = logres.userCode; // app.globalData.openId = logres.openId; // app.globalData.unionId = logres.unionId; // console.log('登录成功', app.globalData) // resolve(logres); // }).catch(err => { // app.globalData.isLogin = false; // reject(err); // }) console.log('登录后的openid:', uuidres.open_id) console.log('登录成功:', app.globalData) SendEvent('login_shanhu', { "uuid": uuidres.uuid }); resolve(res.uuid) }).catch((err) => { reject(err) }) } }) }) }, // 获取系统信息 getSystemInfo() { const systemInfo = wx.getSystemInfoSync() const statusBarHeight = systemInfo.statusBarHeight const navHeight = statusBarHeight + 44 this.setData({ statusBarHeight: statusBarHeight, navHeight: navHeight, navStyle: `height:${navHeight}px`, listStyle: `top:${navHeight}px` }) }, // 获取视频分类 getVideoCategories() { console.log('getVideoCategories', this.data.globalConfig) // 筛选出type=1的视频分类 const videoCategories = this.data.globalConfig.categoryList.filter(item => item.type === 1) console.log('videoCategories', videoCategories) if (videoCategories.length > 0) { // 设置分类列表和默认选中的分类 this.setData({ categoryList: videoCategories, currentCategoryId: videoCategories[0].id }) // 加载第一个分类的视频列表 this.loadVideoList() } else { console.error('未找到视频分类') wx.showToast({ title: '未找到视频分类', icon: 'none' }) } }, // 切换分类 switchCategory(e) { const categoryId = e.currentTarget.dataset.id if (categoryId === this.data.currentCategoryId) return this.setData({ currentCategoryId: categoryId, page: 1, videoList: [], originVideoList: [], hasMore: true }) this.loadVideoList() }, // 加载视频列表 async loadVideoList() { if (this.data.loading) return this.setData({ loading: true }) try { const params = { page: this.data.page, size: this.data.size, tag_id: this.data.currentCategoryId, // 如果不是第一页,传递最后一个视频的ID作为next_id next_id: this.data.page > 1 && this.data.videoList.length > 0 ? this.data.videoList[this.data.videoList.length - 1].id : "" } let videoList = [] try { videoList = await getVideoList(params) if (!Array.isArray(videoList)) { throw new Error('返回数据格式错误') } videoList = videoList.map(item => ({ ...item, views: rnd(1, 10), favors: rnd(5000, 10000), adType: "video", lock: false })) this.data.originVideoList = this.data.originVideoList.concat(videoList) this.data.videoList = this.formatVideoAdList(deepCopy(this.data.originVideoList)) } catch (apiError) { console.error('API调用失败:', apiError) throw apiError } // 如果是第一页,直接替换数据 if (this.data.page === 1) { this.setData({ videoList: this.data.videoList, originVideoList: this.data.originVideoList, loading: false, hasMore: videoList.length >= this.data.size }) } else { // 否则追加数据 this.setData({ videoList: this.data.videoList, originVideoList: this.data.originVideoList, loading: false, hasMore: videoList.length >= this.data.size }) } } catch (error) { console.error('加载视频列表失败:', error) } }, /* ------------------ 广告相关 ----------------- */ /** * 标记广告位置 * @param {} arr * @returns */ formatVideoAdList(arr) { // 原生广告间隔,激励广告间隔 let templateGap = 0, rewardGap = 0 console.log(this.data.globalConfig) if (this.data.globalConfig.isHomeTemplateAd === 1) { templateGap = this.data.globalConfig.homeTemplateAdInterval } else { templateGap = 0 } if (this.data.globalConfig.isHomeRewardAd) { rewardGap = this.data.globalConfig.homeRewardAdInterval } else { rewardGap = 0 } console.log('原生间隔templateGap', templateGap, '激励间隔rewardGap', rewardGap) // 第二个固定是原生广告 let result = [arr.shift(), { adType: 'templateAd' }] // 辅助计算间隔变量 let markIndex = 0 let templateAdFlag = true let rewardAdFlag = true do { markIndex += 1 if (templateGap > 0) { if (templateAdFlag && markIndex - 1 === templateGap) { markIndex = 0 result.push({ adType: "templateAd" }) templateAdFlag = false rewardAdFlag = true continue } } else { rewardAdFlag = true } if (rewardGap > 0) { if (rewardAdFlag && markIndex - 1 === rewardGap) { markIndex = 0 templateAdFlag = true rewardAdFlag = false let rewardItem = arr.shift() rewardItem.lock = true result.push(rewardItem) console.log("标记激励项:", rewardItem) continue } } else { templateAdFlag = true } result.push(arr.shift()) } while (arr.length > 0); return result; }, // 加载更多 loadMore() { console.log("触发loadMore") console.log("当前状态:", { loading: this.data.loading, hasMore: this.data.hasMore, page: this.data.page, videoListLength: this.data.videoList.length }) // 添加防抖,避免频繁触发 const now = Date.now() if (now - this.data.lastLoadTime < 500) { console.log("防抖触发,跳过本次加载") return } if (this.data.hasMore && !this.data.loading) { console.log("开始加载更多数据") this.setData({ page: this.data.page + 1, lastLoadTime: now }) this.loadVideoList() } else { console.log("不满足加载条件:", { hasMore: this.data.hasMore, loading: this.data.loading }) } }, // 刷新列表 refreshList() { wx.showLoading({ title: '刷新中...', }) this.setData({ page: 1, videoList: [], hasMore: true }) this.loadVideoList().then(() => { wx.hideLoading() wx.showToast({ title: '刷新成功', icon: 'success', duration: 1500 }) }).catch(() => { wx.hideLoading() }) }, // 点击视频 onVideoTap(e) { const { id, info, index } = e.currentTarget.dataset; console.log(id, info, index, '视频详情') if (!info) { wx.hideLoading(); wx.showToast({ title: '视频数据错误', icon: 'none' }); return; } SendEvent('click_video_tab_video', { "video_id": id, "tag_id": info.tag_ids[0], "uuid": app.globalData.uuid }) const encodedTitle = encodeURIComponent(info.title || ''); this.unlockUrl = `/pages/video/detail?id=${id}&title=${encodedTitle}&tag_id=${info.tag_ids[0]}` if (!info.lock) { // 显示加载中提示 wx.showLoading({ title: '加载中...', mask: true }); // 跳转到视频详情页 wx.navigateTo({ url: this.unlockUrl, success: () => { wx.hideLoading(); }, fail: (err) => { console.error('跳转失败:', err); wx.hideLoading(); wx.showToast({ title: '跳转失败', icon: 'none' }); } }); } else { this.reawrdVideoIndex = index this.rewardVideo = info this.rewardVideoPlayFn() } }, // 下拉刷新 onPullDownRefresh() { this.setData({ page: 1, videoList: [] }) this.loadVideoList().then(() => { wx.stopPullDownRefresh() }) }, // 分享按钮点击事件 onShareTap(e) { // 阻止事件冒泡 e.stopPropagation(); // SendEvent('click_list_share', {"video_id": video.id, "tag_id": video.tag_ids[0]}); }, // 分享给朋友 onShareAppMessage(e) { const video = e.target.dataset.video if (!video) return {} const jump = wx.getStorageSync('jump');// 是否跳转阅读器 let url = ''; url = `/pages/video/video?shared_video_id=${video.id}&title=${encodeURIComponent(video.title)}&tag_id=${video.tag_ids[0]}&share_count=1`; if (jump === 1) { url += '&jump=1'; } SendEvent('click_list_share', { "video_id": video.id, "tag_id": video.tag_ids[0], "uuid": app.globalData.uuid }); return { title: video.title, path: url, imageUrl: video.cover_image, success: function (res) { wx.showToast({ title: '分享成功', icon: 'success', duration: 1500 }) }, fail: function (res) { wx.showToast({ title: '分享失败', icon: 'none', duration: 1500 }) } } }, // 分享到朋友圈 onShareTimeline(e) { const video = e.target.dataset.video if (!video) return {} const jump = wx.getStorageSync('jump');// 是否跳转阅读器 let url = ''; url = `shared_video_id=${video.id}&title=${encodeURIComponent(video.title)}&tag_id=${video.tag_ids[0]}&share_count=1`; SendEvent('click_list_share', { "video_id": video.id, "tag_id": video.tag_ids[0], "uuid": app.globalData.uuid }); if (jump === 1) { url += '&jump=1'; } return { title: video.title, query: url, imageUrl: video.cover_image } }, // 跳转到书籍详情 goToBookDetail() { getApp().globalData.isShowDialog = true // 使用公共的goToBookDetail函数 goToBookDetail({ bookId: 7266, wxBookId: 'A1Hcfv456vGtMYxQjxUm8KNdJ8', chapterId: null }); }, // 跳转视频详情 goToVideoDetail(videoId, tagId) { // 使用公共的goToVideoDetail函数 goToVideoDetail({ videoId: videoId, tagId: tagId }); }, // 激励视频加载 rewardVideoLoad() { if (wx.createRewardedVideoAd) { let adId = apple.ads.rewardAdId let that = this this.videoAd = wx.createRewardedVideoAd({ adUnitId: adId }) this.videoAd.onLoad(() => { console.log('首页激励加载成功') }) this.videoAd.onError((err) => { console.log('首页激励失败', err) }) this.videoAd.onClose((res) => { // 用户点击了【关闭广告】按钮 this.setData({ isLoadingVideo: false }) if (res && res.isEnded) { // 发放奖励 that.setData({ [`videoList[${that.reawrdVideoIndex}].lock`]: false }) console.log('发放奖励跳转') wx.navigateTo({ url: `${that.unlockUrl}` }) } }) } }, // 激励视频展示 rewardVideoPlayFn() { wx.showLoading({ title: '解锁视频中', }) this.videoAd.show().then(() => { console.log('激励视频播放成功') }).catch((err) => { console.log('激励视频播放失败', err) this.setData({ [`videoList[${that.reawrdVideoIndex}].lock`]: false }) wx.navigateTo({ url: `${this.unlockUrl}` }) }).then(() => { wx.hideLoading() }) }, // 统一小程序广告加载成功 appletsAdLoad(e) { let _target = e.currentTarget.dataset this.setData({ [`adErrorField.${_target.field}`]: false }) }, // 统一小程序广告加载失败 appletsAdError(e) { let _target = e.currentTarget.dataset this.setData({ [`adErrorField.${_target.field}`]: true }) console.error(_target.name, '错误', e) }, // 统一小程序广告关闭 appletsAdClose(e) { let _target = e.currentTarget.dataset }, // 统一小程序广告点击 appletsAdClick(e) { let _target = e.currentTarget.dataset }, })