| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452 |
- // pages/video/video.js
- import { getVideoList, getTemplateConfig, getUuid } from '../../api/api'
- import { rnd, deepCopy, goToBookDetail } from '../../utils/util'
- const app = getApp()
- Page({
- data: {
- videoList: [],
- 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
- },
- async onLoad() {
- console.log('打开视频页面--------------------------')
- if (!getApp().globalData.uuid) {
- await this.getUUID().then(uuid => {
- getApp().globalData.uuid = uuid
- })
- }
- getTemplateConfig({
- box_type: 67,
- uuid: getApp().globalData.uuid
- }).then(res => {
- this.setData({
- globalConfig: res.globalConfig
- })
- // 获取视频分类
- this.getVideoCategories()
- })
- // 获取状态栏高度
- this.getSystemInfo()
- },
- onShow() {
- console.log('页面显示--------------------------')
- // 每次显示页面时刷新列表
- 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;
- // 处理分享进入的情况
- if (options.shared_video_id) {
- if (+options.share_count === 1 && this.data.share_count === 1) {
- this.setData({
- share_count: 2
- })
- this.goToBookDetail()
- } else if (+options.share_count === 1 && this.data.share_count === 2) {
- this.setData({
- share_count: 3
- })
- // 延迟跳转,确保列表页已经加载完成
- 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);
- }
- }
- },
- /**
- * 获取uuid
- */
- getUUID() {
- return new Promise((resolve, reject) => {
- wx.login({
- success: res => {
- let body = {
- code: res.code,
- source_type: 1,
- source_id: ''
- }
- getUuid(body).then(async res => {
- 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: [],
- 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"
- }))
- videoList = this.formatVideoAdList(videoList);
- console.log("format videoList",videoList)
- } catch (apiError) {
- console.error('API调用失败:', apiError)
- throw apiError
- }
- // 如果是第一页,直接替换数据
- if (this.data.page === 1) {
- this.setData({
- videoList: videoList,
- loading: false,
- hasMore: videoList.length >= this.data.size
- })
- } else {
- // 否则追加数据
- this.setData({
- videoList: [...this.data.videoList, ...videoList],
- loading: false,
- hasMore: videoList.length >= this.data.size
- })
- }
- } catch (error) {
- console.error('加载视频列表失败:', error)
- }
- },
- /* ------------------ 广告相关 ----------------- */
- /**
- * 标记广告位置
- * @param {} arr
- * @returns
- */
- formatVideoAdList(arr) {
- // 原生广告间隔,激励广告间隔
- let templateGap = 0, rewardGap = 0
- // 第二个固定是原生广告
- 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)
- 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 videoId = e.currentTarget.dataset.id;
- // 显示加载中提示
- wx.showLoading({
- title: '加载中...',
- mask: true
- });
- // 获取当前点击的视频项
- const video = this.data.videoList.find(item => item.id === videoId);
- // 确保视频对象存在
- if (!video) {
- wx.hideLoading();
- wx.showToast({
- title: '视频数据错误',
- icon: 'none'
- });
- return;
- }
- // 将标题进行URI编码处理(避免特殊字符导致的问题)
- const encodedTitle = encodeURIComponent(video.title || '');
- // 跳转到视频详情页
- wx.navigateTo({
- url: `/pages/video/detail?id=${videoId}&title=${encodedTitle}&tag_id=${e.currentTarget.dataset.info.tag_ids[0]}`,
- success: () => {
- wx.hideLoading();
- },
- fail: (err) => {
- console.error('跳转失败:', err);
- wx.hideLoading();
- wx.showToast({
- title: '跳转失败',
- icon: 'none'
- });
- }
- });
- },
- // 下拉刷新
- onPullDownRefresh() {
- this.setData({
- page: 1,
- videoList: []
- })
- this.loadVideoList().then(() => {
- wx.stopPullDownRefresh()
- })
- },
- // 分享按钮点击事件
- onShareTap(e) {
- // 阻止事件冒泡
- e.stopPropagation();
- },
- // 分享给朋友
- onShareAppMessage(e) {
- const video = e.target.dataset.video
- if (!video) return {}
-
- return {
- title: video.title,
- path: `/pages/video/video?shared_video_id=${video.id}&title=${encodeURIComponent(video.title)}&tag_id=${video.tag_ids[0]}&share_count=1`,
- 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 {}
-
- return {
- title: video.title,
- query: `shared_video_id=${video.id}&title=${encodeURIComponent(video.title)}&tag_id=${video.tag_ids[0]}&share_count=1`,
- imageUrl: video.cover_image
- }
- },
- // 跳转到书籍详情
- goToBookDetail() {
- getApp().globalData.isShowDialog = true
- // 使用公共的goToBookDetail函数
- goToBookDetail({
- bookId: 7266,
- wxBookId: 'A1Hcfv456vGtMYxQjxUm8KNdJ8',
- chapterId: null
- });
- }
- })
|