// subpackagestow/details/details.js // import { models, db, _ } from '../../utils/cloudbase.js' import { getDB, getModels, getCommand, getTempFileURLs, getClient } from '../../utils/cloudbase.js' Page({ /** * 页面的初始数据 */ data: { fileType: 'video', viewType: 'grid', courseList: [], shouchang: '', show_1: '', xiazi: '', xia: '', itemlist: {}, isCollected: false, isPlaying: false, isAudioPlaying: false, }, async onLoad(options) { // 获取传递过来的数据 const itemStr = decodeURIComponent(options.item); const item = JSON.parse(itemStr); // 格式化时间 item.createdAtText = this.formatTime(item.createdAt); // 判断 url 字段是否存在且是 cloud:// if (item.url && item.url.length > 0) { try { // 只转换 cloud:// 格式的 const cloudUrls = item.url.filter(u => u.startsWith('cloud://')); if (cloudUrls.length > 0) { const fileList = await getTempFileURLs(cloudUrls); // 按顺序替换成 http 链接 fileList.forEach((f, i) => { if (f.tempFileURL) { const idx = item.url.indexOf(cloudUrls[i]); if (idx !== -1) { item.url[idx] = f.tempFileURL; } } }); } } catch (err) { console.error('url 转换失败', err); } } // // 设置到页面数据中 // this.setData({ // itemlist: item // }, () => { // // 转换云文件ID为临时链接 // if (item.url && item.url.length > 0) { // wx.cloud.getTempFileURL({ // fileList: [item.url[0]], // success: res => { // if (res.fileList && res.fileList.length > 0) { // this.setData({ // 'itemlist.playUrl': res.fileList[0].tempFileURL // }); // } // }, // fail: err => { // console.error('获取临时链接失败', err); // } // }); // } this.setData({ itemlist: item }) // 转换云文件ID为临时链接 if (item.url && item.url.length > 0) { try { const tempFiles = await getTempFileURLs([item.url[0]]) this.setData({ 'itemlist.playUrl': tempFiles[0].tempFileURL }) } catch (err) { console.error('获取临时链接失败', err) } } // 相关推荐 this.getcourseList() // }); // 获取图片 const fileIDs = [ 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/shouchang.png', 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/show_1.png', 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xiazi.png', 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/xia_1.png' ]; const fileList = await getTempFileURLs(fileIDs) this.setData({ shouchang: fileList[0].tempFileURL, show_1: fileList[1].tempFileURL, xiazi: fileList[2].tempFileURL, xia: fileList[3].tempFileURL, // shouchangs: fileList[4].tempFileURL, }) // // 并发下载多个 fileID // Promise.all( // fileIDs.map(fileID => wx.cloud.downloadFile({ fileID })) // ).then(results => { // // 每个 result 对应一个下载结果 // const tempFilePaths = results.map(r => r.tempFilePath); // console.log('全部下载成功:', tempFilePaths); // this.setData({ // shouchang: tempFilePaths[0], // show_1: tempFilePaths[1], // xiazi: tempFilePaths[2], // xia: tempFilePaths[3], // shouchangs: tempFilePaths[4], // }); // }).catch(err => { // console.error('有文件下载失败:', err); // }); }, formatTime(ts) { const date = new Date(ts); const y = date.getFullYear(); const m = String(date.getMonth() + 1).padStart(2, '0'); const d = String(date.getDate()).padStart(2, '0'); const hh = String(date.getHours()).padStart(2, '0'); const mm = String(date.getMinutes()).padStart(2, '0'); const ss = String(date.getSeconds()).padStart(2, '0'); return `${y}-${m}-${d} ${hh}:${mm}:${ss}`; }, // 相关课件推荐 async getcourseList() { console.log(this.data.itemlist._id, this.data.itemlist.range, this.data.itemlist.tag_id, '+++++++++++++++++++++++++++++++++++++++++++++++' ); let client = await getClient(); // 跨小程序 SDK const result = await client.callFunction({ name: "database", // 云函数部署名 data: { page: "recommende", action: "findFileRangee", data: { _id: this.data.itemlist._id, range: this.data.itemlist.range, tag_id: this.data.itemlist.tag_id, pageSize: 20, pageNum: 1, }, }, }); console.log(result, 'data++++++---------------'); this.setData({ courseList: result.result.records }) const models = await getModels() const { data } = await models.file_manage.list({ filter: { where: { level: this.data.itemlist.level, dan: this.data.itemlist.dan, tag_id: this.data.itemlist.tag_id } }, pageSize: 20, // 分页大小,建议指定,如需设置为其它值,需要和 pageNumber 配合使用,两者同时指定才会生效 pageNumber: 1, // 第几页 getCount: true, // 开启用来获取总数 // envType: pre 体验环境, prod 正式环境 envType: "prod", }); // 返回查询到的数据列表 records 和 总数 total console.log(data, 'data'); let recordsdata = data.records || [] // 提取 cover 云文件 ID const coverFileIDs = recordsdata.map(item => item.cover).filter(Boolean) // 批量获取临时链接 let tempFiles = [] if (coverFileIDs.length > 0) { try { tempFiles = await getTempFileURLs(coverFileIDs) } catch (err) { console.error('获取课程封面临时链接失败', err) } } // 给每条记录添加可直接渲染的 coverUrl recordsdata = recordsdata.map((item, index) => ({ ...item, coverUrl: tempFiles[index] ? tempFiles[index].tempFileURL : '' })) this.setData({ courseList: recordsdata }) }, // 下载 goToGoodsLists(event) { // 获取绑定的数据 const item = event.currentTarget.dataset.item; // 将数据转换为 JSON 字符串并传递 const itemStr = encodeURIComponent(JSON.stringify(item)); wx.navigateTo({ url: `/subpackages/down/down?item=${itemStr}` }); }, // 相关课件点击详情 goToGoodsList(event) { // 获取绑定的数据 const item = event.currentTarget.dataset.item; // 将数据转换为 JSON 字符串并传递 const itemStr = encodeURIComponent(JSON.stringify(item)); wx.navigateTo({ url: `/subpackagestow/details/details?item=${itemStr}` }); }, // // 是否收藏 // async getcollect() { // const { data } = await models.wx_collect.get({ // filter: { // where: { // file_manager_id: this.data.itemlist._id // } // }, // // envType: pre 体验环境, prod 正式环境 // envType: "prod", // }); // // 返回查询到的数据 // console.log(data, '123321'); // // 判断是否有值 // if (data && Object.keys(data).length > 0) { // this.setData({ // isCollected: true // 设置标志为 true // }); // } else { // this.setData({ // isCollected: false // 设置标志为 false // }); // } // }, // // 收藏 // async goTocollect() { // if (this.data.isCollected) { // const { data } = await models.wx_collect.delete({ // filter: { // where: { // file_manager_id: _.eq(this.data.itemlist._id), // 收藏文件id // } // }, // // envType: pre 体验环境, prod 正式环境 // envType: "prod", // }); // // 返回删除成功的条数 // console.log(data, '删除'); // wx.showToast({ title: '取消收藏成功', icon: 'success' }); // this.setData({ // isCollected: false // }) // } else { // const userInfo = wx.getStorageSync('userInfo'); // const { data } = await models.wx_collect.create({ // data: { // wx_user_id: userInfo._id, // 收藏人_id // file_manager_id: this.data.itemlist._id, // 收藏文件id // remark: "备注备注备注备注备注备注", // 备注 // }, // // envType: pre 体验环境, prod 正式环境 // envType: "prod", // }); // // 返回创建的数据 id // console.log(data); // wx.showToast({ title: '收藏成功', icon: 'success' }); // this.setData({ // isCollected: true // 设置标志为 true // }); // } // }, // 预览 async previewPDF() { const fileUrl = this.data.itemlist.url[0]; console.log(fileUrl, 'this.data.itemlist.url[0]'); // 提取文件后缀 const extension = fileUrl.substring(fileUrl.lastIndexOf('.') + 1).toLowerCase(); // 文档类文件需要下载 if (['pdf', 'ppt', 'pptx'].includes(extension)) { try { let downloadUrl = fileUrl; if (fileUrl.startsWith('cloud://')) { // cloud:// 文件获取临时链接 const fileList = await getTempFileURLs([fileUrl]); if (!fileList || !fileList[0]?.tempFileURL) throw new Error('获取临时链接失败'); downloadUrl = fileList[0].tempFileURL; } // 下载到本地临时文件 const res = await new Promise((resolve, reject) => { wx.downloadFile({ url: downloadUrl, success: resolve, fail: reject }); }); // 打开文档 wx.openDocument({ filePath: res.tempFilePath, fileType: extension, success: () => console.log('文档打开成功'), fail: err => console.error('文档打开失败', err) }); } catch (err) { console.error('文档下载失败', err); wx.showToast({ title: '文档下载失败', icon: 'none' }); } } else if (['mp3', 'aac', 'wav'].includes(extension)) { console.log('音频文件,直接播放'); this.toggleAudio(); // HTTP 链接直接播放 } else if (['mp4', 'mov'].includes(extension)) { console.log('视频文件,直接播放'); this.toggleVideo(); // HTTP 链接直接播放 } else { wx.showToast({ title: '暂不支持该文件类型预览', icon: 'none' }); } // const client = await getClient(); // ✅ 获取跨小程序云实例 // console.log(this.data.itemlist.url[0], 'this.data.itemlist.url[0]'); // client.downloadFile({ // fileID: this.data.itemlist.url[0], // success: res => { // const filePath = res.tempFilePath; // const extension = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase(); // console.log('文件后缀:', extension); // // 根据文件类型处理 // if (['pdf', 'ppt', 'pptx'].includes(extension)) { // wx.openDocument({ // filePath: filePath, // fileType: extension, // success: () => { // console.log('文档打开成功'); // }, // fail: err => { // console.error('文档打开失败', err); // } // }); // } else if (['mp3', 'aac', 'wav'].includes(extension)) { // console.log('这是一个音频文件,可以跳转到播放页面或使用音频组件'); // this.toggleAudio() // } else if (['mp4', 'mov'].includes(extension)) { // console.log('这是一个视频文件,可以跳转到视频播放页'); // this.toggleVideo() // } else { // wx.showToast({ // title: '暂不支持该文件类型预览', // icon: 'none' // }); // } // }, // fail: err => { // console.error('文件下载失败', err); // } // }); }, // 视频播放还是暂停 toggleVideo() { const videoContext = wx.createVideoContext('myVideo', this); if (this.data.isPlaying) { videoContext.pause(); this.setData({ isPlaying: false }); } else { videoContext.play(); this.setData({ isPlaying: true }); } }, // 音频的播放暂停 async toggleAudio() { const fileUrl = this.data.itemlist.url[0]; // 如果已经有临时播放链接,直接用它 if (this.data.itemlist.playUrl) { this._playAudio(this.data.itemlist.playUrl); } else if (fileUrl.startsWith('cloud://')) { // // 否则判断 url 是否是 cloud:// 开头,需要转临时链接 // const cloudUrl = this.data.itemlist.url[0]; // if (cloudUrl && cloudUrl.startsWith('cloud://')) { // const fileList = await getTempFileURLs([cloudUrl]); // if (fileList && fileList.length > 0) { // const tempUrl = fileList[0].tempFileURL; // this.setData({ 'itemlist.playUrl': tempUrl }, () => { // this._playAudio(tempUrl); // }); // } else { // wx.showToast({ title: '获取播放链接失败', icon: 'none' }); // } // } else { // // 不是 cloud:// 开头,直接播放原链接 // this._playAudio(cloudUrl); // } // cloud:// 走临时链接逻辑 try { const fileList = await getTempFileURLs([fileUrl]); if (fileList.length > 0) { const tempUrl = fileList[0].tempFileURL; this.setData({ 'itemlist.playUrl': tempUrl }, () => this._playAudio(tempUrl)); } else { wx.showToast({ title: '获取播放链接失败', icon: 'none' }); } } catch (err) { wx.showToast({ title: '获取播放链接失败', icon: 'none' }); console.error(err); } } else { // HTTP 链接直接播放 this._playAudio(fileUrl); } }, _playAudio(url) { if (!this.audioContext) { this.audioContext = wx.createInnerAudioContext(); this.audioContext.onPlay(() => this.setData({ isAudioPlaying: true })); this.audioContext.onPause(() => this.setData({ isAudioPlaying: false })); this.audioContext.onStop(() => this.setData({ isAudioPlaying: false })); this.audioContext.onEnded(() => this.setData({ isAudioPlaying: false })); this.audioContext.onError((res) => { wx.showToast({ title: '音频播放错误', icon: 'none' }); this.setData({ isAudioPlaying: false }); console.error('音频播放错误', res); }); } if (this.data.isAudioPlaying) { this.audioContext.pause(); } else { this.audioContext.src = url; this.audioContext.play(); } }, onUnload() { if (this.audioContext) { this.audioContext.stop(); this.audioContext.destroy(); this.audioContext = null; } }, onHide() { if (this.audioContext) { this.audioContext.pause(); } }, })