diff --git a/pages/goods-update/goods-update.wxml b/pages/goods-update/goods-update.wxml index a5d6ec9..d1dfb16 100644 --- a/pages/goods-update/goods-update.wxml +++ b/pages/goods-update/goods-update.wxml @@ -192,7 +192,7 @@ class="bottom-button" bindtap="prepareUnpublishSupply" disabled="{{goodsDetail.status == 'sold_out'}}" - style="background-color: {{goodsDetail.status == 'sold_out' ? '#d9d9d9' : '#52c41a'}}; color: {{goodsDetail.status == 'sold_out' ? '#999999' : '#ffffff'}}; border: 2px solid {{goodsDetail.status == 'sold_out' ? '#d9d9d9' : '#52c41a'}}; box-shadow: {{goodsDetail.status == 'sold_out' ? 'none' : '0 2px 8px rgba(82, 196, 26, 0.2)'}}; opacity: {{goodsDetail.status == 'sold_out' ? '0.8' : '1'}};" + style="background-color: {{goodsDetail.status == 'sold_out' ? '#d9d9d9' : '#52c41a'}}; color: {{goodsDetail.status == 'sold_out' ? '#999999' : '#ffffff'}}; border: 2px solid {{goodsDetail.status == 'sold_out' ? '#d9d9d9' : '#52c41a'}}; box-shadow: {{goodsDetail.status == 'sold_out' ? 'none' : '0 2px 8px rgba(82, 196, 26, 0.2)'}}; opacity: {{goodsDetail.status == 'sold_out' ? '0.8' : '1'}}" > {{goodsDetail.status == 'sold_out' ? '已下架' : '下架'}} diff --git a/pages/index/index.js b/pages/index/index.js index 1f8a728..22f0a85 100644 --- a/pages/index/index.js +++ b/pages/index/index.js @@ -59,7 +59,7 @@ Page({ needPhoneAuth: false, testMode: true, partnerstatus: '', - + // 侧边栏相关 showSidebar: false, isDragging: false, @@ -69,22 +69,22 @@ Page({ sidebarBtnHidden: false, isPageHidden: false, hasGoodsManagePermission: false, - + // 搜索区域相关 searchSectionVisible: true, lastScrollTop: 0, isScrollLocked: false, - + // 回到顶部按钮 showBackToTop: false, scrollTop: 0, - + // 搜索相关 searchKeyword: '', selectedRegion: '全国', showRegionPicker: false, regions: ['全国', '北京', '上海', '广州', '深圳', '天津', '重庆', '河北', '山西', '辽宁', '吉林', '黑龙江', '江苏', '浙江', '安徽', '福建', '江西', '山东', '河南', '湖北', '湖南', '广东', '海南', '四川', '贵州', '云南', '陕西', '甘肃', '青海', '台湾', '内蒙古', '广西', '西藏', '宁夏', '新疆', '香港', '澳门'], - + // 商品相关 - 淘宝风格 goods: [], filteredGoods: [], @@ -95,25 +95,25 @@ Page({ page: 1, pageSize: 8, soldOutPage: 1, - + // 商品数据缓存 goodsCache: [], categoryQueryCache: {}, lastDataTimestamp: 0, cacheValidDuration: 5 * 60 * 1000, // 缓存有效期5分钟 - + // sold_out 加载状态 isQueryingSoldOut: false, soldOutPage: 1, soldOutPageSize: 8, publishedHasMore: true, - + // 防抖定时器 searchDebounceTimer: null, scrollDebounceTimer: null, isRefreshing: false, isLoading: true, - + // 图片预览相关状态 previewImageUrls: [], previewImageIndex: 0, @@ -124,10 +124,10 @@ Page({ navigateToChat() { wx.navigateTo({ url: '/pages/chat/index', - success: function() { + success: function () { console.log('成功跳转到聊天页面'); }, - fail: function(error) { + fail: function (error) { console.error('跳转到聊天页面失败:', error); wx.showToast({ title: '跳转失败,请稍后重试', @@ -143,10 +143,10 @@ Page({ const userType = e.currentTarget.dataset.type; wx.navigateTo({ url: `/pages/customer-service/index?type=${userType}`, - success: function() { + success: function () { console.log('成功跳转到客服列表页面,类型:', userType); }, - fail: function(error) { + fail: function (error) { console.error('跳转到客服列表页面失败:', error); wx.showToast({ title: '跳转失败,请稍后重试', @@ -160,10 +160,10 @@ Page({ navigateToSettlement() { wx.navigateTo({ url: '/pages/settlement/index', - success: function() { + success: function () { console.log('成功跳转到我要卖蛋页面'); }, - fail: function(error) { + fail: function (error) { console.error('跳转到我要卖蛋页面失败:', error); wx.showToast({ title: '跳转失败,请稍后重试', @@ -172,30 +172,30 @@ Page({ } }); }, - + // 切换侧边栏显示 toggleSidebar() { if (this.data.isDragging) { return; } - + const newShowSidebar = !this.data.showSidebar; - + if (newShowSidebar) { this.checkGoodsManagePermission(); } - + this.setData({ showSidebar: newShowSidebar }); }, - + // 检查用户是否有货源管理权限 checkGoodsManagePermission() { const users = wx.getStorageSync('users') || {}; const userId = wx.getStorageSync('userId'); let userPhone = null; - + if (userId && users[userId] && users[userId].phoneNumber) { userPhone = users[userId].phoneNumber; } else { @@ -206,13 +206,13 @@ Page({ userPhone = wx.getStorageSync('phoneNumber'); } } - + if (!userPhone) { console.log('用户未绑定手机号,无货源管理权限'); this.setData({ hasGoodsManagePermission: false }); return; } - + API.checkPersonnelByPhone(userPhone).then(res => { console.log('货源管理权限检查结果:', res); this.setData({ hasGoodsManagePermission: res.exists }); @@ -221,7 +221,7 @@ Page({ this.setData({ hasGoodsManagePermission: false }); }); }, - + // 切换按钮显示/隐藏到侧边栏 toggleSidebarBtn() { this.setData({ @@ -229,7 +229,7 @@ Page({ }); wx.setStorageSync('sidebarBtnHidden', !this.data.sidebarBtnHidden); }, - + // 触摸开始事件 handleTouchStart(e) { this.setData({ @@ -237,46 +237,46 @@ Page({ startY: e.touches[0].clientY }); }, - + // 触摸移动事件 handleTouchMove(e) { const moveY = e.touches[0].clientY; const diffY = moveY - this.data.startY; - + if (Math.abs(diffY) > 20) { this.setData({ isDragging: true }); - + let newTop = this.data.sidebarBtnTop + diffY * 3; - + const systemInfo = wx.getSystemInfoSync(); const screenHeight = systemInfo.screenHeight * 2; const btnHeight = 90; - + const minTop = screenHeight * 0.2; const maxTop = screenHeight * 0.6; - + if (newTop < minTop) { newTop = minTop; } else if (newTop > maxTop) { newTop = maxTop; } - + this.setData({ sidebarBtnTop: newTop, startY: moveY }); } }, - + // 触摸结束事件 handleTouchEnd(e) { // 如果拖动距离超过屏幕高度的1/3,隐藏按钮 const moveY = e.changedTouches[0].clientY; const diffY = moveY - this.data.startY; const screenHeight = wx.getSystemInfoSync().screenHeight * 2; // 转换为rpx - + if (Math.abs(diffY) > screenHeight / 3) { this.setData({ sidebarBtnTop: -100 // 隐藏按钮 @@ -287,7 +287,7 @@ Page({ wx.setStorageSync('sidebarBtnTop', this.data.sidebarBtnTop); wx.setStorageSync('sidebarBtnHidden', false); } - + this.setData({ isDragging: false }); @@ -298,17 +298,17 @@ Page({ const systemInfo = wx.getSystemInfoSync(); const isIOS = systemInfo.system.toLowerCase().includes('ios'); const screenHeight = systemInfo.screenHeight * 2; - + // 设置iOS特定标志 if (isIOS) { this.setData({ isIOS: true }); } - + const savedBtnTop = wx.getStorageSync('sidebarBtnTop'); const savedBtnHidden = wx.getStorageSync('sidebarBtnHidden'); - + let defaultTop = screenHeight * 0.5; if (savedBtnTop !== '' && savedBtnTop !== -100) { const minTop = screenHeight * 0.2; @@ -317,7 +317,7 @@ Page({ defaultTop = savedBtnTop; } } - + this.setData({ sidebarBtnTop: defaultTop, sidebarBtnHidden: false, @@ -327,7 +327,7 @@ Page({ this.checkAndRestoreLoginStatus() this.loadCategories() this.loadGoods() - + // 计算搜索区域高度 setTimeout(() => { const query = wx.createSelectorQuery(); @@ -338,7 +338,7 @@ Page({ const searchHeight = res[0].height; const categoryHeight = res[1].height; const totalHeight = searchHeight + categoryHeight; - + this.setData({ searchSectionHeight: searchHeight, categorySectionHeight: categoryHeight, @@ -347,12 +347,12 @@ Page({ } }); }, 500); - + // 添加收藏状态变化事件监听 const app = getApp(); this.favoriteChangedHandler = (data) => { console.log('收到收藏状态变化通知:', data); - + // 更新商品列表中对应商品的收藏状态 const updatedGoods = this.data.goods.map(item => { if (String(item.id || item.productId) === data.productId) { @@ -363,16 +363,16 @@ Page({ } return item; }); - + this.setData({ goods: updatedGoods - }, () => { - // 重新应用筛选条件,确保显示的商品收藏状态也更新 - const filteredGoods = this.applyFilters(this.data.goods, false); - this.setData({ - filteredGoods: filteredGoods, - }); + }, () => { + // 重新应用筛选条件,确保显示的商品收藏状态也更新 + const filteredGoods = this.applyFilters(this.data.goods, false); + this.setData({ + filteredGoods: filteredGoods, }); + }); }; app.eventBus.on('favoriteChanged', this.favoriteChangedHandler); }, @@ -386,9 +386,9 @@ Page({ const app = getApp(); app.updateCurrentTab('index'); app.globalData.showTabBar = true; - + const savedBtnHidden = wx.getStorageSync('sidebarBtnHidden'); - + // 只有在返回时才恢复按钮状态(刷新页面不恢复) if (this.data.isPageHidden) { this.setData({ @@ -396,12 +396,12 @@ Page({ isPageHidden: false }); } - + this.setData({ isSearchBarFullyHidden: false, lastScrollTop: 0 }); - + this.checkAndRestoreLoginStatus() }, @@ -411,7 +411,7 @@ Page({ isPageHidden: true }); }, - + onUnload: function () { // 页面卸载时移除收藏状态变化事件监听 const app = getApp(); @@ -421,23 +421,23 @@ Page({ } }, - onPullDownRefresh: function() { + onPullDownRefresh: function () { this.onRefresh() }, - onRestore: function() { + onRestore: function () { this.setData({ isRefreshing: false }) }, - onRefresh: function() { + onRefresh: function () { if (this.data.isRefreshing) { return } - + const existingGoods = [...this.data.goods] - + this.setData({ isRefreshing: true, page: 1, @@ -449,12 +449,12 @@ Page({ categoryQueryCache: {}, lastDataTimestamp: 0, }) - + const timestamp = new Date().getTime(); const currentCategory = this.data.selectedCategory === '全部' ? '' : this.data.selectedCategory; const currentKeyword = this.data.searchKeyword; const pageSize = this.data.pageSize; - + // 强制刷新:清除所有缓存并重新从数据库加载 this.setData({ // 清除商品数据缓存 @@ -462,9 +462,9 @@ Page({ // 重置缓存时间戳 lastDataTimestamp: 0 }); - - // 优先查询published状态的商品,如果有搜索关键词则同时查询sold_out状态 - const statusList = currentKeyword ? ['published', 'sold_out'] : ['published']; + + // 查询published和sold_out状态的商品 + const statusList = ['published', 'sold_out']; const apiParams = { timestamp: timestamp, viewMode: 'shopping', @@ -477,81 +477,81 @@ Page({ apiParams.category = currentCategory } API.getProductList(statusList, apiParams) - .then(res => { - this.setData({ isRefreshing: false }) - - if (res.success && res.products) { - this.processRefreshData(res.products, existingGoods) - wx.showToast({ - title: '刷新成功', - icon: 'success', - duration: 1500 - }) - } else if (res.products.length === 0) { - // 如果published状态没有商品,则查询sold_out状态 - console.log('没有published状态的商品,查询sold_out状态的商品'); - const apiParams = { - timestamp: timestamp, - viewMode: 'shopping', - page: 1, - pageSize: pageSize, - keyword: currentKeyword - } - // 只有非全部分类时才传递category参数 - if (currentCategory) { - apiParams.category = currentCategory - } - API.getProductList(['sold_out'], apiParams) - .then(soldOutRes => { - this.setData({ isRefreshing: false }); - - if (soldOutRes.success && soldOutRes.products && soldOutRes.products.length > 0) { - this.processRefreshData(soldOutRes.products, existingGoods); + .then(res => { + this.setData({ isRefreshing: false }) + + if (res.success && res.products) { + this.processRefreshData(res.products, existingGoods) + wx.showToast({ + title: '刷新成功', + icon: 'success', + duration: 1500 + }) + } else if (res.products.length === 0) { + // 如果published状态没有商品,则查询sold_out状态 + console.log('没有published状态的商品,查询sold_out状态的商品'); + const apiParams = { + timestamp: timestamp, + viewMode: 'shopping', + page: 1, + pageSize: pageSize, + keyword: currentKeyword + } + // 只有非全部分类时才传递category参数 + if (currentCategory) { + apiParams.category = currentCategory + } + API.getProductList(['sold_out'], apiParams) + .then(soldOutRes => { + this.setData({ isRefreshing: false }); + + if (soldOutRes.success && soldOutRes.products && soldOutRes.products.length > 0) { + this.processRefreshData(soldOutRes.products, existingGoods); + wx.showToast({ + title: '刷新成功', + icon: 'success', + duration: 1500 + }); + } else { + this.setData({ + isLoading: false, + loadingMore: false + }); + } + }) + .catch(err => { + this.setData({ isRefreshing: false }); + console.error('刷新sold_out商品数据失败:', err); wx.showToast({ - title: '刷新成功', - icon: 'success', - duration: 1500 + title: '刷新失败,请稍后重试', + icon: 'none', + duration: 2000 }); - } else { - this.setData({ - isLoading: false, - loadingMore: false - }); - } + }); + } else { + this.setData({ + isLoading: false, + loadingMore: false }) - .catch(err => { - this.setData({ isRefreshing: false }); - console.error('刷新sold_out商品数据失败:', err); - wx.showToast({ - title: '刷新失败,请稍后重试', - icon: 'none', - duration: 2000 - }); - }); - } else { - this.setData({ - isLoading: false, - loadingMore: false + } + }) + .catch(err => { + this.setData({ isRefreshing: false }) + console.error('刷新商品数据失败:', err) + wx.showToast({ + title: '刷新失败,请稍后重试', + icon: 'none', + duration: 2000 }) - } - }) - .catch(err => { - this.setData({ isRefreshing: false }) - console.error('刷新商品数据失败:', err) - wx.showToast({ - title: '刷新失败,请稍后重试', - icon: 'none', - duration: 2000 }) - }) }, - onReachBottom: function() { + onReachBottom: function () { this.loadGoods(true) }, // 格式化毛重显示的辅助函数 - formatGrossWeight: function(grossWeight, weight) { + formatGrossWeight: function (grossWeight, weight) { if (grossWeight !== null && grossWeight !== undefined && grossWeight !== '') { return grossWeight; } @@ -560,18 +560,18 @@ Page({ } return ""; }, - + // 提取地区中的省份信息 - extractProvince: function(region) { + extractProvince: function (region) { if (!region || typeof region !== 'string') { return region; } - + const provinceEndIndex = region.indexOf('省'); const autonomousRegionEndIndex = region.indexOf('自治区'); const municipalityEndIndex = region.indexOf('市'); const specialRegionEndIndex = region.indexOf('特别行政区'); - + if (provinceEndIndex !== -1) { return region.substring(0, provinceEndIndex + 1); } else if (autonomousRegionEndIndex !== -1) { @@ -581,12 +581,12 @@ Page({ } else if (municipalityEndIndex === 2) { return region.substring(0, municipalityEndIndex + 1); } - + return region; }, - + // 格式化商品规格显示 - 只显示前两个,后面加... - formatSpecification: function(spec, yolk) { + formatSpecification: function (spec, yolk) { if (!spec || spec === '无') { return { displaySpec: '无', @@ -597,7 +597,7 @@ Page({ // 按常见的分隔符分割规格 const separators = [',', ',', '、', '|', ';', ';']; let parts = [spec]; - + for (let separator of separators) { if (spec.includes(separator)) { parts = spec.split(separator); @@ -612,7 +612,7 @@ Page({ .slice(0, 2); let displaySpec = cleanParts.join(' | '); - + // 如果原规格分割后超过两个部分,添加省略号 if (cleanParts.length < parts.filter(part => part.trim() && part.trim() !== '无').length) { displaySpec += '...'; @@ -625,14 +625,14 @@ Page({ }, // 处理商品数据 - 淘宝风格 - processGoodsData: function(products, isLoadMore = false) { + processGoodsData: function (products, isLoadMore = false) { let newGoods = products.map(product => { const imageUrls = product.imageUrls || product.images || []; const formattedImageUrls = Array.isArray(imageUrls) ? imageUrls : [imageUrls]; - + // 确保商品ID的一致性 const productId = product.productId || product.id; - + // 预处理媒体URL,添加类型信息 const mediaItems = formattedImageUrls.map(url => { return { @@ -640,7 +640,7 @@ Page({ type: isVideoUrl(url) ? 'video' : 'image' }; }); - + // 计算库存总数 - 支持逗号分隔的数字字符串 const calculateTotalStock = (value) => { if (!value) return 0; @@ -658,11 +658,11 @@ Page({ const inventory = calculateTotalStock(product.inventory); const availableStock = calculateTotalStock(product.availableStock); const totalAvailable = calculateTotalStock(product.totalAvailable); - + // 优先使用最具体的库存字段 const primaryStock = quantity || minOrder || stock || inventory || availableStock || totalAvailable; const totalStock = primaryStock; - + // 智能库存显示 - 库存>=10000显示"库存充足",库存=0显示"暂无",其他显示具体数字 let displayStock; if (totalStock >= 10000) { @@ -710,10 +710,10 @@ Page({ displayYolk: formattedSpec.displayYolk // 格式化后的蛋黄 } }) - + // 过滤隐藏状态的商品 newGoods = newGoods.filter(item => (item.status || '').toLowerCase() !== 'hidden') - + // 先对新商品进行内部查重 const uniqueNewGoodsMap = new Map(); newGoods.forEach(item => { @@ -722,10 +722,10 @@ Page({ } }); newGoods = Array.from(uniqueNewGoodsMap.values()); - + // 更新商品的收藏状态 this.updateGoodsFavoriteStatus(newGoods, isLoadMore) - + // 只在第一页或刷新时在商品列表最前面插入广告,且只插入一次 let adSlotsAdded = false; if ((!isLoadMore || this.data.page === 1) && newGoods.length > 0) { @@ -748,11 +748,11 @@ Page({ isAd: true } ]; - + newGoods = [...adSlots, ...newGoods]; adSlotsAdded = true; } - + let updatedGoods = [] if (isLoadMore) { // 加载更多时,去重处理 @@ -763,10 +763,10 @@ Page({ // 首次加载或切换分类时,直接使用去重后的新商品 updatedGoods = newGoods } - + const filteredGoods = this.applyFilters(updatedGoods, false) const groupedGoods = this.groupGoodsForStaggeredLayout(filteredGoods); - + this.setData({ goods: updatedGoods, filteredGoods: filteredGoods, @@ -778,16 +778,16 @@ Page({ lastDataTimestamp: new Date().getTime() }) }, - + // 处理刷新数据 - 查重并保持原有商品 - processRefreshData: function(newProducts, existingGoods) { + processRefreshData: function (newProducts, existingGoods) { let newGoods = newProducts.map(product => { const imageUrls = product.imageUrls || product.images || []; const formattedImageUrls = Array.isArray(imageUrls) ? imageUrls : [imageUrls]; - + // 确保商品ID的一致性 const productId = product.productId || product.id; - + return { ...product, id: productId, // 统一使用id字段 @@ -813,9 +813,9 @@ Page({ imageUrls: formattedImageUrls } }) - + newGoods = newGoods.filter(item => (item.status || '').toLowerCase() !== 'hidden') - + // 对新商品进行内部查重 const newGoodsMap = new Map(); newGoods.forEach(item => { @@ -824,21 +824,21 @@ Page({ } }); newGoods = Array.from(newGoodsMap.values()); - + // 移除与现有商品重复的新商品(包括广告和普通商品) const existingIds = new Set(existingGoods.map(item => item.id)); const uniqueNewGoods = newGoods.filter(item => !existingIds.has(item.id)); - + // 合并现有商品和去重后的新商品 const updatedGoods = [...existingGoods, ...uniqueNewGoods] - + const filteredGoods = this.applyFilters(updatedGoods, false) const groupedGoods = this.groupGoodsForStaggeredLayout(filteredGoods); - + const currentCategory = this.data.selectedCategory === '全部' ? '' : this.data.selectedCategory; const currentKeyword = this.data.searchKeyword; const cacheKey = `${currentCategory}_${currentKeyword}`; - + this.setData({ goods: updatedGoods, filteredGoods: filteredGoods, @@ -849,7 +849,7 @@ Page({ // 更新缓存时间戳 lastDataTimestamp: new Date().getTime() }) - + // 更新分类查询缓存 const newCategoryQueryCache = { ...this.data.categoryQueryCache }; newCategoryQueryCache[cacheKey] = updatedGoods; @@ -857,11 +857,11 @@ Page({ categoryQueryCache: newCategoryQueryCache }) }, - + // 插入广告位数据 - insertAdSlots: function(goods) { + insertAdSlots: function (goods) { if (!goods || goods.length === 0) return goods - + const adSlot1 = { id: 'ad_slot_1', name: '广告位1', @@ -870,7 +870,7 @@ Page({ adType: 'full_card', isAd: true } - + const adSlot2 = { id: 'ad_slot_2', name: '广告位2', @@ -879,26 +879,26 @@ Page({ adType: 'half_image', isAd: true } - + return [adSlot1, adSlot2, ...goods] }, - + // 广告点击事件处理 - onAdClick: function(e) { + onAdClick: function (e) { const adSlot = e.currentTarget.dataset.ad; let imageSrc = e.currentTarget.dataset.src; - + // 如果没有从data-src获取到,尝试从图片元素直接获取src if (!imageSrc) { imageSrc = e.currentTarget.src; } - + console.log('广告被点击, 广告位:', adSlot); console.log('广告图片路径:', imageSrc); - + // 直接预览广告图片(单击触发) const validImageUrls = [imageSrc]; - + if (validImageUrls.length > 0 && validImageUrls[0]) { this.setData({ previewImageUrls: validImageUrls, @@ -914,9 +914,9 @@ Page({ }); } }, - + // 加载商品分类列表 - loadCategories: function() { + loadCategories: function () { API.getProductCategories().then(categories => { if (categories && categories.length > 0) { this.setData({ @@ -927,50 +927,50 @@ Page({ console.error('加载分类失败:', err); }); }, - + // 加载商品数据 - 优化版带缓存,支持状态优先级 - loadGoods: function(isLoadMore = false, forceRefresh = false) { + loadGoods: function (isLoadMore = false, forceRefresh = false) { if (isLoadMore && !this.data.hasMoreData) { return } - + console.log('loadGoods - 开始加载商品,isLoadMore:', isLoadMore, 'forceRefresh:', forceRefresh); console.log('loadGoods - 当前搜索关键词:', this.data.searchKeyword); console.log('loadGoods - 当前分类:', this.data.selectedCategory); - + const currentCategory = this.data.selectedCategory === '全部' ? '' : this.data.selectedCategory; const currentKeyword = this.data.searchKeyword; const cacheKey = `${currentCategory}_${currentKeyword}`; const now = new Date().getTime(); const timestamp = new Date().getTime(); - + // 如果正在加载sold_out,继续加载sold_out if (isLoadMore && this.data.isQueryingSoldOut) { this.loadSoldOutData(cacheKey, currentKeyword, currentCategory, timestamp, isLoadMore); return; } - + // 只有非加载更多模式才使用缓存 - if (!isLoadMore && !forceRefresh && - this.data.categoryQueryCache[cacheKey] && - (now - this.data.lastDataTimestamp) < this.data.cacheValidDuration) { + if (!isLoadMore && !forceRefresh && + this.data.categoryQueryCache[cacheKey] && + (now - this.data.lastDataTimestamp) < this.data.cacheValidDuration) { // 使用缓存数据 const cachedGoods = this.data.categoryQueryCache[cacheKey]; this.setData({ lastDataTimestamp: now }); this.processCachedGoods(cachedGoods, isLoadMore); return; } - + // 筛选时不显示骨架屏 if (isLoadMore) { this.setData({ loadingMore: true }) } else if (!forceRefresh) { // 只有非筛选的首次加载才显示骨架屏 this.setData({ isLoading: true, publishedHasMore: true, soldOutPage: 1 }) } - + const page = isLoadMore ? this.data.page : 1 const pageSize = this.data.pageSize; - + // 构建API请求参数 const apiParams = { timestamp: timestamp, @@ -983,105 +983,105 @@ Page({ if (currentCategory) { apiParams.category = currentCategory } - + console.log('loadGoods - API请求参数:', apiParams); - - // 在搜索时同时查询published和sold_out状态的商品,否则只查询published - const statusList = this.data.searchKeyword ? ['published', 'sold_out'] : ['published']; + + // 查询published和sold_out状态的商品 + const statusList = ['published', 'sold_out']; console.log('loadGoods - 查询状态列表:', statusList); - + API.getProductList(statusList, apiParams) - .then(res => { - wx.hideLoading(); - - console.log(`===== ${statusList.join(', ')}状态查询结果 =====`); - console.log('res.success:', res.success); - console.log('res.products:', res.products); - console.log('res.products.length:', res.products ? res.products.length : 'undefined'); - console.log('page:', page); - - // 如果有published商品,直接处理 - if (res.success && res.products && res.products.length > 0) { - console.log('有published商品,处理商品数据'); - const totalGoods = res.total || 0; - const totalPages = res.totalPages || Math.ceil(totalGoods / pageSize); - // 只需要判断是否还有下一页,不需要检查当前页数据量是否等于pageSize - const publishedHasMore = page < totalPages; - - // 当published商品没有更多数据时,查询sold_out商品 - const shouldQuerySoldOut = !publishedHasMore; - - // 更新缓存(加载更多时追加数据) - const updatedCache = { ...this.data.categoryQueryCache }; - if (isLoadMore && updatedCache[cacheKey]) { - // 追加新数据到缓存 - const existingIds = new Set(updatedCache[cacheKey].map(item => item.id)); - const newProducts = res.products.filter(item => !existingIds.has(item.id)); - updatedCache[cacheKey] = [...updatedCache[cacheKey], ...newProducts]; - } else { - // 首次加载或刷新时替换缓存 - updatedCache[cacheKey] = res.products; - } + .then(res => { + wx.hideLoading(); - // 计算sold_out起始页码和每页数量 - let soldOutPageNum = 1; - let soldOutPageSize = pageSize; - if (shouldQuerySoldOut || (!publishedHasMore && isLoadMore)) { - // 如果published已无更多数据,查询sold_out商品 - soldOutPageNum = isLoadMore ? this.data.soldOutPage + 1 : 1; - soldOutPageSize = pageSize; - } + console.log(`===== ${statusList.join(', ')}状态查询结果 =====`); + console.log('res.success:', res.success); + console.log('res.products:', res.products); + console.log('res.products.length:', res.products ? res.products.length : 'undefined'); + console.log('page:', page); + + // 如果有published商品,直接处理 + if (res.success && res.products && res.products.length > 0) { + console.log('有published商品,处理商品数据'); + const totalGoods = res.total || 0; + const totalPages = res.totalPages || Math.ceil(totalGoods / pageSize); + // 只需要判断是否还有下一页,不需要检查当前页数据量是否等于pageSize + const publishedHasMore = page < totalPages; + + // 当published商品没有更多数据时,查询sold_out商品 + const shouldQuerySoldOut = !publishedHasMore; + + // 更新缓存(加载更多时追加数据) + const updatedCache = { ...this.data.categoryQueryCache }; + if (isLoadMore && updatedCache[cacheKey]) { + // 追加新数据到缓存 + const existingIds = new Set(updatedCache[cacheKey].map(item => item.id)); + const newProducts = res.products.filter(item => !existingIds.has(item.id)); + updatedCache[cacheKey] = [...updatedCache[cacheKey], ...newProducts]; + } else { + // 首次加载或刷新时替换缓存 + updatedCache[cacheKey] = res.products; + } - this.setData({ - hasMoreData: publishedHasMore || (shouldQuerySoldOut || this.data.isQueryingSoldOut), - isQueryingSoldOut: shouldQuerySoldOut || (!publishedHasMore && isLoadMore), - publishedHasMore: publishedHasMore, - soldOutPage: soldOutPageNum, - soldOutPageSize: soldOutPageSize, - categoryQueryCache: updatedCache, - lastDataTimestamp: now, - goodsCache: updatedCache[cacheKey] - }); - - this.processGoodsData(res.products, isLoadMore); + // 计算sold_out起始页码和每页数量 + let soldOutPageNum = 1; + let soldOutPageSize = pageSize; + if (shouldQuerySoldOut || (!publishedHasMore && isLoadMore)) { + // 如果published已无更多数据,查询sold_out商品 + soldOutPageNum = isLoadMore ? this.data.soldOutPage + 1 : 1; + soldOutPageSize = pageSize; + } - // 如果需要查询sold_out - if (this.data.isQueryingSoldOut) { + this.setData({ + hasMoreData: publishedHasMore || (shouldQuerySoldOut || this.data.isQueryingSoldOut), + isQueryingSoldOut: shouldQuerySoldOut || (!publishedHasMore && isLoadMore), + publishedHasMore: publishedHasMore, + soldOutPage: soldOutPageNum, + soldOutPageSize: soldOutPageSize, + categoryQueryCache: updatedCache, + lastDataTimestamp: now, + goodsCache: updatedCache[cacheKey] + }); + + this.processGoodsData(res.products, isLoadMore); + + // 如果需要查询sold_out + if (this.data.isQueryingSoldOut) { + this.loadSoldOutData(cacheKey, currentKeyword, currentCategory, timestamp, isLoadMore); + } + + return; + } + + // 如果没有published商品,查询sold_out状态 + if (page === 1) { + console.log('没有published商品,查询sold_out状态'); + console.log('查询参数 - page:', page, 'pageSize:', pageSize, 'keyword:', currentKeyword, 'category:', currentCategory); + this.setData({ isQueryingSoldOut: true, soldOutPage: 1, soldOutPageSize: pageSize }); this.loadSoldOutData(cacheKey, currentKeyword, currentCategory, timestamp, isLoadMore); + return; + } else { + this.setData({ loadingMore: false, isLoading: false }); } - - return; - } - - // 如果没有published商品,查询sold_out状态 - if (page === 1) { - console.log('没有published商品,查询sold_out状态'); - console.log('查询参数 - page:', page, 'pageSize:', pageSize, 'keyword:', currentKeyword, 'category:', currentCategory); - this.setData({ isQueryingSoldOut: true, soldOutPage: 1, soldOutPageSize: pageSize }); - this.loadSoldOutData(cacheKey, currentKeyword, currentCategory, timestamp, isLoadMore); - return; - } else { - this.setData({ loadingMore: false, isLoading: false }); - } - }) - .catch(err => { - console.error('加载商品数据失败:', err); - this.setData({ - loadingMore: false, - isLoading: false, - isRefreshing: false - }); - }) + }) + .catch(err => { + console.error('加载商品数据失败:', err); + this.setData({ + loadingMore: false, + isLoading: false, + isRefreshing: false + }); + }) }, - + // 加载sold_out数据 - loadSoldOutData: function(cacheKey, currentKeyword, currentCategory, timestamp, isLoadMore) { + loadSoldOutData: function (cacheKey, currentKeyword, currentCategory, timestamp, isLoadMore) { const pageSize = this.data.soldOutPageSize || 8; const soldOutPageNum = this.data.soldOutPage || 1; - + console.log('加载sold_out数据 - page:', soldOutPageNum, 'pageSize:', pageSize); console.log('查询参数 - page:', soldOutPageNum, 'pageSize:', pageSize, 'keyword:', currentKeyword, 'category:', currentCategory); - + const apiParams = { timestamp: timestamp, viewMode: 'shopping', @@ -1094,71 +1094,71 @@ Page({ apiParams.category = currentCategory } API.getProductList(['sold_out'], apiParams) - .then(soldOutRes => { - console.log('===== sold_out状态查询结果 ====='); - console.log('soldOutRes.success:', soldOutRes.success); - console.log('soldOutRes.products:', soldOutRes.products); - console.log('soldOutRes.products.length:', soldOutRes.products ? soldOutRes.products.length : 'undefined'); - - if (soldOutRes.success && soldOutRes.products && soldOutRes.products.length > 0) { - const soldOutTotal = soldOutRes.total || 0; - const soldOutTotalPages = soldOutRes.totalPages || Math.ceil(soldOutTotal / pageSize); - const soldOutHasMore = soldOutPageNum < soldOutTotalPages && soldOutRes.products.length >= pageSize; - - // 更新缓存 - const updatedCache = { ...this.data.categoryQueryCache }; - const existingCache = updatedCache[cacheKey] || []; - const existingIds = new Set(existingCache.map(item => item.id)); - const uniqueSoldOutProducts = soldOutRes.products.filter(item => !existingIds.has(item.id)); - - updatedCache[cacheKey] = [...existingCache, ...uniqueSoldOutProducts]; - + .then(soldOutRes => { + console.log('===== sold_out状态查询结果 ====='); + console.log('soldOutRes.success:', soldOutRes.success); + console.log('soldOutRes.products:', soldOutRes.products); + console.log('soldOutRes.products.length:', soldOutRes.products ? soldOutRes.products.length : 'undefined'); + + if (soldOutRes.success && soldOutRes.products && soldOutRes.products.length > 0) { + const soldOutTotal = soldOutRes.total || 0; + const soldOutTotalPages = soldOutRes.totalPages || Math.ceil(soldOutTotal / pageSize); + const soldOutHasMore = soldOutPageNum < soldOutTotalPages && soldOutRes.products.length >= pageSize; + + // 更新缓存 + const updatedCache = { ...this.data.categoryQueryCache }; + const existingCache = updatedCache[cacheKey] || []; + const existingIds = new Set(existingCache.map(item => item.id)); + const uniqueSoldOutProducts = soldOutRes.products.filter(item => !existingIds.has(item.id)); + + updatedCache[cacheKey] = [...existingCache, ...uniqueSoldOutProducts]; + + this.setData({ + hasMoreData: soldOutHasMore, + isQueryingSoldOut: soldOutHasMore, + soldOutPage: soldOutPageNum + 1, + categoryQueryCache: updatedCache, + lastDataTimestamp: new Date().getTime(), + goodsCache: updatedCache[cacheKey] + }); + + this.processGoodsData(updatedCache[cacheKey], isLoadMore); + console.log('sold_out数据加载完成,总商品数:', updatedCache[cacheKey].length, 'hasMoreData:', soldOutHasMore); + } else { + console.log('没有找到更多sold_out商品'); + this.setData({ + isQueryingSoldOut: false, + hasMoreData: false, + loadingMore: false, + isLoading: false + }); + } + }) + .catch(err => { + console.error('加载sold_out数据失败:', err); this.setData({ - hasMoreData: soldOutHasMore, - isQueryingSoldOut: soldOutHasMore, - soldOutPage: soldOutPageNum + 1, - categoryQueryCache: updatedCache, - lastDataTimestamp: new Date().getTime(), - goodsCache: updatedCache[cacheKey] - }); - - this.processGoodsData(updatedCache[cacheKey], isLoadMore); - console.log('sold_out数据加载完成,总商品数:', updatedCache[cacheKey].length, 'hasMoreData:', soldOutHasMore); - } else { - console.log('没有找到更多sold_out商品'); - this.setData({ - isQueryingSoldOut: false, - hasMoreData: false, - loadingMore: false, - isLoading: false + isQueryingSoldOut: false, + loadingMore: false, + isLoading: false, + isRefreshing: false }); - } - }) - .catch(err => { - console.error('加载sold_out数据失败:', err); - this.setData({ - isQueryingSoldOut: false, - loadingMore: false, - isLoading: false, - isRefreshing: false }); - }); }, - + // 处理缓存的商品数据 - processCachedGoods: function(cachedGoods, isLoadMore) { + processCachedGoods: function (cachedGoods, isLoadMore) { + - // 处理商品数据格式并去重 const goodsMap = new Map(); - + cachedGoods.forEach(product => { const imageUrls = product.imageUrls || product.images || []; const formattedImageUrls = Array.isArray(imageUrls) ? imageUrls : [imageUrls]; - + // 确保商品ID的一致性 const productId = product.productId || product.id; - + // 只有当商品ID不存在时才添加,避免重复 if (!goodsMap.has(productId)) { // 计算库存总数 - 支持逗号分隔的数字字符串 @@ -1178,11 +1178,11 @@ Page({ const inventory = calculateTotalStock(product.inventory); const availableStock = calculateTotalStock(product.availableStock); const totalAvailable = calculateTotalStock(product.totalAvailable); - + // 优先使用最具体的库存字段 const primaryStock = quantity || minOrder || stock || inventory || availableStock || totalAvailable; const totalStock = primaryStock; - + // 智能库存显示 - 库存>=10000显示"库存充足",库存=0显示"暂无",其他显示具体数字 let displayStock; if (totalStock >= 10000) { @@ -1222,21 +1222,21 @@ Page({ totalStock: displayStock, // 使用优化后的库存显示值 originalTotalStock: totalStock // 保留原始计算值用于调试 }; - + goodsMap.set(productId, processedProduct); } }); - + // 转换为数组 const processedGoods = Array.from(goodsMap.values()); - + // 更新收藏状态 this.updateGoodsFavoriteStatus(processedGoods, false); - + // 应用筛选条件 const filteredGoods = this.applyFilters(processedGoods, false); const groupedGoods = this.groupGoodsForStaggeredLayout(filteredGoods); - + this.setData({ goods: processedGoods, filteredGoods: filteredGoods, @@ -1247,9 +1247,9 @@ Page({ hasMoreData: false // 缓存数据不分页 }); }, - + // 刷新商品列表 - 强制刷新机制 - refreshGoodsList: function() { + refreshGoodsList: function () { this.setData({ page: 1, hasMoreData: true, @@ -1265,41 +1265,41 @@ Page({ this.loadGoods(false, true); // 第二个参数true表示强制刷新 }) }, - + // 统一字段长度 - normalizeFieldLength: function(item) { + normalizeFieldLength: function (item) { const normalized = { ...item } - + // 统一 name 字段长度为 20 字符 if (normalized.name) { - normalized.name = normalized.name.length > 20 ? - normalized.name.substring(0, 17) + '...' : + normalized.name = normalized.name.length > 20 ? + normalized.name.substring(0, 17) + '...' : normalized.name.padEnd(20, ' ') } - + // 统一 region 字段长度为 15 字符 if (normalized.region) { - normalized.region = normalized.region.length > 15 ? - normalized.region.substring(0, 12) + '...' : + normalized.region = normalized.region.length > 15 ? + normalized.region.substring(0, 12) + '...' : normalized.region.padEnd(15, ' ') } - + // 统一 grossWeight 字段长度为 10 字符 if (normalized.grossWeight) { - normalized.grossWeight = normalized.grossWeight.length > 10 ? - normalized.grossWeight.substring(0, 7) + '...' : + normalized.grossWeight = normalized.grossWeight.length > 10 ? + normalized.grossWeight.substring(0, 7) + '...' : normalized.grossWeight.padEnd(10, ' ') } - + return normalized }, // 应用筛选条件 - applyFilters: function(goods, shouldSort = true) { + applyFilters: function (goods, shouldSort = true) { let filtered = [...goods] - + console.log('applyFilters - 开始过滤,原始商品数量:', goods.length, '关键词:', this.data.searchKeyword); - + // 筛选条件:销售价为空并且没有联系人信息的不显示在主页上 filtered = filtered.filter(item => { // 广告位不受影响 @@ -1313,19 +1313,19 @@ Page({ // 只保留:销售价不为空 或 有联系人信息 的商品 return !(hasEmptyPrice && hasNoContact); }); - + if (this.data.selectedCategory !== '全部') { const category = this.data.selectedCategory filtered = filtered.filter(item => item.isAd || (item.category === category)) console.log('applyFilters - 分类过滤后数量:', filtered.length); } - + if (this.data.searchKeyword) { const keyword = this.data.searchKeyword.toLowerCase() - + const originalLength = filtered.length; console.log('applyFilters - 搜索关键词:', keyword, '过滤前数量:', originalLength); - + // 记录每个商品的匹配情况 filtered = filtered.filter(item => { const nameMatch = (item.name || '').toLowerCase().includes(keyword); @@ -1336,7 +1336,7 @@ Page({ const grossWeightMatch = (item.grossWeight || '').toLowerCase().includes(keyword); const yolkMatch = (item.yolk || '').toLowerCase().includes(keyword); const match = item.isAd || nameMatch || productNameMatch || specMatch || regionMatch || grossWeightMatch || yolkMatch; - + // 详细日志,记录每个商品的匹配字段 if (originalLength <= 20 || keyword === '41' || keyword === '43-44') { // 增加特定关键词的日志记录 console.log('商品匹配详情:', { @@ -1360,18 +1360,18 @@ Page({ match: match }); } - + return match; }) - + console.log('applyFilters - 搜索过滤后数量:', filtered.length); } - + if (this.data.selectedRegion !== '全国') { const selectedRegion = this.data.selectedRegion filtered = filtered.filter(item => item.isAd || (item.region && item.region.includes(selectedRegion))) } - + // 去重处理 - 确保返回的商品列表中没有重复的商品 const uniqueGoodsMap = new Map(); filtered.forEach(item => { @@ -1386,68 +1386,68 @@ Page({ } }); filtered = Array.from(uniqueGoodsMap.values()); - + if (shouldSort) { filtered.sort((a, b) => { const reservedCountA = a.reservedCount || 0 const reservedCountB = b.reservedCount || 0 if (reservedCountB !== reservedCountA) return reservedCountB - reservedCountA - + const priceA = parseFloat(a.price || 0) const priceB = parseFloat(b.price || 0) if (!isNaN(priceB) && !isNaN(priceA) && priceA !== priceB) return priceA - priceB - + const createdAtA = new Date(a.createdAt || 0).getTime() const createdAtB = new Date(b.createdAt || 0).getTime() return createdAtB - createdAtA }) } - + // 统一字段长度 filtered = filtered.map(item => this.normalizeFieldLength(item)) - + return filtered }, - + // 瀑布流布局 - 淘宝风格左右交替 - distributeToColumns: function(goods) { + distributeToColumns: function (goods) { if (!goods || goods.length === 0) { return { leftColumnGoods: [], rightColumnGoods: [] } } - + const leftColumn = [] const rightColumn = [] - + for (let i = 0; i < goods.length; i += 2) { const currentRow = Math.floor(i / 2) const isEvenRow = currentRow % 2 === 0 - + if (i < goods.length) { const item = { ...goods[i], isLong: isEvenRow } leftColumn.push(item) } - + if (i + 1 < goods.length) { const item = { ...goods[i + 1], isLong: !isEvenRow } rightColumn.push(item) } } - + return { leftColumnGoods: leftColumn, rightColumnGoods: rightColumn } }, - + // 分组商品用于交错布局(左长右短,左短右长交替) - groupGoodsForStaggeredLayout: function(goods) { + groupGoodsForStaggeredLayout: function (goods) { if (!goods || goods.length === 0) { return [] } - + const grouped = [] const len = goods.length - + for (let i = 0; i < len; i += 2) { const row = [] - + // 第一个商品:如果是偶数行(index为偶数),则是长商品;如果是奇数行,则是短商品 if (i < len) { row.push({ @@ -1455,7 +1455,7 @@ Page({ isLong: i % 2 === 0 // 偶数索引为长商品 }) } - + // 第二个商品:与第一个相反 if (i + 1 < len) { row.push({ @@ -1463,37 +1463,37 @@ Page({ isLong: i % 2 !== 0 // 奇数索引为长商品 }) } - + grouped.push(row) } - + return grouped }, - + // 瀑布流布局:将商品分配到左右两列 // 规则:左长右短 -> 左短右长 交替排列 // 偶数行(0,2,4...):左长右短 // 奇数行(1,3,5...):左短右长 - distributeToColumns: function(goods) { + distributeToColumns: function (goods) { if (!goods || goods.length === 0) { return { leftColumnGoods: [], rightColumnGoods: [] } } - + const leftColumn = [] const rightColumn = [] const rowCount = Math.ceil(goods.length / 2) - + for (let i = 0; i < goods.length; i += 2) { const currentRow = Math.floor(i / 2) const isEvenRow = currentRow % 2 === 0 - + if (i < goods.length) { leftColumn.push({ ...goods[i], isLong: isEvenRow // 偶数行左边为长,奇数行左边为短 }) } - + if (i + 1 < goods.length) { rightColumn.push({ ...goods[i + 1], @@ -1501,53 +1501,53 @@ Page({ }) } } - + return { leftColumnGoods: leftColumn, rightColumnGoods: rightColumn } }, - + // 搜索输入(带防抖) - onSearchInput: function(e) { + onSearchInput: function (e) { const keyword = e.detail.value - + this.setData({ searchKeyword: keyword }) - + // 清除之前的定时器 if (this.data.searchDebounceTimer) { clearTimeout(this.data.searchDebounceTimer) } - + // 设置新的定时器,300ms防抖 const timer = setTimeout(() => { this.searchGoods() }, 300) - + this.setData({ searchDebounceTimer: timer }) }, - + // 搜索商品 - searchGoods: function() { + searchGoods: function () { // 重新显示tabBar const app = getApp(); if (app && app.globalData) { app.globalData.showTabBar = true; } - + console.log('searchGoods - 开始搜索,关键词:', this.data.searchKeyword); console.log('searchGoods - 本地已有商品数量:', this.data.goods.length); - + // 先对本地已加载的商品进行过滤 const filteredGoods = this.applyFilters(this.data.goods, false); - + console.log('searchGoods - 本地过滤结果数量:', filteredGoods.length); - + // 如果本地过滤结果不足,或者没有匹配的商品,则重新加载数据 if (filteredGoods.length < 3 && this.data.searchKeyword) { console.log('searchGoods - 本地过滤结果不足3个,将重新加载数据'); @@ -1577,31 +1577,31 @@ Page({ }); } }, - + // 切换地区选择器 - toggleRegionPicker: function() { + toggleRegionPicker: function () { this.setData({ showRegionPicker: !this.data.showRegionPicker }) }, - + // 选择地区(强制刷新机制) - selectRegion: function(e) { + selectRegion: function (e) { const region = e.currentTarget.dataset.region - + // 立即关闭弹窗 this.setData({ selectedRegion: region, searchKeyword: '', // 清除搜索关键词,筛选框优先级更高 showRegionPicker: false }) - + // 重新显示tabBar const app = getApp(); if (app && app.globalData) { app.globalData.showTabBar = true; } - + // 清除缓存并重新加载数据 - 仿照下拉刷新机制 this.setData({ page: 1, @@ -1614,29 +1614,29 @@ Page({ lastDataTimestamp: 0, goodsCache: [] }); - + this.loadGoods(false, true); // 强制刷新 }, - + // 阻止事件冒泡 - stopPropagation: function() { + stopPropagation: function () { // 空函数,用于阻止事件冒泡 }, - + // 选择品种 - 使用下拉刷新机制 - selectCategory: function(e) { + selectCategory: function (e) { // 重新显示tabBar const app = getApp(); if (app && app.globalData) { app.globalData.showTabBar = true; } - + const category = e.currentTarget.dataset.category if (category === this.data.selectedCategory) { return // 如果选择的分类和当前相同,不重复加载 } - + // 清除缓存并重新加载数据 - 筛选时不显示骨架屏,直接显示内容 this.setData({ selectedCategory: category, @@ -1653,19 +1653,19 @@ Page({ lastDataTimestamp: 0, goodsCache: [] }); - + // 强制刷新:从数据库重新加载数据 this.loadGoods(false, true); // 第二个参数true表示强制刷新 }, - + // 查看商品详情 - viewGoodsDetail: function(e) { + viewGoodsDetail: function (e) { const item = e.currentTarget.dataset.item - + // 确保productId存在,优先使用id,其次使用productId const productId = String(item.id || item.productId || '') - + if (!productId) { console.error('商品ID不存在,无法查看详情'); wx.showToast({ @@ -1675,7 +1675,7 @@ Page({ }) return; } - + // 将完整的商品数据传递给详情页,包含联系人信息,与buyer页面保持一致 // 同时传递登录状态信息,让详情页决定是否显示登录弹窗 const needLogin = this.data.needPhoneAuth; @@ -1683,16 +1683,16 @@ Page({ url: `/pages/goods-detail/goods-detail?goodsData=${encodeURIComponent(JSON.stringify(item))}&productId=${productId}&needLogin=${needLogin}` }) }, - + // 跳转到我要卖蛋页面 - navigateToSettlement: function() { + navigateToSettlement: function () { wx.switchTab({ url: '/pages/settlement/index' }) }, // 跳转到招商合作页面 - navigateToCooperation: function() { + navigateToCooperation: function () { this.setData({ sidebarBtnHidden: true }); @@ -1702,7 +1702,7 @@ Page({ }, // 跳转到货源管理页面 - navigateToGoods: function() { + navigateToGoods: function () { this.setData({ sidebarBtnHidden: true }); @@ -1712,31 +1712,31 @@ Page({ }, // 预览图片 - previewImage: function(e) { + previewImage: function (e) { // 阻止事件冒泡,避免触发商品点击事件 e.stopPropagation(); - + // 获取图片信息 const item = e.currentTarget.dataset.item; const index = e.currentTarget.dataset.index; - + if (!item) { return; } - + // 确保图片URL存在且为数组 let imageUrls = item.imageUrls || item.images || []; if (!Array.isArray(imageUrls)) { imageUrls = [imageUrls]; } - + // 过滤掉无效的图片URL const validImageUrls = imageUrls.filter(url => url && typeof url === 'string' && url.trim() !== ''); - + if (validImageUrls.length === 0) { return; } - + // 显示图片预览弹窗 this.setData({ previewImageUrls: validImageUrls, @@ -1744,55 +1744,55 @@ Page({ showImagePreview: true }); }, - + // 关闭图片预览 - closeImagePreview: function() { + closeImagePreview: function () { this.setData({ showImagePreview: false }); }, - + // 预览图片切换事件 - onPreviewImageChange: function(e) { + onPreviewImageChange: function (e) { this.setData({ previewImageIndex: e.detail.current }); }, - + // 滚动事件处理 - 优化性能 - onScroll: function(e) { + onScroll: function (e) { const { scrollTop } = e.detail; - + // 清除之前的防抖定时器 if (this.data.scrollDebounceTimer) { clearTimeout(this.data.scrollDebounceTimer) } - + // 设置防抖,32ms约等于30fps,限制高速滑动时的处理频率 const timer = setTimeout(() => { this.handleScroll(scrollTop) }, 32) - + this.setData({ scrollDebounceTimer: timer }) }, - + // 实际的滚动处理逻辑 - handleScroll: function(scrollTop) { + handleScroll: function (scrollTop) { const threshold = 50; const backToTopThreshold = 300; - + const lastScrollTop = this.data.lastScrollTop || 0; const isScrollingDown = scrollTop > lastScrollTop; - + let needUpdate = false; const updates = { lastScrollTop: scrollTop }; - + // 搜索框始终固定显示,不做隐藏处理 - + // 侧边栏按钮显示逻辑 // 下滑时隐藏按钮(除非用户未手动隐藏过且在顶部) if (isScrollingDown && scrollTop > threshold && !this.data.sidebarBtnHidden) { @@ -1807,33 +1807,33 @@ Page({ needUpdate = true; wx.setStorageSync('sidebarBtnHidden', false); } - + // 回到顶部按钮显示逻辑 const shouldShowBackToTop = scrollTop > backToTopThreshold; if (shouldShowBackToTop !== this.data.showBackToTop) { updates.showBackToTop = shouldShowBackToTop; needUpdate = true; } - + if (needUpdate) { this.setData(updates); } - + // TabBar显示 const app = getApp(); if (app && app.globalData) { app.globalData.showTabBar = true; } }, - + // 更新商品的收藏状态 - updateGoodsFavoriteStatus: function(goods, isLoadMore) { + updateGoodsFavoriteStatus: function (goods, isLoadMore) { // 获取用户手机号 let userPhone = ''; try { const users = wx.getStorageSync('users') || {}; const userId = wx.getStorageSync('userId'); - + // 尝试从users中获取手机号 if (userId && users[userId] && users[userId].phoneNumber) { userPhone = users[userId].phoneNumber; @@ -1850,12 +1850,12 @@ Page({ } catch (e) { console.error('获取用户手机号失败:', e); } - + if (!userPhone) { // 用户未登录,无法获取收藏状态 return; } - + // 调用API获取用户收藏列表 API.getFavorites(userPhone) .then(res => { @@ -1869,19 +1869,19 @@ Page({ } else if (res.data && Array.isArray(res.data.data)) { favoritesList = res.data.data; } - + // 从收藏列表中提取商品ID const favoriteProductIds = favoritesList.map(item => { // 尝试从不同的字段名获取商品ID return String(item.productId || item.id || item.product_id || ''); }).filter(id => id !== ''); // 过滤掉空字符串 - + // 更新商品的isFavorite状态 const updatedGoods = goods.map(item => ({ ...item, isFavorite: favoriteProductIds.includes(String(item.id || item.productId)) })); - + // 更新商品列表 let updatedGoodsList = this.data.goods; if (!isLoadMore || this.data.page === 1) { @@ -1891,7 +1891,7 @@ Page({ // 加载更多时,追加到现有列表 updatedGoodsList = [...this.data.goods, ...updatedGoods]; } - + this.setData({ goods: updatedGoodsList }, () => { @@ -1907,23 +1907,23 @@ Page({ console.error('获取收藏状态失败:', err); }); }, - + // 回到顶部 - scrollToTop: function() { - this.setData({ + scrollToTop: function () { + this.setData({ scrollTop: 0, searchSectionVisible: true, showBackToTop: false }); }, - + // 上拉加载更多 - onReachBottom: function() { + onReachBottom: function () { if (this.data.hasMoreData && !this.data.loadingMore) { this.loadGoods(true) } }, - + // 显示一键登录弹窗 showOneKeyLogin() { this.setData({ @@ -2022,7 +2022,7 @@ Page({ if (e.detail.errMsg === 'getPhoneNumber:ok') { // 用户同意授权,实际处理授权流程 - + // 同时请求位置授权 wx.authorize({ @@ -2208,7 +2208,7 @@ Page({ } // 保存用户信息并等待上传完成 - + const uploadResult = await this.saveUserInfo(tempUserInfo, currentUserType) console.log('用户信息保存并上传完成') @@ -2604,7 +2604,7 @@ Page({ // 确保存储操作成功 try { wx.setStorageSync('users', users) - + } catch (e) { console.error('保存用户信息到本地存储失败:', e) } @@ -2711,29 +2711,29 @@ Page({ checkAndRestoreLoginStatus() { console.log('开始检查并恢复登录状态') const app = getApp() - + // 从本地存储获取用户信息 const localUserInfo = wx.getStorageSync('userInfo') || {} const userId = wx.getStorageSync('userId') const openid = wx.getStorageSync('openid') console.log('恢复登录状态 - userId:', userId, 'openid:', openid ? '已获取' : '未获取') - + // 优先使用全局用户信息,如果没有则使用本地存储的用户信息 if (app.globalData.userInfo) { - this.setData({ + this.setData({ userInfo: app.globalData.userInfo, needPhoneAuth: !app.globalData.userInfo.phoneNumber, isLoggedIn: !!(userId && openid) }) } else { app.globalData.userInfo = localUserInfo - this.setData({ + this.setData({ userInfo: localUserInfo, needPhoneAuth: !localUserInfo.phoneNumber, isLoggedIn: !!(userId && openid) }) } - + if (userId && openid) { // 确保users存储结构存在 let users = wx.getStorageSync('users') @@ -2752,45 +2752,45 @@ Page({ const currentType = user.type this.setData({ currentUserType: currentType }) console.log('恢复登录状态 - 当前本地存储的用户类型:', currentType) - + // 从服务器获取最新的用户信息,确保身份由数据库决定 this.refreshUserInfoFromServer(openid, userId) } else { console.log('未找到有效的本地登录信息') } }, - + // 从服务器刷新用户信息并同步身份数据 refreshUserInfoFromServer(openid, userId) { const API = require('../../utils/api.js') - + API.getUserInfo(openid).then(res => { console.log('从服务器获取用户信息成功:', res) - + if (res.success && res.data) { const serverUserInfo = res.data - + // 更新本地用户信息 const app = getApp() const updatedUserInfo = { ...app.globalData.userInfo, ...serverUserInfo } - + app.globalData.userInfo = updatedUserInfo wx.setStorageSync('userInfo', updatedUserInfo) - + // 设置用户入驻状态 this.setData({ userInfo: updatedUserInfo, partnerstatus: serverUserInfo.partnerstatus || '' }) - + // 同步更新用户身份信息(当前身份由数据库决定) if (serverUserInfo.type) { this.syncUserTypeFromServer(userId, serverUserInfo.type) } - + console.log('用户信息已更新,昵称:', updatedUserInfo.name, '手机号:', updatedUserInfo.phoneNumber, '身份:', serverUserInfo.type) } }).catch(err => { @@ -2798,31 +2798,31 @@ Page({ // 如果getUserInfo失败,尝试使用validateUserLogin作为备选 API.validateUserLogin().then(res => { console.log('使用validateUserLogin获取用户信息成功:', res) - + if (res.success && res.data) { const serverUserInfo = res.data - + // 更新本地用户信息 const app = getApp() const updatedUserInfo = { ...app.globalData.userInfo, ...serverUserInfo } - + app.globalData.userInfo = updatedUserInfo wx.setStorageSync('userInfo', updatedUserInfo) - + // 设置用户入驻状态 this.setData({ userInfo: updatedUserInfo, partnerstatus: serverUserInfo.partnerstatus || '' }) - + // 同步更新用户身份信息(当前身份由数据库决定) if (serverUserInfo.type) { this.syncUserTypeFromServer(userId, serverUserInfo.type) } - + console.log('用户信息已更新(备选方案):', updatedUserInfo) } }).catch(validateErr => { @@ -2831,37 +2831,37 @@ Page({ }) }) }, - + // 从服务器同步用户身份信息 syncUserTypeFromServer(userId, serverType) { if (!userId || !serverType) { console.error('同步用户身份信息失败: 参数不完整') return } - + console.log('从服务器同步用户身份信息:', { userId, serverType }) - + // 更新本地存储的用户身份 let users = wx.getStorageSync('users') || {} if (!users[userId]) { users[userId] = {} } - + // 移除serverType中的customer(如果存在) let processedServerType = serverType.replace(/,?customer/g, '').replace(/^,|,$/g, '') - + // 构建新的用户类型 let newUserType = processedServerType - + // 只有当新构建的用户类型与本地不同时才更新 if (users[userId].type !== newUserType) { users[userId].type = newUserType wx.setStorageSync('users', users) - + // 更新全局用户类型 const app = getApp() app.globalData.userType = newUserType - + console.log('用户身份已从服务器同步并保留客服标识:', newUserType) } else { console.log('用户身份与服务器一致,无需更新:', newUserType) @@ -3228,7 +3228,7 @@ Page({ const latitude = res.latitude; const longitude = res.longitude; wx.setStorageSync('userLocation', { latitude, longitude }); - + let openid = wx.getStorageSync('openid'); if (!openid) { const globalUserInfo = wx.getStorageSync('userInfo');