// pages/video/video.js import { getVideoList, getTemplateConfig, getUuid } from "../../api/api"; import { rnd, deepCopy, goToBookDetail, goToVideoDetail, SendEvent, rndone, } 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)); // 是否跳转阅读器 this.autoLogin(options.promotionid); 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); }, // 自动登录 async autoLogin(promotionid) { try { await getApp().login(promotionid); } catch (error) { console.error("登录失败:", error); } }, onShow() { console.log("页面显示--------------------------"); this.rewardVideoLoad(); // 每次显示页面时刷新列表 if (this.data.videoList.length === 0) { this.setData({ page: 1, }); } }, handleEntrace(options) { console.log("点击入口按钮"); if (!options || Object.keys(options).length === 0) { return; } console.log("入口:", options); try { let { type, jump, shared_video_id, tag_id, collectId, tid } = options; const scene = wx.getStorageSync("scene"); console.log("入口:", type, jump, scene, shared_video_id); if ((type === "share" || type === "tuiguang") && shared_video_id) { SendEvent("enter_wxwork_material", { materialId: shared_video_id, type: "video", tag_id: tag_id, task_id: tid, }); 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( `&shared_video_id=${shared_video_id}&tag_id=${tag_id}`, ); }, 500); } else { console.log("scene不为1007,1008且jump不为1,跳转到视频详情页"); // 延迟跳转,确保列表页已经加载完成 setTimeout(() => { this.goToVideoDetail(shared_video_id, tag_id); }, 500); } } } if ((type === "share" || type === "tuiguang") && collectId) { if (scene === 1007 || scene === 1008) { console.log("scene为1007或1008,跳转到书详情页"); // 延迟跳转,确保列表页已经加载完成 //跳转合集视频 setTimeout(() => { this.goToBookDetail(`&collectId=${collectId}`); }, 500); } else { wx.navigateTo({ url: "/pages/collect-video/video?collectId=" + collectId, }); } } } 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(query) { getApp().globalData.isShowDialog = true; // 使用公共的goToBookDetail函数 const rndBook = rndone(apple.bookList); goToBookDetail( { bookId: rndBook.bookId, wxBookId: rndBook.wxBookId, chapterId: rndBook.chapterId, }, query, ); }, // 跳转视频详情 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, }); SendEvent("rewardad_finish", { video_id: that.rewardVideo.id, tag_id: that.rewardVideo.tag_ids[0], }); 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; }, });