| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599 |
- // pages/collect-video/video.js
- import {
- getCollectDetail,
- getTemplateConfig,
- getUuid,
- getCollectRealVideoUrl,
- getRecCollectList,
- } from "../../api/api";
- import { rnd, SendEvent, rndone, deepCopy } from "../../utils/util";
- import { apple } from "../../config/config";
- const app = getApp();
- let interstitialAd = null;
- Page({
- data: {
- loading: false,
- hasMore: true,
- // 状态栏高度
- statusBarHeight: 20,
- navHeight: 64, // 导航栏高度 = 状态栏 + 44
- navStyle: "",
- listStyle: "",
- ads: null,
- globalConfig: null,
- hasLoadAdConfig: false,
- templateAdId: "",
- adErrorField: {
- videoError: false,
- bannerError: false,
- templateError: false,
- },
- collectId: "", // 合集id
- tagId: "", // 合集标签id
- eps: [], // 合集视频列表
- playingEp: 0, // 正在播放集
- videoDetail: null,
- isPlaying: false,
- videoStatus: 1,
- duration: 0, // 视频总时长
- currentTime: 0, // 当前播放时间
- },
- async onLoad(options) {
- console.log("打开视频合集页面--------------------------");
- // wx.setStorageSync("jump", parseInt(options.jump)); // 是否跳转阅读器
- await this.autoLogin(options.promotionid);
- if (!app.globalData.uuid) {
- this.getUUID().then((uuid) => {
- // getApp().globalData.uuid = uuid
- console.log("登录成功");
- });
- }
- this.handleEntrace(options);
- this.setData({
- collectId: options.collectId,
- templateAdId: apple.ads.template2AdId,
- hasLoadAdConfig: true,
- });
- getTemplateConfig({
- box_type: 73,
- uuid: app.globalData.uuid,
- }).then((res) => {
- this.setData({
- globalConfig: res.globalConfig,
- });
- this.interstitalLoad();
- this.rewardVideoLoad();
- setTimeout(() => {
- this.interstitalPlayFn();
- }, 5000);
- // 获取合集视频详情
- this.getCollectVideoDetail();
- this.loadVideoList();
- });
- // 获取状态栏高度
- this.getSystemInfo();
- // this.handleEntrace(options);
- },
- // 自动登录
- async autoLogin(promotionid) {
- try {
- await getApp().login(promotionid);
- } catch (error) {
- console.error("登录失败:", error);
- }
- },
- onShow() {},
- handleEntrace(options) {
- // console.log("点击入口按钮");
- // if (!options || Object.keys(options).length === 0) {
- // return;
- // }
- // console.log("入口:", options);
- // try {
- // } catch (e) {
- // console.log("处理不同场景进入小程序出错", error);
- // }
- },
- clickBack() {
- wx.switchTab({
- url: "/pages/video/video",
- });
- },
- // 获取视频合集详情
- getCollectVideoDetail() {
- // 显示加载中提示
- wx.showLoading({
- title: "加载中...",
- mask: true,
- });
- getCollectDetail(this.data.collectId)
- .then((res) => {
- if (res && res.video.length > 0) {
- res.video
- .sort((a, b) => a.sort - b.sort)
- .map((e, i) => {
- // -------- 锁定判断 --------
- if (this.isCollectNeedLock()) {
- // set lock status
- if (i + 1 >= res.lockStart) {
- e.lock = true;
- } else {
- e.lock = false;
- }
- } else {
- e.lock = false;
- }
- return e;
- });
- console.log(res.video);
- this.setData({
- eps: res.video,
- tagId: res.tagId,
- playingEp: 0,
- videoDetail: res.video[0],
- });
- // 默认播放第一集
- this.getVideoPlayUrl();
- }
- })
- .catch((err) => {
- console.error(err);
- })
- .then(() => {
- wx.hideLoading();
- });
- },
- // 判断合集是否需要锁定
- isCollectNeedLock() {
- // 获取当前日期(格式:YYYY-MM-DD)
- const today = new Date().toISOString().split("T")[0];
- // 从 localStorage 获取数据
- const hadRewardNum = parseInt(
- wx.getStorageSync("had_reward_num") || "0",
- 10,
- );
- const unlockCollectIds = JSON.parse(
- wx.getStorageSync("unlock_collect_ids") || "[]",
- );
- const lastCheckDate = wx.getStorageSync("last_check_date");
- if (this.data.globalConfig.isShowReward === 1) {
- // 检查是否需要重置(新的一天)
- if (lastCheckDate !== today) {
- // 重置解锁数据
- wx.setStorageSync("had_reward_num", "0");
- wx.setStorageSync("unlock_collect_ids", "[]");
- wx.setStorageSync("last_check_date", today);
- return true; // 新的一天,当前视频未解锁
- }
- // 判断解锁状态
- // 1. 如果当天广告观看次数 >= 3,所有视频解锁
- if (hadRewardNum >= 3) {
- return false;
- }
- if (unlockCollectIds.includes(this.data.collectId)) {
- return false;
- }
- return true;
- } else {
- return false;
- }
- },
- async getVideoPlayUrl() {
- try {
- const res = await getCollectRealVideoUrl(this.data.videoDetail.url);
- this.setData({
- "videoDetail.playUrl": res.url_info[0].url,
- });
- setTimeout(() => {
- const videoContext = wx.createVideoContext("my-video");
- videoContext.play();
- }, 200);
- // 获取视频实例并播放
- } catch (error) {}
- },
- // 点击集
- clickEp(e) {
- const { ep, idx } = e.currentTarget.dataset;
- if (idx === this.data.playingEp) return;
- this.setData({
- playingEp: idx,
- videoDetail: ep,
- });
- SendEvent("click_collection_video", {
- cid: this.data.collectId,
- video_id: this.data.eps[this.data.playingEp].id,
- tag_id: this.data.tagId,
- });
- if (!this.data.videoDetail.lock) {
- this.getVideoPlayUrl();
- }
- },
- clickUnlock() {
- this.rewardVideoPlayFn();
- },
- /**
- * 获取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;
- 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`,
- });
- },
- // 加载视频列表
- async loadVideoList() {
- this.setData({
- loading: true,
- });
- try {
- const params = {
- tagIdList: this.data.globalConfig.tagIds.join(","),
- count: this.data.globalConfig.recommendListNum,
- id: Number(this.data.collectId),
- };
- const res = await getRecCollectList(params);
- res.forEach((e) => {
- e.adType = "video";
- e.views = rnd(1, 10);
- });
- this.setData({
- videoList: this.formatVideoAdList(deepCopy(res)),
- loading: false,
- hasMore: false,
- });
- } catch (error) {
- console.error("加载视频列表失败:", error);
- }
- },
- // 视频播放
- makeVideoPlay() {
- if (!this.data.videoDetail.lock && this.data.videoStatus == 2) {
- const videoContext = wx.createVideoContext("my-video");
- videoContext.play();
- }
- },
- // 视频暂停
- makeVideoPause() {
- if (this.data.videoStatus == 1) {
- const videoContext = wx.createVideoContext("my-video");
- videoContext.pause();
- }
- },
- // 视频播放事件
- onVideoPlay() {
- this.setData({
- isPlaying: true,
- videoStatus: 1,
- });
- // 可以添加播放埋点
- SendEvent("collection_video_play", {
- cid: this.data.collectId,
- video_id: this.data.eps[this.data.playingEp].id,
- tag_id: this.data.tagId,
- });
- },
- // 视频暂停事件
- onVideoPause() {
- this.setData({
- isPlaying: false,
- videoStatus: 2,
- });
- },
- // 视频播放结束事件
- onVideoEnd() {
- this.setData({
- isPlaying: false,
- videoStatus: 0,
- });
- const nextEp = this.data.playingEp + 1;
- // 最后一集播放完,随机播放下一个合集
- if (nextEp === this.data.eps.length && this.data.videoList.length > 0) {
- const rndCollect = rndone(this.data.videoList);
- this.setData({
- collectId: rndCollect.id,
- });
- this.getCollectVideoDetail();
- } else {
- // 切换下一集
- if (nextEp <= this.data.eps.length - 1) {
- this.setData({
- playingEp: nextEp,
- videoDetail: this.data.eps[nextEp],
- });
- if (!this.data.videoDetail.lock) {
- this.getVideoPlayUrl();
- }
- }
- }
- },
- // 视频时间更新事件
- onVideoUpdate(e) {
- const { currentTime, duration } = e.detail;
- this.setData({
- currentTime,
- duration,
- });
- },
- // 视频元数据加载完成
- onVideoLoaded(e) {
- console.log("视频元数据加载完成", e.detail);
- },
- /* ------------------ 广告相关 ----------------- */
- /**
- * 标记广告位置
- * @param {} arr
- * @returns
- */
- formatVideoAdList(arr) {
- // 原生广告间隔,激励广告间隔
- let templateGap = 9,
- 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 = [];
- // 辅助计算间隔变量
- 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;
- },
- // 点击合集
- clickCollect(e) {
- const { id, info, index } = e.currentTarget.dataset;
- const _this = this;
- this.setData({
- collectId: id,
- tagId: info.tagId,
- });
- SendEvent("click_collection", {
- cid: this.data.collectId,
- tag_id: this.data.tagId,
- });
- console.log(id, info, index, "合集详情");
- wx.redirectTo({
- url: `/pages/collect-video/video?collectId=${id}`,
- fail(err) {
- _this.getCollectVideoDetail();
- },
- });
- },
- // 分享给朋友
- onShareAppMessage(e) {},
- // 激励视频加载
- rewardVideoLoad() {
- if (this.data.globalConfig.isShowReward !== 1) return;
- if (wx.createRewardedVideoAd) {
- let adId = apple.ads.rewardAdId;
- this.videoAd = wx.createRewardedVideoAd({
- adUnitId: adId,
- });
- this.videoAd.onLoad(() => {
- console.log("首页激励加载成功");
- });
- this.videoAd.onError((err) => {
- console.log("首页激励失败", err);
- });
- this.videoAd.onClose((res) => {
- // 用户点击了【关闭广告】按钮
- if (res && res.isEnded) {
- // 发放奖励
- const hadRewardNum = parseInt(
- wx.getStorageSync("had_reward_num") || "0",
- 10,
- );
- const unlockCollectIds = JSON.parse(
- wx.getStorageSync("unlock_collect_ids") || "[]",
- );
- wx.setStorageSync("had_reward_num", hadRewardNum + 1);
- wx.setStorageSync(
- "unlock_collect_ids",
- JSON.stringify([...unlockCollectIds, this.data.collectId]),
- );
- // 解锁当前合集,播放视频
- this.data.eps = this.data.eps.map((e) => {
- e.lock = false;
- return e;
- });
- this.setData({
- "videoDetail.lock": false,
- eps: this.data.eps,
- });
- SendEvent("unlock_collection", {
- cid: this.data.collectId,
- video_id: this.data.eps[this.data.playingEp].id,
- // tag_id: this.data.tagId,
- ad_num: hadRewardNum + 1,
- });
- this.getVideoPlayUrl();
- } else {
- SendEvent("unlock_collection_fail", {
- cid: this.data.collectId,
- video_id: this.data.eps[this.data.playingEp].id,
- });
- }
- });
- }
- },
- // 激励视频展示
- rewardVideoPlayFn() {
- if (this.data.globalConfig.isShowReward !== 1) return;
- wx.showLoading({
- title: "解锁视频中",
- });
- this.videoAd
- .show()
- .then(() => {
- console.log("激励视频播放成功");
- })
- .catch((err) => {
- console.log("激励视频播放失败", err);
- })
- .then(() => {
- wx.hideLoading();
- });
- },
- // 插屏广告加载
- interstitalLoad() {
- if (this.data.globalConfig.isShowInsert !== 1) return;
- 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");
- this.makeVideoPlay();
- });
- },
- // 插屏广告展示
- interstitalPlayFn() {
- if (this.data.globalConfig.isShowInsert !== 1) return;
- if (interstitialAd) {
- interstitialAd
- .show()
- .then(() => {
- setTimeout(() => {
- this.makeVideoPause();
- }, 500);
- })
- .catch((err) => {
- console.error("合集视频页插屏显示错误", err);
- });
- }
- },
- });
|