// pages/favorites/index.js const API = require('../../utils/api.js'); // 提取地区中的省份信息 function extractProvince(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) { // 包含"自治区",提取到"自治区"结束 return region.substring(0, autonomousRegionEndIndex + 3); } else if (specialRegionEndIndex !== -1) { // 包含"特别行政区",提取到"特别行政区"结束 return region.substring(0, specialRegionEndIndex + 5); } else if (municipalityEndIndex === 2) { // 直辖市(如北京市、上海市),市字在第2个字符位置 return region.substring(0, municipalityEndIndex + 1); } // 如果没有找到匹配的格式,返回原字符串 return region; } Page({ /** * 页面的初始数据 */ data: { favoritesList: [], loading: true, hasFavorites: false, // 图片预览相关状态 showImagePreview: false, // 控制图片预览弹窗显示 previewImageUrls: [], // 预览的图片URL列表 previewImageIndex: 0, // 当前预览图片的索引 // 图片缩放相关状态 scale: 1, // 当前缩放比例 lastScale: 1, // 上一次缩放比例 startDistance: 0, // 双指起始距离 doubleTapTimer: null, // 双击计时器 lastTapTime: 0, // 上一次单击时间 isScaling: false, // 是否正在缩放中 offsetX: 0, // X轴偏移量 offsetY: 0, // Y轴偏移量 initialTouch: null // 初始触摸点 }, /** * 生命周期函数--监听页面加载 */ onLoad(options) { this.loadFavorites(); // 添加收藏状态变化事件监听 const app = getApp(); this.favoriteChangedHandler = (data) => { console.log('收藏页面收到收藏状态变化通知:', data); // 重新加载收藏列表以更新状态 this.loadFavorites(); }; app.eventBus.on('favoriteChanged', this.favoriteChangedHandler); }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady() { }, /** * 生命周期函数--监听页面显示 */ onShow() { // 每次显示页面时重新加载收藏列表 this.loadFavorites(); // 更新自定义tabBar状态 if (typeof this.getTabBar === 'function' && this.getTabBar()) { this.getTabBar().setData({ selected: 3 }); } // 更新全局tab状态 const app = getApp(); if (app.updateCurrentTab) { app.updateCurrentTab('favorites'); } }, /** * 生命周期函数--监听页面隐藏 */ onHide() { }, /** * 生命周期函数--监听页面卸载 */ onUnload() { // 移除事件监听 const app = getApp(); if (this.favoriteChangedHandler) { app.eventBus.off('favoriteChanged', this.favoriteChangedHandler); console.log('收藏页面移除收藏状态变化事件监听'); } }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh() { // 下拉刷新时重新加载收藏列表 this.loadFavorites(true); }, /** * 页面上拉触底事件的处理函数 */ onReachBottom() { }, /** * 用户点击右上角分享 */ onShareAppMessage() { }, /** * 加载收藏列表 */ loadFavorites: function (isPullDown = false) { this.setData({ loading: true }); // 获取手机号码 - 使用与API.js一致的获取方式 const users = wx.getStorageSync('users') || {}; const userId = wx.getStorageSync('userId'); let phoneNumber = null; // 尝试从users中获取手机号 if (userId && users[userId] && users[userId].phoneNumber) { phoneNumber = users[userId].phoneNumber; } else { // 尝试从全局用户信息获取 const userInfo = wx.getStorageSync('userInfo'); if (userInfo && userInfo.phoneNumber) { phoneNumber = userInfo.phoneNumber; } else { // 尝试从直接存储的phoneNumber获取 phoneNumber = wx.getStorageSync('phoneNumber'); } } // 检查用户是否登录 if (!phoneNumber) { // 用户未登录,显示提示 wx.showToast({ title: '请先登录', icon: 'none' }); this.setData({ loading: false, hasFavorites: false }); if (isPullDown) { wx.stopPullDownRefresh(); } return; } // 首先获取所有商品列表,确保包含联系人信息 API.getProductList('published', { page: 1, pageSize: 100 // 获取足够多的商品,确保包含所有收藏商品 }).then(productListRes => { console.log('获取商品列表成功:', productListRes); // 然后获取收藏列表 return API.getFavorites(phoneNumber).then(res => { console.log('获取收藏列表成功:', res); // 检查API返回是否成功 if (res && res.code === 200 && res.data) { let favorites = res.data.favorites || []; // 获取商品列表数据 const allProducts = productListRes && productListRes.products ? productListRes.products : []; // 转换supplyStatus字段值,并从商品列表中获取联系人信息 favorites = favorites.map(item => { if (item.Product && item.Product.supplyStatus) { // 将supplyStatus由"平台货源"、"三方认证"、"三方未认证"修改为"预售"、"现货" // 平台货源和三方认证转为现货,三方未认证转为预售 if (['平台货源', '三方认证'].includes(item.Product.supplyStatus)) { item.Product.supplyStatus = "现货"; } else if (item.Product.supplyStatus === '三方未认证') { item.Product.supplyStatus = "预售"; } } // 从商品列表中查找对应的商品,获取联系人信息 const productId = item.Product?.productId || item.productId; const matchingProduct = allProducts.find(product => String(product.id) === String(productId) || String(product.productId) === String(productId) ); // 提取联系人信息 let product_contact = ''; let contact_phone = ''; let fullRegion = ''; let province = ''; let status = 'pending_review'; // 默认状态 // 优先从商品列表中获取联系人信息和地区信息 if (matchingProduct) { product_contact = matchingProduct.product_contact || matchingProduct.contact || ''; contact_phone = matchingProduct.contact_phone || matchingProduct.phone || ''; // 保存完整地区数据 fullRegion = matchingProduct.fullRegion || matchingProduct.region || ''; // 提取省份 province = extractProvince(fullRegion); // 获取商品状态 status = matchingProduct.status || 'pending_review'; } // 然后尝试从收藏数据中获取 else if (item.Product) { product_contact = item.Product.product_contact || item.Product.contact || ''; contact_phone = item.Product.contact_phone || item.Product.phone || ''; // 保存完整地区数据 fullRegion = item.Product.region || ''; // 提取省份 province = extractProvince(fullRegion); // 获取商品状态 status = item.Product.status || 'pending_review'; } // 更新item对象,确保联系人信息和地区信息同时存在于顶层和Product对象中 item.product_contact = product_contact; item.contact_phone = contact_phone; item.fullRegion = fullRegion; item.region = province; item.status = status; if (item.Product) { item.Product.product_contact = product_contact; item.Product.contact_phone = contact_phone; item.Product.fullRegion = fullRegion; item.Product.region = province; item.Product.status = status; } return item; }); // 过滤掉已下架或软删除的商品,只保留已发布状态的货源 favorites = favorites.filter(item => { const status = item.status || item.Product?.status || 'pending_review'; // 只保留已发布状态的商品 return status === 'published'; }); console.log('更新后的收藏列表:', favorites); this.setData({ favoritesList: favorites, hasFavorites: favorites.length > 0, loading: false }); } else { // API返回格式不正确 this.setData({ loading: false, hasFavorites: false }); wx.showToast({ title: '数据获取失败', icon: 'none' }); } // 停止下拉刷新 if (isPullDown) { wx.stopPullDownRefresh(); } }); }).catch(err => { console.error('获取收藏列表失败:', err); wx.showToast({ title: '获取收藏列表失败', icon: 'none' }); this.setData({ loading: false, hasFavorites: false }); // 停止下拉刷新 if (isPullDown) { wx.stopPullDownRefresh(); } }); }, /** * 取消收藏 */ cancelFavorite: function (e) { const productId = e.currentTarget.dataset.productid; wx.showLoading({ title: '正在取消收藏', mask: true }); API.cancelFavorite(productId).then(res => { console.log('取消收藏成功:', res); // 从收藏列表中移除该商品 const updatedList = this.data.favoritesList.filter(item => item.productId !== productId); this.setData({ favoritesList: updatedList, hasFavorites: updatedList.length > 0 }); wx.showToast({ title: '取消收藏成功', icon: 'success' }); // 触发全局事件,通知其他页面收藏状态已更改 const app = getApp(); app.eventBus.emit('favoriteChanged', { productId: productId, isFavorite: false }); }).catch(err => { console.error('取消收藏失败:', err); wx.showToast({ title: '取消收藏失败', icon: 'none' }); }).finally(() => { wx.hideLoading(); }); }, /** * 跳转到商品详情页 */ goToGoodsDetail: function(e) { console.log('goToGoodsDetail - e.currentTarget.dataset:', e.currentTarget.dataset); const goodsItem = e.currentTarget.dataset.item; console.log('goToGoodsDetail - goodsItem:', goodsItem); console.log('goToGoodsDetail - goodsItem.Product:', goodsItem.Product); // 检查用户登录状态 const openid = wx.getStorageSync('openid'); const userId = wx.getStorageSync('userId'); if (!openid || !userId) { console.log('用户未登录,提示登录'); wx.showToast({ title: '请先登录', icon: 'none' }); return; } // 获取商品ID const productId = goodsItem.Product?.productId || goodsItem.productId; console.log('获取完整商品详情 - productId:', productId); // 调用API.getProductList获取完整的商品列表,确保包含联系人信息 wx.showLoading({ title: '加载中' }); API.getProductList('published', { page: 1, pageSize: 100 // 获取足够多的商品,确保包含当前商品 }).then(productListRes => { console.log('获取商品列表成功:', productListRes); // 获取商品列表数据 const allProducts = productListRes && productListRes.products ? productListRes.products : []; // 从商品列表中查找对应的商品,获取联系人信息 const matchingProduct = allProducts.find(product => String(product.id) === String(productId) || String(product.productId) === String(productId) ); // 提取联系人信息 let product_contact = ''; let contact_phone = ''; let region = ''; // 优先从商品列表中获取联系人信息 if (matchingProduct) { product_contact = matchingProduct.product_contact || matchingProduct.contact || ''; contact_phone = matchingProduct.contact_phone || matchingProduct.phone || ''; region = matchingProduct.region || ''; console.log('从商品列表获取到联系人信息:', { product_contact, contact_phone, region }); } // 然后尝试从收藏数据中获取 else { product_contact = goodsItem.product_contact || goodsItem.Product?.product_contact || goodsItem.Product?.contact || goodsItem.contact || ''; contact_phone = goodsItem.contact_phone || goodsItem.Product?.contact_phone || goodsItem.Product?.phone || goodsItem.phone || ''; region = goodsItem.region || goodsItem.Product?.region || ''; console.log('从收藏数据获取到联系人信息:', { product_contact, contact_phone, region }); } // 确保商品ID正确设置 const productData = goodsItem.Product || {}; const completeGoodsData = { // 首先包含原始商品对象的所有字段 ...goodsItem, // 然后用Product对象中的字段覆盖 ...productData, // 确保商品ID正确设置 id: productData.productId || goodsItem.productId, productId: productData.productId || goodsItem.productId, // 强制设置从商品列表中获取到的联系人信息和地区信息 product_contact: product_contact, contact_phone: contact_phone, // 保存完整地区数据 fullRegion: region, // 只显示省份 region: extractProvince(region) }; // 专门检查并记录联系人信息 console.log('联系人信息检查:'); console.log('- 联系人姓名:', completeGoodsData.product_contact || '暂无'); console.log('- 联系电话:', completeGoodsData.contact_phone || '暂无'); // 添加更多日志,确保我们没有丢失重要信息 console.log('准备传递的完整商品数据:', completeGoodsData); wx.hideLoading(); // 跳转到商品详情页 wx.navigateTo({ url: '/pages/goods-detail/goods-detail?goodsData=' + encodeURIComponent(JSON.stringify(completeGoodsData)) }); // 后台调用API.updateProductContacts(),与buyer页面保持一致 console.log('开始调用API.updateProductContacts()'); API.updateProductContacts().then(function(res) { console.log('商品联系人更新成功:', res); }).catch(function(err) { console.error('商品联系人更新失败:', err); }); }).catch(err => { console.error('获取商品列表失败:', err); wx.hideLoading(); // 即使获取商品列表失败,也尝试跳转到详情页 // 保存当前已有的联系人信息 const existingContactInfo = { product_contact: goodsItem.product_contact || goodsItem.Product?.product_contact || goodsItem.Product?.contact || goodsItem.contact || '', contact_phone: goodsItem.contact_phone || goodsItem.Product?.contact_phone || goodsItem.Product?.phone || goodsItem.phone || '', region: goodsItem.region || goodsItem.Product?.region || '' }; // 确保商品ID正确设置 const productData = goodsItem.Product || {}; const completeGoodsData = { ...goodsItem, ...productData, id: productData.productId || goodsItem.productId, productId: productData.productId || goodsItem.productId, product_contact: existingContactInfo.product_contact, contact_phone: existingContactInfo.contact_phone, region: existingContactInfo.region }; // 跳转到商品详情页 wx.navigateTo({ url: '/pages/goods-detail/goods-detail?goodsData=' + encodeURIComponent(JSON.stringify(completeGoodsData)) }); }); }, // 轮播图切换 swiperChange(e) { const current = e.detail.current; const itemId = e.currentTarget.dataset.itemId; // 更新对应商品项的currentImageIndex this.setData({ [`favoritesList[${itemId}].currentImageIndex`]: current }); }, // 预览图片 previewImage(e) { // 登录验证 const userInfo = wx.getStorageSync('userInfo') || null; const userId = wx.getStorageSync('userId') || null; if (!userInfo || !userId) { // 未登录,显示授权登录弹窗 this.setData({ showAuthModal: true, pendingUserType: 'buyer' }); return; } // 已登录,执行图片预览 const { urls, index } = e.currentTarget.dataset; this.setData({ showImagePreview: true, previewImageUrls: urls, previewImageIndex: parseInt(index) }); }, // 关闭图片预览 closeImagePreview() { this.setData({ showImagePreview: false }); this.resetZoom(); }, // 重置缩放状态 resetZoom() { this.setData({ scale: 1, lastScale: 1, offsetX: 0, offsetY: 0, initialTouch: null }); }, // 处理图片点击事件(单击/双击判断) handleImageTap(e) { const currentTime = Date.now(); const lastTapTime = this.data.lastTapTime; // 判断是否为双击(300ms内连续点击) if (currentTime - lastTapTime < 300) { // 双击事件 if (this.data.doubleTapTimer) { clearTimeout(this.data.doubleTapTimer); } // 切换放大/缩小状态 const newScale = this.data.scale === 1 ? 2 : 1; this.setData({ scale: newScale, lastScale: newScale, offsetX: 0, offsetY: 0, lastTapTime: 0 // 重置双击状态 }); } else { // 单击事件,设置延迟来检测是否会成为双击 if (this.data.doubleTapTimer) { clearTimeout(this.data.doubleTapTimer); } this.setData({ lastTapTime: currentTime, doubleTapTimer: setTimeout(() => { // 确认是单击,关闭图片预览 this.closeImagePreview(); }, 300) }); } }, // 处理触摸开始事件 handleTouchStart(e) { const touches = e.touches; if (touches.length === 1) { // 单指:准备拖动 this.setData({ initialTouch: { x: touches[0].clientX, y: touches[0].clientY } }); } else if (touches.length === 2) { // 双指:记录起始距离,准备缩放 const distance = this.calculateDistance(touches[0], touches[1]); this.setData({ startDistance: distance, isScaling: true, lastScale: this.data.scale }); } }, // 处理触摸移动事件 handleTouchMove(e) { const touches = e.touches; if (touches.length === 1 && this.data.initialTouch && this.data.scale !== 1) { // 单指拖动(只有在缩放状态下才允许拖动) const deltaX = touches[0].clientX - this.data.initialTouch.x; const deltaY = touches[0].clientY - this.data.initialTouch.y; // 计算新的偏移量 let newOffsetX = this.data.offsetX + deltaX; let newOffsetY = this.data.offsetY + deltaY; // 边界限制 const windowWidth = wx.getSystemInfoSync().windowWidth; const windowHeight = wx.getSystemInfoSync().windowHeight; const maxOffsetX = (windowWidth * (this.data.scale - 1)) / 2; const maxOffsetY = (windowHeight * (this.data.scale - 1)) / 2; newOffsetX = Math.max(-maxOffsetX, Math.min(maxOffsetX, newOffsetX)); newOffsetY = Math.max(-maxOffsetY, Math.min(maxOffsetY, newOffsetY)); this.setData({ offsetX: newOffsetX, offsetY: newOffsetY, initialTouch: { x: touches[0].clientX, y: touches[0].clientY } }); } else if (touches.length === 2) { // 双指缩放 const currentDistance = this.calculateDistance(touches[0], touches[1]); const scale = (currentDistance / this.data.startDistance) * this.data.lastScale; // 限制缩放范围在0.5倍到3倍之间 const newScale = Math.max(0.5, Math.min(3, scale)); this.setData({ scale: newScale, isScaling: true }); } }, // 处理触摸结束事件 handleTouchEnd(e) { this.setData({ isScaling: false, lastScale: this.data.scale, initialTouch: null }); }, // 计算两点之间的距离 calculateDistance(touch1, touch2) { const dx = touch2.clientX - touch1.clientX; const dy = touch2.clientY - touch1.clientY; return Math.sqrt(dx * dx + dy * dy); }, // 切换预览图片 onPreviewImageChange(e) { this.setData({ previewImageIndex: e.detail.current }); this.resetZoom(); } })