video.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. // pages/video/video.js
  2. import { getVideoList, getTemplateConfig, getUuid } from '../../api/api'
  3. import { rnd, deepCopy, goToBookDetail } from '../../utils/util'
  4. const app = getApp()
  5. Page({
  6. data: {
  7. videoList: [],
  8. loading: false,
  9. hasMore: true,
  10. page: 1,
  11. size: 10,
  12. // 状态栏高度
  13. statusBarHeight: 20,
  14. navHeight: 64, // 导航栏高度 = 状态栏 + 44
  15. navStyle: '',
  16. listStyle: '',
  17. // 添加防抖时间戳
  18. lastLoadTime: 0,
  19. ads: null,
  20. globalConfig: null,
  21. // 视频分类列表
  22. categoryList: [],
  23. // 当前选中的分类ID
  24. currentCategoryId: null,
  25. share_count: 1
  26. },
  27. async onLoad() {
  28. console.log('打开视频页面--------------------------')
  29. if (!getApp().globalData.uuid) {
  30. await this.getUUID().then(uuid => {
  31. getApp().globalData.uuid = uuid
  32. })
  33. }
  34. getTemplateConfig({
  35. box_type: 67,
  36. uuid: getApp().globalData.uuid
  37. }).then(res => {
  38. this.setData({
  39. globalConfig: res.globalConfig
  40. })
  41. // 获取视频分类
  42. this.getVideoCategories()
  43. })
  44. // 获取状态栏高度
  45. this.getSystemInfo()
  46. },
  47. onShow() {
  48. console.log('页面显示--------------------------')
  49. // 每次显示页面时刷新列表
  50. if (this.data.videoList.length === 0) {
  51. this.setData({
  52. page: 1
  53. })
  54. // this.loadVideoList()
  55. }
  56. // 获取当前页面的参数
  57. const pages = getCurrentPages();
  58. const currentPage = pages[pages.length - 1];
  59. const options = currentPage.options;
  60. // 处理分享进入的情况
  61. if (options.shared_video_id) {
  62. if (+options.share_count === 1 && this.data.share_count === 1) {
  63. this.setData({
  64. share_count: 2
  65. })
  66. this.goToBookDetail()
  67. } else if (+options.share_count === 1 && this.data.share_count === 2) {
  68. this.setData({
  69. share_count: 3
  70. })
  71. // 延迟跳转,确保列表页已经加载完成
  72. setTimeout(() => {
  73. wx.navigateTo({
  74. url: `/pages/video/detail?id=${options.shared_video_id}&title=${options.title || ''}&tag_id=${options.tag_id || ''}`,
  75. fail: (err) => {
  76. console.error('跳转到视频详情页失败:', err);
  77. wx.showToast({
  78. title: '打开视频失败',
  79. icon: 'none'
  80. });
  81. }
  82. });
  83. }, 500);
  84. }
  85. }
  86. },
  87. /**
  88. * 获取uuid
  89. */
  90. getUUID() {
  91. return new Promise((resolve, reject) => {
  92. wx.login({
  93. success: res => {
  94. let body = {
  95. code: res.code,
  96. source_type: 1,
  97. source_id: ''
  98. }
  99. getUuid(body).then(async res => {
  100. resolve(res.uuid)
  101. }).catch((err) => {
  102. reject(err)
  103. })
  104. }
  105. })
  106. })
  107. },
  108. // 获取系统信息
  109. getSystemInfo() {
  110. const systemInfo = wx.getSystemInfoSync()
  111. const statusBarHeight = systemInfo.statusBarHeight
  112. const navHeight = statusBarHeight + 44
  113. this.setData({
  114. statusBarHeight: statusBarHeight,
  115. navHeight: navHeight,
  116. navStyle: `height:${navHeight}px`,
  117. listStyle: `top:${navHeight}px`
  118. })
  119. },
  120. // 获取视频分类
  121. getVideoCategories() {
  122. console.log('getVideoCategories', this.data.globalConfig)
  123. // 筛选出type=1的视频分类
  124. const videoCategories = this.data.globalConfig.categoryList.filter(item => item.type === 1)
  125. console.log('videoCategories',videoCategories)
  126. if (videoCategories.length > 0) {
  127. // 设置分类列表和默认选中的分类
  128. this.setData({
  129. categoryList: videoCategories,
  130. currentCategoryId: videoCategories[0].id
  131. })
  132. // 加载第一个分类的视频列表
  133. this.loadVideoList()
  134. } else {
  135. console.error('未找到视频分类')
  136. wx.showToast({
  137. title: '未找到视频分类',
  138. icon: 'none'
  139. })
  140. }
  141. },
  142. // 切换分类
  143. switchCategory(e) {
  144. const categoryId = e.currentTarget.dataset.id
  145. if (categoryId === this.data.currentCategoryId) return
  146. this.setData({
  147. currentCategoryId: categoryId,
  148. page: 1,
  149. videoList: [],
  150. hasMore: true
  151. })
  152. this.loadVideoList()
  153. },
  154. // 加载视频列表
  155. async loadVideoList() {
  156. if (this.data.loading) return
  157. this.setData({ loading: true })
  158. try {
  159. const params = {
  160. page: this.data.page,
  161. size: this.data.size,
  162. tag_id: this.data.currentCategoryId,
  163. // 如果不是第一页,传递最后一个视频的ID作为next_id
  164. next_id: this.data.page > 1 && this.data.videoList.length > 0
  165. ? this.data.videoList[this.data.videoList.length - 1].id
  166. : ""
  167. }
  168. let videoList = []
  169. try {
  170. videoList = await getVideoList(params)
  171. if (!Array.isArray(videoList)) {
  172. throw new Error('返回数据格式错误')
  173. }
  174. videoList = videoList.map(item => ({
  175. ...item,
  176. views: rnd(1, 10),
  177. favors: rnd(5000, 10000),
  178. adType: "video"
  179. }))
  180. videoList = this.formatVideoAdList(videoList);
  181. console.log("format videoList",videoList)
  182. } catch (apiError) {
  183. console.error('API调用失败:', apiError)
  184. throw apiError
  185. }
  186. // 如果是第一页,直接替换数据
  187. if (this.data.page === 1) {
  188. this.setData({
  189. videoList: videoList,
  190. loading: false,
  191. hasMore: videoList.length >= this.data.size
  192. })
  193. } else {
  194. // 否则追加数据
  195. this.setData({
  196. videoList: [...this.data.videoList, ...videoList],
  197. loading: false,
  198. hasMore: videoList.length >= this.data.size
  199. })
  200. }
  201. } catch (error) {
  202. console.error('加载视频列表失败:', error)
  203. }
  204. },
  205. /* ------------------ 广告相关 ----------------- */
  206. /**
  207. * 标记广告位置
  208. * @param {} arr
  209. * @returns
  210. */
  211. formatVideoAdList(arr) {
  212. // 原生广告间隔,激励广告间隔
  213. let templateGap = 0, rewardGap = 0
  214. // 第二个固定是原生广告
  215. let result = [arr.shift(), {
  216. adType: 'templateAd'
  217. }]
  218. // 辅助计算间隔变量
  219. let markIndex = 0
  220. let templateAdFlag = true
  221. let rewardAdFlag = true
  222. do {
  223. markIndex += 1
  224. if (templateGap > 0) {
  225. if (templateAdFlag && markIndex - 1 === templateGap) {
  226. markIndex = 0
  227. result.push({
  228. adType: "templateAd"
  229. })
  230. templateAdFlag = false
  231. rewardAdFlag = true
  232. continue
  233. }
  234. } else {
  235. rewardAdFlag = true
  236. }
  237. if (rewardGap > 0) {
  238. if (rewardAdFlag && markIndex - 1 === rewardGap) {
  239. markIndex = 0
  240. templateAdFlag = true
  241. rewardAdFlag = false
  242. let rewardItem = arr.shift()
  243. rewardItem.lock = true
  244. result.push(rewardItem)
  245. continue
  246. }
  247. } else {
  248. templateAdFlag = true
  249. }
  250. result.push(arr.shift())
  251. } while (arr.length > 0);
  252. return result;
  253. },
  254. // 加载更多
  255. loadMore() {
  256. console.log("触发loadMore")
  257. console.log("当前状态:", {
  258. loading: this.data.loading,
  259. hasMore: this.data.hasMore,
  260. page: this.data.page,
  261. videoListLength: this.data.videoList.length
  262. })
  263. // 添加防抖,避免频繁触发
  264. const now = Date.now()
  265. if (now - this.data.lastLoadTime < 500) {
  266. console.log("防抖触发,跳过本次加载")
  267. return
  268. }
  269. if (this.data.hasMore && !this.data.loading) {
  270. console.log("开始加载更多数据")
  271. this.setData({
  272. page: this.data.page + 1,
  273. lastLoadTime: now
  274. })
  275. this.loadVideoList()
  276. } else {
  277. console.log("不满足加载条件:", {
  278. hasMore: this.data.hasMore,
  279. loading: this.data.loading
  280. })
  281. }
  282. },
  283. // 刷新列表
  284. refreshList() {
  285. wx.showLoading({
  286. title: '刷新中...',
  287. })
  288. this.setData({
  289. page: 1,
  290. videoList: [],
  291. hasMore: true
  292. })
  293. this.loadVideoList().then(() => {
  294. wx.hideLoading()
  295. wx.showToast({
  296. title: '刷新成功',
  297. icon: 'success',
  298. duration: 1500
  299. })
  300. }).catch(() => {
  301. wx.hideLoading()
  302. })
  303. },
  304. // 点击视频
  305. onVideoTap(e) {
  306. const videoId = e.currentTarget.dataset.id;
  307. // 显示加载中提示
  308. wx.showLoading({
  309. title: '加载中...',
  310. mask: true
  311. });
  312. // 获取当前点击的视频项
  313. const video = this.data.videoList.find(item => item.id === videoId);
  314. // 确保视频对象存在
  315. if (!video) {
  316. wx.hideLoading();
  317. wx.showToast({
  318. title: '视频数据错误',
  319. icon: 'none'
  320. });
  321. return;
  322. }
  323. // 将标题进行URI编码处理(避免特殊字符导致的问题)
  324. const encodedTitle = encodeURIComponent(video.title || '');
  325. // 跳转到视频详情页
  326. wx.navigateTo({
  327. url: `/pages/video/detail?id=${videoId}&title=${encodedTitle}&tag_id=${e.currentTarget.dataset.info.tag_ids[0]}`,
  328. success: () => {
  329. wx.hideLoading();
  330. },
  331. fail: (err) => {
  332. console.error('跳转失败:', err);
  333. wx.hideLoading();
  334. wx.showToast({
  335. title: '跳转失败',
  336. icon: 'none'
  337. });
  338. }
  339. });
  340. },
  341. // 下拉刷新
  342. onPullDownRefresh() {
  343. this.setData({
  344. page: 1,
  345. videoList: []
  346. })
  347. this.loadVideoList().then(() => {
  348. wx.stopPullDownRefresh()
  349. })
  350. },
  351. // 分享按钮点击事件
  352. onShareTap(e) {
  353. // 阻止事件冒泡
  354. e.stopPropagation();
  355. },
  356. // 分享给朋友
  357. onShareAppMessage(e) {
  358. const video = e.target.dataset.video
  359. if (!video) return {}
  360. return {
  361. title: video.title,
  362. path: `/pages/video/video?shared_video_id=${video.id}&title=${encodeURIComponent(video.title)}&tag_id=${video.tag_ids[0]}&share_count=1`,
  363. imageUrl: video.cover_image,
  364. success: function(res) {
  365. wx.showToast({
  366. title: '分享成功',
  367. icon: 'success',
  368. duration: 1500
  369. })
  370. },
  371. fail: function(res) {
  372. wx.showToast({
  373. title: '分享失败',
  374. icon: 'none',
  375. duration: 1500
  376. })
  377. }
  378. }
  379. },
  380. // 分享到朋友圈
  381. onShareTimeline(e) {
  382. const video = e.target.dataset.video
  383. if (!video) return {}
  384. return {
  385. title: video.title,
  386. query: `shared_video_id=${video.id}&title=${encodeURIComponent(video.title)}&tag_id=${video.tag_ids[0]}&share_count=1`,
  387. imageUrl: video.cover_image
  388. }
  389. },
  390. // 跳转到书籍详情
  391. goToBookDetail() {
  392. getApp().globalData.isShowDialog = true
  393. // 使用公共的goToBookDetail函数
  394. goToBookDetail({
  395. bookId: 7266,
  396. wxBookId: 'A1Hcfv456vGtMYxQjxUm8KNdJ8',
  397. chapterId: null
  398. });
  399. }
  400. })