// import { models, db, _ } from '../../utils/cloudbase.js' import { getDB, getModels, getCommand, getTempFileURLs } from '../../utils/cloudbase.js' Page({ data: { cartItems: [], souimg: '', pageNumber: 1, pageSize: 10, hasMore: true, // 是否还有更多数据 isLoading: false, // 防止多次触发 searchText: '', // 输入的搜索内容 }, onShow() { if (typeof this.getTabBar === 'function' && this.getTabBar()) { this.getTabBar().setSelected(2); // 比如首页就是 0 } // 列表数据 this.setData({ pageNumber: 1, hasMore: true, cartItems: [] }, () => { this.getdatalist() }); }, async onLoad() { // // 列表数据 // this.setData({ // pageNumber: 1, // hasMore: true, // cartItems: [] // }, () => { // this.getdatalist() // }); const fileIDs = [ 'cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/images/icon/sou.png', ]; const fileList = await getTempFileURLs(fileIDs) this.setData({ souimg: fileList[0].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({ // souimg: tempFilePaths[0], // }); // }).catch(err => { // console.error('有文件下载失败:', err); // }); }, onReachBottom() { // 上拉触底事件的处理函数 this.loadMore(); }, loadMore() { // 加载更多数据的逻辑 console.log('加载更多'); // this.getdatalist(true); if (this.data.isLoading || !this.data.hasMore) return; this.setData({ isLoading: true }); this.getdatalist(true); }, // 模糊搜索 onSearchInput(e) { const searchText = e.detail.value.trim(); this.setData({ searchText, pageNumber: 1, cartItems: [], hasMore: true }, () => { this.getdatalist(); }); }, onSearchConfirm() { this.setData({ pageNumber: 1, cartItems: [], hasMore: true }, () => { this.getdatalist(); }); }, // 获取列表数据 async getdatalist(isLoadMore = false) { const models = await getModels() if (this.data.isLoading || !this.data.hasMore) return; this.setData({ isLoading: true }); const { pageNumber, pageSize, searchText } = this.data; // 获取本地存储的用户信息 const userInfo = wx.getStorageSync('userInfo'); const userId = userInfo && userInfo._id ? userInfo._id : ''; // 根据你的userInfo结构取ID const cartWhere = { user_id: userId // 每次必传 }; if (searchText) { cartWhere.name = { $regex_ci: searchText }; } try { const { data } = await models.shopping_cart.list({ filter: { where: cartWhere }, pageSize, pageNumber, getCount: true, // 开启用来获取总数 // envType: pre 体验环境, prod 正式环境 envType: "prod", }); // 返回查询到的数据列表 records 和 总数 total console.log(data); const collectList = data.records || []; if (collectList.length === 0) { this.setData({ hasMore: false, isLoading: false }); return; } const fileManagerIds = collectList.map(item => item.merchandise_id); // 第二步:循环获取每个文件数据(单条查询) const fileDetailPromises = fileManagerIds.map(id => { return models.wx_merchandise.list({ filter: { where: { _id: id } }, envType: "prod" }).then(res => { const record = res.data?.records?.[0]; if (!record) { console.warn(`未找到 _id 为 ${id} 的文件`); } return record || null; }) .catch(err => { console.error(`获取文件 ${id} 失败`, err); return null; }); }); // 第三步:等待所有请求完成 const fileDetails = await Promise.all(fileDetailPromises); console.log(fileDetails, 'fileDetails'); // 第四步:过滤无效项,并添加 checked 字段 let newFiles = fileDetails .filter(Boolean) .map((file, index) => { const historyRecord = collectList[index]; if (!file) return null; return { ...file, checked: false, download_history_id: historyRecord._id, specs_index: Number(historyRecord.specs_index), num: historyRecord.num }; }) .filter(Boolean); // ✅ 如果搜索内容不为空,在本地进行模糊匹配过滤 if (searchText) { const pattern = new RegExp(searchText, 'i'); // 不区分大小写 newFiles = newFiles.filter(item => pattern.test(item.name)); } // 循环去查 groupbuy 表 for (let item of newFiles) { try { const res = await models.wx_groupbuy_groupbuy.list({ filter: { where: { groupbuy_id: item._id } }, envType: "prod", }); // 把查到的记录存入 specList,保证是数组 item.specList = res.data.records || []; } catch (err) { console.error(`获取 groupbuy 失败,商品ID: ${item._id}`, err); item.specList = []; } } console.log(newFiles, '+++++++++++++++++++++++++++++'); // 第五步:循环处理 specList 和商品主图 for (let item of newFiles) { // 处理 groupbuy 里的 detail_images if (item.specList && item.specList.length > 0) { for (let i = 0; i < item.specList.length; i++) { const images = item.specList[i].detail_images || []; if (images.length > 0) { const tempFiles = await getTempFileURLs(images); item.specList[i].detail_images = tempFiles.map(f => f.tempFileURL); } } } // 处理商品主图 item.img if (item.img) { const tempFiles = await getTempFileURLs([item.img]); item.img = tempFiles[0].tempFileURL; } } this.setData({ cartItems: isLoadMore ? this.data.cartItems.concat(newFiles) : newFiles, pageNumber: pageNumber + 1, hasMore: collectList.length === pageSize, // 如果返回的数量小于 pageSize,说明已经到底 isLoading: false }, () => { this.updateTotalPrice(); }); } catch (err) { console.error('获取收藏文件失败:', err); this.setData({ isLoading: false }); } }, handleCheckboxChange(e) { const { value } = e.detail; const cartItems = this.data.cartItems.map(item => ({ ...item, checked: value.includes(item.download_history_id) })); this.setData({ cartItems }); this.updateTotalPrice(); }, handleAllCheckboxChange(e) { const { value } = e.detail; const allChecked = value.includes('all'); const cartItems = this.data.cartItems.map(item => ({ ...item, checked: allChecked })); this.setData({ cartItems, allChecked }); this.updateTotalPrice(); }, updateTotalPrice() { const totalPrice = this.data.cartItems.reduce((total, item) => { if (item.checked) { return total + item.specList[item.specs_index].price * item.num; } return total; }, 0); this.setData({ totalPrice }); }, // handleCheckout() { // // 过滤出已选中的商品 // const selectedItems = this.data.cartItems.filter(item => item.checked); // if (selectedItems.length === 0) { // wx.showToast({ // title: '请选择要结算的商品', // icon: 'none' // }); // return; // } // // 将数据存入本地缓存 // wx.setStorageSync('checkoutItems', selectedItems); // wx.navigateTo({ // url: '/subpackages/submitorder/submitorder' // }); // }, handleCheckout: async function() { const models = await getModels() // 过滤出已选中的商品 const selectedItems = this.data.cartItems.filter(item => item.checked); if (selectedItems.length === 0) { wx.showToast({ title: '请选择要结算的商品', icon: 'none' }); return; } // 1️⃣ 将选中商品存入本地缓存 wx.setStorageSync('checkoutItems', selectedItems); // 2️⃣ 删除购物车表中已选商品(循环单条删除) wx.showLoading({ title: '处理中...' }); try { const deletePromises = selectedItems.map(item => { return models.shopping_cart.delete({ filter: { where: { $and: [ { _id: { $eq: item.download_history_id } } ] } }, envType: 'prod' }); }); const results = await Promise.all(deletePromises); console.log('删除结果:', results.map(r => r.data.count)); // 3️⃣ 更新前端页面数据 // const remainingItems = this.data.cartItems.filter(item => !item.checked); // this.setData({ cartItems: remainingItems }); wx.hideLoading(); // 4️⃣ 跳转结算页 wx.navigateTo({ url: '/subpackages/submitorder/submitorder' }); } catch (err) { // console.error('删除失败:', err); // wx.hideLoading(); // wx.showToast({ title: '删除购物车失败,请重试', icon: 'none' }); // // 即便删除失败,也可以跳转结算页(可选) // wx.navigateTo({ // url: '/subpackages/submitorder/submitorder' // }); } }, // 购买数量 onChange(e) { const { id } = e.currentTarget.dataset; const { detail } = e; const cartItems = this.data.cartItems.map(item => { if (item.download_history_id === id) { return { ...item, num: detail }; } return item; }); this.setData({ cartItems }, () => { this.updateTotalPrice(); }); } });