diff --git a/miniprogram/pages/buy/buy.js b/miniprogram/pages/buy/buy.js index 0d73c42..cc84ac3 100644 --- a/miniprogram/pages/buy/buy.js +++ b/miniprogram/pages/buy/buy.js @@ -60,10 +60,8 @@ Page({ * 生命周期函数--监听页面显示 */ onShow() { - // 页面显示时刷新数据 - if (this.data.products.length === 0) { - this.loadProducts(); - } + // 页面显示时刷新数据,确保显示最新发布的商品 + this.loadProducts(true); }, /** @@ -186,15 +184,13 @@ Page({ currentPage: 1, hasMore: true }); - - // 模拟网络请求 - setTimeout(() => { - this.loadProducts(true); - this.setData({ - refreshing: false - }); - wx.stopPullDownRefresh(); - }, 1000); + + // 重新加载数据 + this.loadProducts(true); + this.setData({ + refreshing: false + }); + wx.stopPullDownRefresh(); }, /** @@ -231,21 +227,81 @@ Page({ * 加载商品数据 */ loadProducts(refresh = false) { + const db = wx.cloud.database(); + const { currentPage, pageSize, selectedCategory, categories } = this.data; + + // 如果是刷新,重置页码 + const page = refresh ? 1 : currentPage; + this.setData({ loading: true }); - - // 模拟网络请求 - setTimeout(() => { - const products = this.generateMockProducts(1, this.data.pageSize); - this.setData({ - products: products, - filteredProducts: products, - currentPage: 1, - hasMore: products.length === this.data.pageSize, - loading: false + + // 构建查询条件 + let query = db.collection('T_product').where({ + status: '在售' // 只显示在售商品 + }); + + // 分类筛选 + if (selectedCategory > 0 && categories[selectedCategory]) { + const category = categories[selectedCategory]; + query = query.where({ + productCategory: category }); - }, 800); + } + + // 分页查询 + query = query + .orderBy('createTime', 'desc') // 按创建时间倒序 + .skip((page - 1) * pageSize) + .limit(pageSize); + + query.get({ + success: (res) => { + console.log('查询商品成功:', res); + + if (res.data && res.data.length > 0) { + // 处理商品数据 + this.processProducts(res.data).then((processedProducts) => { + const products = refresh ? processedProducts : [...this.data.products, ...processedProducts]; + + this.setData({ + products: products, + filteredProducts: products, + currentPage: page, + hasMore: res.data.length === pageSize, + loading: false + }); + + // 应用筛选和排序 + this.filterProducts(); + }); + } else { + // 没有数据 + this.setData({ + hasMore: false, + loading: false + }); + if (refresh) { + this.setData({ + products: [], + filteredProducts: [] + }); + } + } + }, + fail: (err) => { + console.error('查询商品失败:', err); + wx.showToast({ + title: '加载失败,请重试', + icon: 'none', + duration: 2000 + }); + this.setData({ + loading: false + }); + } + }); }, /** @@ -293,27 +349,126 @@ Page({ this.sortProducts(); }, + /** + * 处理商品数据,转换格式并获取图片URL + */ + async processProducts(products) { + const processedProducts = await Promise.all(products.map(async (product) => { + // 获取图片临时URL + let imageUrl = '/images/default-product.png'; // 默认图片 + if (product.productImage) { + try { + // 如果是云存储路径,获取临时URL + if (product.productImage.startsWith('cloud://')) { + const tempFileURL = await wx.cloud.getTempFileURL({ + fileList: [product.productImage] + }); + if (tempFileURL.fileList && tempFileURL.fileList.length > 0) { + imageUrl = tempFileURL.fileList[0].tempFileURL; + } + } else { + // 如果是网络URL,直接使用 + imageUrl = product.productImage; + } + } catch (err) { + console.error('获取图片URL失败:', err); + } + } + + // 计算折扣 + let discount = null; + if (product.originalPrice > 0 && product.salePrice > 0) { + discount = (product.salePrice / product.originalPrice * 10).toFixed(1); + } + + // 格式化时间 + const publishTime = this.formatTime(product.createTime); + + // 获取卖家信息 + const sellerName = product.sellerInfo?.sname || '用户'; + const sellerAvatar = product.sellerInfo?.avatar || '/images/default-avatar.png'; + + // 返回格式化后的商品数据 + return { + id: product._id, + name: product.productName || '未命名商品', + description: product.productDescription || '', + price: product.salePrice || product.suggestedPrice || 0, + originalPrice: product.originalPrice || null, + discount: discount, + category: product.productCategory || '其他', + condition: product.conditionLevel || '未知', + location: '校园', // 可以根据需要添加location字段 + publishTime: publishTime, + image: imageUrl, + sellerAvatar: sellerAvatar, + sellerName: sellerName, + sellerRating: '4.8', // 可以根据需要添加评分系统 + status: product.status === '在售' ? 'selling' : 'sold', + // 保留原始数据字段,方便后续使用 + _originalData: product + }; + })); + + return processedProducts; + }, + + /** + * 格式化时间显示 + */ + formatTime(date) { + if (!date) return ''; + + const now = new Date(); + const createTime = date instanceof Date ? date : new Date(date); + const diff = now - createTime; + + const seconds = Math.floor(diff / 1000); + const minutes = Math.floor(seconds / 60); + const hours = Math.floor(minutes / 60); + const days = Math.floor(hours / 24); + + if (seconds < 60) { + return '刚刚'; + } else if (minutes < 60) { + return `${minutes}分钟前`; + } else if (hours < 24) { + return `${hours}小时前`; + } else if (days < 7) { + return `${days}天前`; + } else { + // 超过7天,显示具体日期 + const month = createTime.getMonth() + 1; + const day = createTime.getDate(); + return `${month}月${day}日`; + } + }, + /** * 排序商品 */ sortProducts() { let sorted = [...this.data.filteredProducts]; - + switch (this.data.selectedSort) { case 0: // 最新发布 - sorted.sort((a, b) => new Date(b.publishTime) - new Date(a.publishTime)); + sorted.sort((a, b) => { + const timeA = a._originalData?.createTime || new Date(0); + const timeB = b._originalData?.createTime || new Date(0); + return new Date(timeB) - new Date(timeA); + }); break; case 1: // 价格从低到高 - sorted.sort((a, b) => parseFloat(a.price) - parseFloat(b.price)); + sorted.sort((a, b) => parseFloat(a.price || 0) - parseFloat(b.price || 0)); break; case 2: // 价格从高到低 - sorted.sort((a, b) => parseFloat(b.price) - parseFloat(a.price)); + sorted.sort((a, b) => parseFloat(b.price || 0) - parseFloat(a.price || 0)); break; - case 3: // 评分最高 - sorted.sort((a, b) => parseFloat(b.sellerRating) - parseFloat(a.sellerRating)); + case 3: // 评分最高(暂时使用固定评分) + sorted.sort((a, b) => parseFloat(b.sellerRating || 0) - parseFloat(a.sellerRating || 0)); break; } - + this.setData({ filteredProducts: sorted }); diff --git a/miniprogram/pages/buy/buy.wxml b/miniprogram/pages/buy/buy.wxml index fb9f1d4..be86615 100644 --- a/miniprogram/pages/buy/buy.wxml +++ b/miniprogram/pages/buy/buy.wxml @@ -144,8 +144,8 @@ - - + + 📦 暂无商品 换个筛选条件试试 diff --git a/miniprogram/pages/publish/publish.js b/miniprogram/pages/publish/publish.js index ebacc35..7b35782 100644 --- a/miniprogram/pages/publish/publish.js +++ b/miniprogram/pages/publish/publish.js @@ -358,218 +358,83 @@ Page({ tradeMethodIndex } = this.data; - // 获取当前用户信息并关联T_user表 - wx.cloud.callFunction({ - name: 'quickstartFunctions', - data: { - type: 'getOpenId' - }, - success: (userRes) => { - const userInfo = userRes.result || {}; - const openid = userInfo.openid || ''; - - console.log('获取到用户openid:', openid); - - // 通过云函数查询T_user表,获取用户详细信息并建立关联 - wx.cloud.callFunction({ - name: 'quickstartFunctions', - data: { - type: 'getUserByOpenId', - openid: openid - }, - success: (userQueryRes) => { - let sellerUserId = null; - let sellerUserInfo = null; - - if (userQueryRes.result && userQueryRes.result.success && userQueryRes.result.data) { - // 找到用户记录,建立关联 - const userData = userQueryRes.result.data; - sellerUserId = userData.userId; - sellerUserInfo = { - userId: userData.userId, - sno: userData.sno || '', - sname: userData.sname || '', - phone: userData.phone || '', - avatar: userData.avatar || '' - }; - console.log('找到用户记录,建立关联:', sellerUserInfo); - } else { - console.warn('未找到用户记录,仅保存openid'); - } - - // 构建商品数据 - const productData = { - // 基本信息 - productName: productName, - productCategory: productCategory, - productDescription: productDescription, - productImage: imageFileID, - - // 价格信息 - originalPrice: parseFloat(originalPrice) || 0, - suggestedPrice: parseFloat(suggestedPrice) || 0, - salePrice: parseFloat(salePrice) || 0, - priceRange: priceRange || '', - - // 商品状况 - conditionLevel: conditionLevel || '', - aiScore: aiScore || '', - analysisReport: analysisReport || '', - - // 发布信息 - contactInfo: contactInfo, - transactionMethod: transactionMethods[tradeMethodIndex] || '面交', - - // 状态信息 - status: '在售', // 商品状态:在售、已售、下架 - viewCount: 0, // 浏览数 - likeCount: 0, // 点赞数 - - // 时间信息 - createTime: new Date(), - updateTime: new Date(), - - // 用户关联信息(建立与T_user的关联) - sellerOpenId: openid, // 微信openid - sellerUserId: sellerUserId, // 关联到T_user表的_id(主要关联字段) - sellerAppId: userInfo.appid || '', - - // 用户快照信息(可选,用于快速显示,避免频繁查询) - sellerInfo: sellerUserInfo ? { - sno: sellerUserInfo.sno, - sname: sellerUserInfo.sname, - phone: sellerUserInfo.phone, - avatar: sellerUserInfo.avatar - } : null - }; - - console.log('准备保存商品数据(含用户关联):', productData); - - // 保存到数据库 - db.collection('T_product').add({ - data: productData, - success: (res) => { - console.log('商品发布成功:', res); - wx.hideLoading(); - - this.setData({ - isPublishing: false - }); - - // 显示发布成功提示 - wx.showToast({ - title: '发布成功', - icon: 'success', - duration: 2000 - }); - - // 延迟跳转到主页面 - setTimeout(() => { - wx.switchTab({ - url: '/pages/main/main' - }); - }, 1500); - }, - fail: (err) => { - console.error('商品保存失败:', err); - wx.hideLoading(); - - this.setData({ - isPublishing: false - }); - - wx.showModal({ - title: '发布失败', - content: '商品保存失败,请重试。错误信息:' + (err.errMsg || '未知错误'), - showCancel: false, - confirmText: '知道了' - }); - } - }); - }, - fail: (err) => { - console.error('查询用户信息失败:', err); - // 即使查询失败,也尝试保存商品(仅保存openid) - const productData = { - // 基本信息 - productName: productName, - productCategory: productCategory, - productDescription: productDescription, - productImage: imageFileID, - - // 价格信息 - originalPrice: parseFloat(originalPrice) || 0, - suggestedPrice: parseFloat(suggestedPrice) || 0, - salePrice: parseFloat(salePrice) || 0, - priceRange: priceRange || '', - - // 商品状况 - conditionLevel: conditionLevel || '', - aiScore: aiScore || '', - analysisReport: analysisReport || '', - - // 发布信息 - contactInfo: contactInfo, - transactionMethod: transactionMethods[tradeMethodIndex] || '面交', - - // 状态信息 - status: '在售', - viewCount: 0, - likeCount: 0, - - // 时间信息 - createTime: new Date(), - updateTime: new Date(), - - // 用户信息(仅保存openid) - sellerOpenId: openid, - sellerAppId: userInfo.appid || '', - sellerUserId: null // 关联失败,留空 - }; - - db.collection('T_product').add({ - data: productData, - success: (res) => { - console.log('商品发布成功(用户关联失败):', res); - wx.hideLoading(); - this.setData({ isPublishing: false }); - wx.showToast({ - title: '发布成功', - icon: 'success', - duration: 2000 - }); - setTimeout(() => { - wx.switchTab({ url: '/pages/main/main' }); - }, 1500); - }, - fail: (saveErr) => { - console.error('商品保存失败:', saveErr); - wx.hideLoading(); - this.setData({ isPublishing: false }); - wx.showModal({ - title: '发布失败', - content: '商品保存失败,请重试', - showCancel: false, - confirmText: '知道了' - }); - } - }); - } + // 构建商品数据 + const productData = { + // 基本信息 + productName: productName, + productCategory: productCategory, + productDescription: productDescription, + productImage: imageFileID, + + // 价格信息 + originalPrice: parseFloat(originalPrice) || 0, + suggestedPrice: parseFloat(suggestedPrice) || 0, + salePrice: parseFloat(salePrice) || 0, + priceRange: priceRange || '', + + // 商品状况 + conditionLevel: conditionLevel || '', + aiScore: aiScore || '', + analysisReport: analysisReport || '', + + // 发布信息 + contactInfo: contactInfo, + transactionMethod: transactionMethods[tradeMethodIndex] || '面交', + + // 状态信息 + status: '在售', + viewCount: 0, + likeCount: 0, + + // 时间信息 + createTime: new Date(), + updateTime: new Date(), + + // 用户信息(暂时简化) + sellerOpenId: 'test_openid', // 暂时使用测试数据 + sellerAppId: 'test_appid' + }; + + console.log('准备保存商品数据:', productData); + + // 保存到数据库 + db.collection('T_product').add({ + data: productData, + success: (res) => { + console.log('商品发布成功:', res); + wx.hideLoading(); + + this.setData({ + isPublishing: false }); - }, + + // 显示发布成功提示 + wx.showToast({ + title: '发布成功', + icon: 'success', + duration: 2000 + }); + + // 延迟跳转到主页面 + setTimeout(() => { + wx.switchTab({ + url: '/pages/main/main' + }); + }, 1500); }, fail: (err) => { - console.error('获取用户信息失败:', err); + console.error('商品保存失败:', err); wx.hideLoading(); - + this.setData({ isPublishing: false }); - wx.showToast({ - title: '获取用户信息失败', - icon: 'none', - duration: 2000 + wx.showModal({ + title: '发布失败', + content: '商品保存失败,请重试。错误信息:' + (err.errMsg || '未知错误'), + showCancel: false, + confirmText: '知道了' }); } });