details.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. // subpackagestow/details/details.js
  2. // import { models, db, _ } from '../../utils/cloudbase.js'
  3. import { getDB, getModels, getCommand, getTempFileURLs, getClient } from '../../utils/cloudbase.js'
  4. Page({
  5. /**
  6. * 页面的初始数据
  7. */
  8. data: {
  9. fileType: 'video',
  10. viewType: 'grid',
  11. courseList: [],
  12. shouchang: '',
  13. show_1: '',
  14. xiazi: '',
  15. xia: '',
  16. itemlist: {},
  17. isCollected: false,
  18. isPlaying: false,
  19. isAudioPlaying: false,
  20. },
  21. async onLoad(options) {
  22. // 获取传递过来的数据
  23. const itemStr = decodeURIComponent(options.item);
  24. const item = JSON.parse(itemStr);
  25. // 格式化时间
  26. item.createdAtText = this.formatTime(item.createdAt);
  27. // 判断 url 字段是否存在且是 cloud://
  28. if (item.url && item.url.length > 0) {
  29. try {
  30. // 只转换 cloud:// 格式的
  31. const cloudUrls = item.url.filter(u => u.startsWith('cloud://'));
  32. if (cloudUrls.length > 0) {
  33. const fileList = await getTempFileURLs(cloudUrls);
  34. // 按顺序替换成 http 链接
  35. fileList.forEach((f, i) => {
  36. if (f.tempFileURL) {
  37. const idx = item.url.indexOf(cloudUrls[i]);
  38. if (idx !== -1) {
  39. item.url[idx] = f.tempFileURL;
  40. }
  41. }
  42. });
  43. }
  44. } catch (err) {
  45. console.error('url 转换失败', err);
  46. }
  47. }
  48. // // 设置到页面数据中
  49. // this.setData({
  50. // itemlist: item
  51. // }, () => {
  52. // // 转换云文件ID为临时链接
  53. // if (item.url && item.url.length > 0) {
  54. // wx.cloud.getTempFileURL({
  55. // fileList: [item.url[0]],
  56. // success: res => {
  57. // if (res.fileList && res.fileList.length > 0) {
  58. // this.setData({
  59. // 'itemlist.playUrl': res.fileList[0].tempFileURL
  60. // });
  61. // }
  62. // },
  63. // fail: err => {
  64. // console.error('获取临时链接失败', err);
  65. // }
  66. // });
  67. // }
  68. this.setData({ itemlist: item })
  69. // 转换云文件ID为临时链接
  70. if (item.url && item.url.length > 0) {
  71. try {
  72. const tempFiles = await getTempFileURLs([item.url[0]])
  73. this.setData({ 'itemlist.playUrl': tempFiles[0].tempFileURL })
  74. } catch (err) {
  75. console.error('获取临时链接失败', err)
  76. }
  77. }
  78. // 相关推荐
  79. this.getcourseList()
  80. // });
  81. // 获取图片
  82. const fileIDs = [
  83. 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/shouchang.png',
  84. 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/show_1.png',
  85. 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xiazi.png',
  86. 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xia_1.png'
  87. ];
  88. const fileList = await getTempFileURLs(fileIDs)
  89. this.setData({
  90. shouchang: fileList[0].tempFileURL,
  91. show_1: fileList[1].tempFileURL,
  92. xiazi: fileList[2].tempFileURL,
  93. xia: fileList[3].tempFileURL,
  94. // shouchangs: fileList[4].tempFileURL,
  95. })
  96. // // 并发下载多个 fileID
  97. // Promise.all(
  98. // fileIDs.map(fileID => wx.cloud.downloadFile({ fileID }))
  99. // ).then(results => {
  100. // // 每个 result 对应一个下载结果
  101. // const tempFilePaths = results.map(r => r.tempFilePath);
  102. // console.log('全部下载成功:', tempFilePaths);
  103. // this.setData({
  104. // shouchang: tempFilePaths[0],
  105. // show_1: tempFilePaths[1],
  106. // xiazi: tempFilePaths[2],
  107. // xia: tempFilePaths[3],
  108. // shouchangs: tempFilePaths[4],
  109. // });
  110. // }).catch(err => {
  111. // console.error('有文件下载失败:', err);
  112. // });
  113. },
  114. formatTime(ts) {
  115. const date = new Date(ts);
  116. const y = date.getFullYear();
  117. const m = String(date.getMonth() + 1).padStart(2, '0');
  118. const d = String(date.getDate()).padStart(2, '0');
  119. const hh = String(date.getHours()).padStart(2, '0');
  120. const mm = String(date.getMinutes()).padStart(2, '0');
  121. const ss = String(date.getSeconds()).padStart(2, '0');
  122. return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
  123. },
  124. // 相关课件推荐
  125. async getcourseList() {
  126. console.log(this.data.itemlist._id, this.data.itemlist.range, this.data.itemlist.tag_id, '+++++++++++++++++++++++++++++++++++++++++++++++' );
  127. let client = await getClient(); // 跨小程序 SDK
  128. const result = await client.callFunction({
  129. name: "database", // 云函数部署名
  130. data: {
  131. page: "recommende",
  132. action: "findFileRangee",
  133. data: {
  134. _id: this.data.itemlist._id,
  135. range: this.data.itemlist.range,
  136. tag_id: this.data.itemlist.tag_id,
  137. pageSize: 20,
  138. pageNum: 1,
  139. },
  140. },
  141. });
  142. console.log(result, 'data++++++---------------');
  143. this.setData({
  144. courseList: result.result.records
  145. })
  146. const models = await getModels()
  147. const { data } = await models.file_manage.list({
  148. filter: {
  149. where: {
  150. level: this.data.itemlist.level,
  151. dan: this.data.itemlist.dan,
  152. tag_id: this.data.itemlist.tag_id
  153. }
  154. },
  155. pageSize: 20, // 分页大小,建议指定,如需设置为其它值,需要和 pageNumber 配合使用,两者同时指定才会生效
  156. pageNumber: 1, // 第几页
  157. getCount: true, // 开启用来获取总数
  158. // envType: pre 体验环境, prod 正式环境
  159. envType: "prod",
  160. });
  161. // 返回查询到的数据列表 records 和 总数 total
  162. console.log(data, 'data');
  163. let recordsdata = data.records || []
  164. // 提取 cover 云文件 ID
  165. const coverFileIDs = recordsdata.map(item => item.cover).filter(Boolean)
  166. // 批量获取临时链接
  167. let tempFiles = []
  168. if (coverFileIDs.length > 0) {
  169. try {
  170. tempFiles = await getTempFileURLs(coverFileIDs)
  171. } catch (err) {
  172. console.error('获取课程封面临时链接失败', err)
  173. }
  174. }
  175. // 给每条记录添加可直接渲染的 coverUrl
  176. recordsdata = recordsdata.map((item, index) => ({
  177. ...item,
  178. coverUrl: tempFiles[index] ? tempFiles[index].tempFileURL : ''
  179. }))
  180. this.setData({
  181. courseList: recordsdata
  182. })
  183. },
  184. // 下载
  185. goToGoodsLists(event) {
  186. // 获取绑定的数据
  187. const item = event.currentTarget.dataset.item;
  188. // 将数据转换为 JSON 字符串并传递
  189. const itemStr = encodeURIComponent(JSON.stringify(item));
  190. wx.navigateTo({
  191. url: `/subpackages/down/down?item=${itemStr}`
  192. });
  193. },
  194. // 相关课件点击详情
  195. goToGoodsList(event) {
  196. // 获取绑定的数据
  197. const item = event.currentTarget.dataset.item;
  198. // 将数据转换为 JSON 字符串并传递
  199. const itemStr = encodeURIComponent(JSON.stringify(item));
  200. wx.navigateTo({
  201. url: `/subpackagestow/details/details?item=${itemStr}`
  202. });
  203. },
  204. // // 是否收藏
  205. // async getcollect() {
  206. // const { data } = await models.wx_collect.get({
  207. // filter: {
  208. // where: {
  209. // file_manager_id: this.data.itemlist._id
  210. // }
  211. // },
  212. // // envType: pre 体验环境, prod 正式环境
  213. // envType: "prod",
  214. // });
  215. // // 返回查询到的数据
  216. // console.log(data, '123321');
  217. // // 判断是否有值
  218. // if (data && Object.keys(data).length > 0) {
  219. // this.setData({
  220. // isCollected: true // 设置标志为 true
  221. // });
  222. // } else {
  223. // this.setData({
  224. // isCollected: false // 设置标志为 false
  225. // });
  226. // }
  227. // },
  228. // // 收藏
  229. // async goTocollect() {
  230. // if (this.data.isCollected) {
  231. // const { data } = await models.wx_collect.delete({
  232. // filter: {
  233. // where: {
  234. // file_manager_id: _.eq(this.data.itemlist._id), // 收藏文件id
  235. // }
  236. // },
  237. // // envType: pre 体验环境, prod 正式环境
  238. // envType: "prod",
  239. // });
  240. // // 返回删除成功的条数
  241. // console.log(data, '删除');
  242. // wx.showToast({ title: '取消收藏成功', icon: 'success' });
  243. // this.setData({
  244. // isCollected: false
  245. // })
  246. // } else {
  247. // const userInfo = wx.getStorageSync('userInfo');
  248. // const { data } = await models.wx_collect.create({
  249. // data: {
  250. // wx_user_id: userInfo._id, // 收藏人_id
  251. // file_manager_id: this.data.itemlist._id, // 收藏文件id
  252. // remark: "备注备注备注备注备注备注", // 备注
  253. // },
  254. // // envType: pre 体验环境, prod 正式环境
  255. // envType: "prod",
  256. // });
  257. // // 返回创建的数据 id
  258. // console.log(data);
  259. // wx.showToast({ title: '收藏成功', icon: 'success' });
  260. // this.setData({
  261. // isCollected: true // 设置标志为 true
  262. // });
  263. // }
  264. // },
  265. // 预览
  266. async previewPDF() {
  267. const fileUrl = this.data.itemlist.url[0];
  268. console.log(fileUrl, 'this.data.itemlist.url[0]');
  269. // 提取文件后缀
  270. const extension = fileUrl.substring(fileUrl.lastIndexOf('.') + 1).toLowerCase();
  271. // 文档类文件需要下载
  272. if (['pdf', 'ppt', 'pptx'].includes(extension)) {
  273. try {
  274. let downloadUrl = fileUrl;
  275. if (fileUrl.startsWith('cloud://')) {
  276. // cloud:// 文件获取临时链接
  277. const fileList = await getTempFileURLs([fileUrl]);
  278. if (!fileList || !fileList[0]?.tempFileURL) throw new Error('获取临时链接失败');
  279. downloadUrl = fileList[0].tempFileURL;
  280. }
  281. // 下载到本地临时文件
  282. const res = await new Promise((resolve, reject) => {
  283. wx.downloadFile({
  284. url: downloadUrl,
  285. success: resolve,
  286. fail: reject
  287. });
  288. });
  289. // 打开文档
  290. wx.openDocument({
  291. filePath: res.tempFilePath,
  292. fileType: extension,
  293. success: () => console.log('文档打开成功'),
  294. fail: err => console.error('文档打开失败', err)
  295. });
  296. } catch (err) {
  297. console.error('文档下载失败', err);
  298. wx.showToast({ title: '文档下载失败', icon: 'none' });
  299. }
  300. } else if (['mp3', 'aac', 'wav'].includes(extension)) {
  301. console.log('音频文件,直接播放');
  302. this.toggleAudio(); // HTTP 链接直接播放
  303. } else if (['mp4', 'mov'].includes(extension)) {
  304. console.log('视频文件,直接播放');
  305. this.toggleVideo(); // HTTP 链接直接播放
  306. } else {
  307. wx.showToast({ title: '暂不支持该文件类型预览', icon: 'none' });
  308. }
  309. // const client = await getClient(); // ✅ 获取跨小程序云实例
  310. // console.log(this.data.itemlist.url[0], 'this.data.itemlist.url[0]');
  311. // client.downloadFile({
  312. // fileID: this.data.itemlist.url[0],
  313. // success: res => {
  314. // const filePath = res.tempFilePath;
  315. // const extension = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
  316. // console.log('文件后缀:', extension);
  317. // // 根据文件类型处理
  318. // if (['pdf', 'ppt', 'pptx'].includes(extension)) {
  319. // wx.openDocument({
  320. // filePath: filePath,
  321. // fileType: extension,
  322. // success: () => {
  323. // console.log('文档打开成功');
  324. // },
  325. // fail: err => {
  326. // console.error('文档打开失败', err);
  327. // }
  328. // });
  329. // } else if (['mp3', 'aac', 'wav'].includes(extension)) {
  330. // console.log('这是一个音频文件,可以跳转到播放页面或使用音频组件');
  331. // this.toggleAudio()
  332. // } else if (['mp4', 'mov'].includes(extension)) {
  333. // console.log('这是一个视频文件,可以跳转到视频播放页');
  334. // this.toggleVideo()
  335. // } else {
  336. // wx.showToast({
  337. // title: '暂不支持该文件类型预览',
  338. // icon: 'none'
  339. // });
  340. // }
  341. // },
  342. // fail: err => {
  343. // console.error('文件下载失败', err);
  344. // }
  345. // });
  346. },
  347. // 视频播放还是暂停
  348. toggleVideo() {
  349. const videoContext = wx.createVideoContext('myVideo', this);
  350. if (this.data.isPlaying) {
  351. videoContext.pause();
  352. this.setData({ isPlaying: false });
  353. } else {
  354. videoContext.play();
  355. this.setData({ isPlaying: true });
  356. }
  357. },
  358. // 音频的播放暂停
  359. async toggleAudio() {
  360. const fileUrl = this.data.itemlist.url[0];
  361. // 如果已经有临时播放链接,直接用它
  362. if (this.data.itemlist.playUrl) {
  363. this._playAudio(this.data.itemlist.playUrl);
  364. } else if (fileUrl.startsWith('cloud://')) {
  365. // // 否则判断 url 是否是 cloud:// 开头,需要转临时链接
  366. // const cloudUrl = this.data.itemlist.url[0];
  367. // if (cloudUrl && cloudUrl.startsWith('cloud://')) {
  368. // const fileList = await getTempFileURLs([cloudUrl]);
  369. // if (fileList && fileList.length > 0) {
  370. // const tempUrl = fileList[0].tempFileURL;
  371. // this.setData({ 'itemlist.playUrl': tempUrl }, () => {
  372. // this._playAudio(tempUrl);
  373. // });
  374. // } else {
  375. // wx.showToast({ title: '获取播放链接失败', icon: 'none' });
  376. // }
  377. // } else {
  378. // // 不是 cloud:// 开头,直接播放原链接
  379. // this._playAudio(cloudUrl);
  380. // }
  381. // cloud:// 走临时链接逻辑
  382. try {
  383. const fileList = await getTempFileURLs([fileUrl]);
  384. if (fileList.length > 0) {
  385. const tempUrl = fileList[0].tempFileURL;
  386. this.setData({ 'itemlist.playUrl': tempUrl }, () => this._playAudio(tempUrl));
  387. } else {
  388. wx.showToast({ title: '获取播放链接失败', icon: 'none' });
  389. }
  390. } catch (err) {
  391. wx.showToast({ title: '获取播放链接失败', icon: 'none' });
  392. console.error(err);
  393. }
  394. } else {
  395. // HTTP 链接直接播放
  396. this._playAudio(fileUrl);
  397. }
  398. },
  399. _playAudio(url) {
  400. if (!this.audioContext) {
  401. this.audioContext = wx.createInnerAudioContext();
  402. this.audioContext.onPlay(() => this.setData({ isAudioPlaying: true }));
  403. this.audioContext.onPause(() => this.setData({ isAudioPlaying: false }));
  404. this.audioContext.onStop(() => this.setData({ isAudioPlaying: false }));
  405. this.audioContext.onEnded(() => this.setData({ isAudioPlaying: false }));
  406. this.audioContext.onError((res) => {
  407. wx.showToast({ title: '音频播放错误', icon: 'none' });
  408. this.setData({ isAudioPlaying: false });
  409. console.error('音频播放错误', res);
  410. });
  411. }
  412. if (this.data.isAudioPlaying) {
  413. this.audioContext.pause();
  414. } else {
  415. this.audioContext.src = url;
  416. this.audioContext.play();
  417. }
  418. },
  419. onUnload() {
  420. if (this.audioContext) {
  421. this.audioContext.stop();
  422. this.audioContext.destroy();
  423. this.audioContext = null;
  424. }
  425. },
  426. onHide() {
  427. if (this.audioContext) {
  428. this.audioContext.pause();
  429. }
  430. },
  431. })