// pages/goods-detail/goods-detail.js const API = require('../../utils/api.js') // 根据sourceType获取对应的颜色 function getSourceTypeColor(sourceType) { const colorMap = { '三方认证': '#4d9dff', '三方未认证': '#ff4d4f', '平台货源': '#2ad21f' }; return colorMap[sourceType] || '#4d9dff'; } // 格式化毛重显示的辅助函数 function formatGrossWeight(grossWeight, weight) { console.log('===== formatGrossWeight 函数调用 ====='); console.log('输入参数:'); console.log('- grossWeight:', grossWeight, '(类型:', typeof grossWeight, ')'); console.log('- weight:', weight, '(类型:', typeof weight, ')'); // 1. 优先使用grossWeight,只要它不是null、不是undefined、不是空字符串 if (grossWeight !== null && grossWeight !== undefined && grossWeight !== '') { console.log('使用grossWeight参数'); return grossWeight; } // 如果grossWeight无效,尝试使用weight字段 if (weight !== null && weight !== undefined && weight !== '') { console.log('使用weight参数'); return weight; } // 3. 新增逻辑:如果grossWeight和weight都无效,返回空字符串以支持文字输入 console.log('两个参数都无效,返回空字符串'); return ""; } // 提取地区中的省份信息 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({ // 分享给朋友/群聊 onShareAppMessage() { const goodsDetail = this.data.goodsDetail || {}; const title = goodsDetail.name ? `优质鸡蛋 - ${goodsDetail.name}` : '优质鸡蛋货源'; return { title: title, path: `/pages/goods-detail/goods-detail?productId=${goodsDetail.id || goodsDetail.productId}`, imageUrl: goodsDetail.imageUrls && goodsDetail.imageUrls.length > 0 ? goodsDetail.imageUrls[0] : '/images/你有好蛋.png' } }, // 分享到朋友圈 onShareTimeline() { const goodsDetail = this.data.goodsDetail || {}; const title = goodsDetail.name ? `优质鸡蛋 - ${goodsDetail.name}` : '优质鸡蛋货源'; return { title: title, query: `productId=${goodsDetail.id || goodsDetail.productId}`, imageUrl: goodsDetail.imageUrls && goodsDetail.imageUrls.length > 0 ? goodsDetail.imageUrls[0] : '/images/你有好蛋.png' } }, data: { goodsDetail: {}, // 当前商品详情 showImagePreview: false, // 控制图片预览弹窗显示 previewImageUrls: [], // 预览的图片URL列表 previewImageIndex: 0, // 当前预览图片的索引 fromSeller: false, // 是否来自seller页面 isFavorite: false, // 当前商品是否已收藏 // 登录弹窗状态 showOneKeyLoginModal: false, // 是否显示登录弹窗 // 图片缩放相关状态 scale: 1, // 当前缩放比例 lastScale: 1, // 上一次缩放比例 startDistance: 0, // 双指起始距离 doubleTapTimer: null, // 双击计时器 lastTapTime: 0, // 上一次单击时间 isScaling: false, // 是否正在缩放中 offsetX: 0, // X轴偏移量 offsetY: 0, // Y轴偏移量 initialTouch: null, // 初始触摸点 }, onLoad: function (options) { console.log('商品详情页面加载,参数:', options); // 处理登录状态检查 if (options.needLogin === 'true' || options.needLogin === true) { console.log('检测到需要登录,显示登录提示弹窗'); // 延迟显示登录弹窗,确保页面完全加载 setTimeout(() => { this.setData({ showOneKeyLoginModal: true }); }, 500); } // 解析传入的商品数据 let goodsData = null; if (options.goodsData) { try { goodsData = JSON.parse(decodeURIComponent(options.goodsData)); console.log('解析后的商品数据:', goodsData); // 优先使用传入的商品数据中的联系人信息 this.setData({ goodsDetail: goodsData, fromSeller: options.fromSeller === 'true', isFavorite: goodsData.isFavorite || false // 初始化收藏状态 }); } catch (error) { console.error('解析商品数据失败:', error); } } // 从商品数据中提取商品ID let productId; if (goodsData && (goodsData.id || goodsData.productId)) { productId = goodsData.id || goodsData.productId; } else if (options.productId) { productId = options.productId; } else { console.error('未找到商品ID'); wx.showToast({ title: '商品信息有误', icon: 'none', duration: 2000 }); // 2秒后返回上一页 setTimeout(() => { wx.navigateBack(); }, 2000); return; } console.log('最终使用的商品ID:', productId); // 加载商品详情(即使已有goodsData,也调用API获取最新数据) this.loadGoodsDetail(productId, goodsData); // 添加收藏状态变化事件监听 const app = getApp(); this.favoriteChangedHandler = (data) => { console.log('收到收藏状态变化通知:', data); // 如果通知的商品ID与当前页面的商品ID相同,则更新收藏状态 if (data.productId === String(productId) || data.productId === String(this.data.goodsDetail.id)) { this.setData({ isFavorite: data.isFavorite }); } }; app.eventBus.on('favoriteChanged', this.favoriteChangedHandler); }, onUnload: function () { // 页面卸载时移除事件监听 const app = getApp(); if (this.favoriteChangedHandler) { app.eventBus.off('favoriteChanged', this.favoriteChangedHandler); console.log('移除收藏状态变化事件监听'); } }, loadGoodsDetail: function (productId, preloadedData = null) { // 首先显示预加载的数据,确保UI快速响应 if (preloadedData) { console.log('使用预加载数据显示UI'); } console.log('调用API获取商品详情,productId:', productId); API.getProductDetail({ productId: productId }) .then(res => { console.log('获取商品详情成功:', res); if (res && res.code === 200 && res.data) { // 从本地存储获取已预约商品ID列表 const reservedGoodsIds = wx.getStorageSync('reservedGoodsIds') || []; const product = res.data; // 详细检查联系人相关字段 - 特别关注数据库字段名 console.log('===== 数据库字段名详细检查 ====='); console.log('- 数据库字段 product_contact:', product.product_contact, '(类型:', typeof product.product_contact, ')'); console.log('- 数据库字段 contact_phone:', product.contact_phone, '(类型:', typeof product.contact_phone, ')'); console.log('- 其他可能的字段:'); console.log(' - contactPhone:', product.contactPhone); console.log(' - phone:', product.phone); console.log(' - contact:', product.contact); console.log(' - name:', product.name); console.log(' - id:', product.id); console.log(' - productId:', product.productId); // 检查完整的API响应字段,确保不错过任何重要信息 console.log('API响应完整字段列表:', Object.keys(product).sort()); // 只过滤hidden状态的商品 if (product.status === 'hidden') { wx.showToast({ title: '商品已下架', icon: 'none', duration: 2000 }); // 2秒后返回上一页 setTimeout(() => { wx.navigateBack(); }, 2000); return; } // 确保商品ID的一致性 const productIdStr = String(product.productId || product.id); // 关键修改:直接使用API返回的reservedCount值,这个值已经是从favorites表中统计的收藏数量 // 不再使用selected或reservationCount字段计算,确保收藏人数显示正确 const finalReservationCount = product.reservedCount || 0; // 处理grossWeight为null或无效的情况,返回空字符串以支持文字输入 const grossWeightValue = product.grossWeight !== null && product.grossWeight !== undefined ? product.grossWeight : ''; // 转换supplyStatus字段值 let supplyStatusValue = product.supplyStatus || ''; // 将"平台货源"、"三方认证"、"三方未认证"修改为"预售"、"现货" if (supplyStatusValue === '平台货源' || supplyStatusValue === '三方认证') { supplyStatusValue = '现货'; } else if (supplyStatusValue === '三方未认证') { supplyStatusValue = '预售'; } // 关键修改:优先使用预加载数据中的联系人信息,与buyer页面保持一致 let contactPhone = ''; let contactName = ''; let region = ''; // 首先检查预加载数据,与buyer页面保持一致 if (preloadedData) { // 直接从预加载数据中获取联系人信息,与buyer页面保持一致 contactPhone = preloadedData.contact_phone || preloadedData.contactPhone || preloadedData.phone || ''; contactName = preloadedData.product_contact || preloadedData.contact || preloadedData.contactName || ''; region = preloadedData.region || ''; console.log('从预加载数据获取联系人信息:', { contactName, contactPhone, region }); console.log('preloadedData product_contact:', preloadedData.product_contact, 'contact_phone:', preloadedData.contact_phone); } // 如果预加载数据中没有,则使用API返回的数据 if (!contactPhone && product) { contactPhone = product.contact_phone || product.contactPhone || product.phone || ''; } if (!contactName && product) { contactName = product.product_contact || product.contact || product.contactName || ''; } if (!region && product && product.region) { region = product.region || ''; } // 确保联系人信息不为空 if (!contactPhone) { contactPhone = product.contact_phone || product.contactPhone || product.phone || '暂无联系电话'; } if (!contactName) { contactName = product.product_contact || product.contact || product.contactName || '联系人信息暂不可用'; } if (!region && product.region) { region = extractProvince(product.region); } // 如果region仍为空,尝试从预加载数据中提取 if (!region && preloadedData && preloadedData.region) { region = extractProvince(preloadedData.region); } if (!region) region = '地区未知'; // 转换商品数据格式 const formattedGoods = { id: productIdStr, productId: productIdStr, // 直接使用数据库字段名 name: product.productName || product.name || '商品名称', price: product.price, minOrder: product.minOrder || product.quantity, yolk: product.yolk, spec: product.spec || product.specification || '暂无规格', region: region, // 保留原始字段引用,确保数据完整性 imageUrls: product.imageUrls || product.images || [], displayGrossWeight: formatGrossWeight(grossWeightValue, product.weight), isReserved: reservedGoodsIds.some(itemId => String(itemId) === productIdStr), created_at: product.created_at || product.createdAt, updated_at: product.updated_at || product.updatedAt, status: product.status, supplyStatus: supplyStatusValue, sourceType: product.sourceType || '', sourceTypeColor: getSourceTypeColor(product.sourceType), // 复制原始产品对象中的所有字段,确保不丢失任何数据 ...product, // 合并预加载数据中的字段 ...(preloadedData || {}), // 直接使用数据库字段名,确保与表结构完全一致,放在后面覆盖前面的值 product_contact: contactName, contact_phone: contactPhone, // 确保reservedCount字段使用我们计算得到的值,放在最后以覆盖其他来源的值 reservedCount: finalReservationCount }; console.log('最终格式化后的数据:', { product_contact: formattedGoods.product_contact, contact_phone: formattedGoods.contact_phone, region: formattedGoods.region }); // 保存预加载数据中的isFavorite状态,确保是布尔值 const preloadedFavoriteStatus = preloadedData ? (preloadedData.isFavorite || false) : false; this.setData({ goodsDetail: formattedGoods, isFavorite: preloadedFavoriteStatus // 优先使用预加载数据中的收藏状态 }); // 只有当没有预加载的收藏状态时,才从服务器加载 if (!preloadedData || preloadedData.isFavorite === undefined) { this.loadGoodsFavoriteStatus(productIdStr); } } else { wx.showToast({ title: '获取商品详情失败', icon: 'none', duration: 2000 }); } }) .catch(err => { console.error('获取商品详情失败:', err); wx.showToast({ title: '获取商品详情失败', icon: 'none', duration: 2000 }); }) .finally(() => { wx.hideLoading(); }); }, // 加载商品的收藏状态 loadGoodsFavoriteStatus: function (productId) { const openid = wx.getStorageSync('openid'); const userId = wx.getStorageSync('userId'); // 如果用户未登录,不加载收藏状态 if (!openid || !userId) { return; } // 获取用户手机号 let userPhone = ''; try { const users = wx.getStorageSync('users') || {}; if (userId && users[userId] && users[userId].phoneNumber) { userPhone = users[userId].phoneNumber; } else { const userInfo = wx.getStorageSync('userInfo'); if (userInfo && userInfo.phoneNumber) { userPhone = userInfo.phoneNumber; } else { userPhone = wx.getStorageSync('phoneNumber'); } } } catch (e) { console.error('获取用户手机号失败:', e); } if (!userPhone) { return; } // 调用API获取用户收藏列表 API.getFavorites(userPhone) .then(res => { if (res && res.code === 200) { // 检查API返回的数据结构,确保我们获取到正确的收藏列表 let favoritesList = []; if (Array.isArray(res.data)) { favoritesList = res.data; } else if (res.data && Array.isArray(res.data.favorites)) { favoritesList = res.data.favorites; } else if (res.data && Array.isArray(res.data.data)) { favoritesList = res.data.data; } console.log('获取收藏列表成功,处理后的数据:', favoritesList); // 从收藏列表中提取商品ID const favoriteProductIds = favoritesList.map(item => { // 尝试从不同的字段名获取商品ID return String(item.productId || item.id || item.product_id || ''); }).filter(id => id !== ''); // 过滤掉空字符串 console.log('收藏商品ID列表:', favoriteProductIds); console.log('当前商品ID:', String(productId)); const isFavorite = favoriteProductIds.includes(String(productId)); console.log('计算得到的收藏状态:', isFavorite); // 只有当从收藏列表中明确获取到结果时,才更新收藏状态 // 避免因为API返回数据结构问题导致收藏状态被错误覆盖 this.setData({ isFavorite: isFavorite }); } }) .catch(err => { console.error('获取收藏状态失败:', err); // 注意:这里不要更新isFavorite状态,保持之前的状态 }); }, // 添加收藏 addFavorite: function () { const productId = String(this.data.goodsDetail.id || this.data.goodsDetail.productId); console.log('用户点击了收藏按钮,商品ID:', productId); // 检查用户登录状态 const openid = wx.getStorageSync('openid'); const userId = wx.getStorageSync('userId'); if (!openid || !userId) { console.log('用户未登录,显示一键登录弹窗'); // 显示登录弹窗 this.setData({ showOneKeyLoginModal: true }); return; } wx.showLoading({ title: '正在收藏...' }); // 调用API添加收藏 API.addFavorite(productId) .then(res => { wx.hideLoading(); console.log('添加收藏成功:', res); // 更新商品的收藏状态 this.setData({ isFavorite: true }); // 触发全局事件,通知其他页面收藏状态已更改 const app = getApp(); app.eventBus.emit('favoriteChanged', { productId: productId, isFavorite: true }); // 显示成功提示 wx.showToast({ title: '收藏成功', icon: 'success', duration: 1500 }); }) .catch(err => { wx.hideLoading(); console.error('添加收藏失败:', err); // 显示错误提示 wx.showToast({ title: '收藏失败,请稍后重试', icon: 'none', duration: 2000 }); }); }, // 取消收藏 cancelFavorite: function () { const productId = String(this.data.goodsDetail.id || this.data.goodsDetail.productId); console.log('用户点击了取消收藏按钮,商品ID:', productId); // 检查用户登录状态 const openid = wx.getStorageSync('openid'); const userId = wx.getStorageSync('userId'); if (!openid || !userId) { console.log('用户未登录,显示一键登录弹窗'); // 由于商品详情页可能没有登录弹窗,这里直接提示用户登录 wx.showToast({ title: '请先登录', icon: 'none', duration: 2000 }); return; } wx.showLoading({ title: '正在取消收藏...' }); // 调用API取消收藏 API.cancelFavorite(productId) .then(res => { wx.hideLoading(); console.log('取消收藏成功:', res); // 更新商品的收藏状态 this.setData({ isFavorite: false }); // 触发全局事件,通知其他页面收藏状态已更改 const app = getApp(); app.eventBus.emit('favoriteChanged', { productId: productId, isFavorite: false }); // 显示成功提示 wx.showToast({ title: '取消收藏成功', icon: 'success', duration: 1500 }); }) .catch(err => { wx.hideLoading(); console.error('取消收藏失败:', err); // 显示错误提示 wx.showToast({ title: '取消收藏失败,请稍后重试', icon: 'none', duration: 2000 }); }); }, // 处理收藏按钮点击事件 onFavoriteClick: function () { if (this.data.isFavorite) { this.cancelFavorite(); } else { this.addFavorite(); } }, // 预览图片 previewImage(e) { const { urls, index } = e.currentTarget.dataset; if (!urls || urls.length === 0) { wx.showToast({ title: '没有图片可预览', icon: 'none' }); return; } this.setData({ showImagePreview: true, previewImageUrls: urls, previewImageIndex: parseInt(index || 0) }); this.resetZoom(); }, // 关闭图片预览 closeImagePreview() { this.setData({ showImagePreview: false }); this.resetZoom(); }, // 重置缩放状态 resetZoom() { this.setData({ scale: 1, lastScale: 1, offsetX: 0, offsetY: 0, initialTouch: null }); }, // 图片预览切换 onPreviewImageChange(e) { this.setData({ previewImageIndex: e.detail.current }); // 切换图片时重置缩放状态 this.resetZoom(); }, // 处理图片点击事件(单击/双击判断) handleImageTap(e) { const currentTime = Date.now(); const lastTapTime = this.data.lastTapTime || 0; // 判断是否为双击(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) }); } }, // 计算两点之间的距离 calculateDistance(touch1, touch2) { const dx = touch2.clientX - touch1.clientX; const dy = touch2.clientY - touch1.clientY; return Math.sqrt(dx * dx + dy * dy); }, // 处理触摸开始事件 handleTouchStart(e) { console.log('触摸开始事件:', 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 }); }, // 拨打电话 makePhoneCall(e) { console.log('拨打电话事件:', e); const phoneNumber = e.currentTarget.dataset.phone; if (phoneNumber) { wx.showModal({ title: '联系人电话', content: phoneNumber, showCancel: true, cancelText: '取消', confirmText: '拨打', success: (res) => { if (res.confirm) { wx.makePhoneCall({ phoneNumber: phoneNumber, success: () => { console.log('拨打电话成功'); }, fail: (err) => { console.error('拨打电话失败', err); wx.showToast({ title: '拨打电话失败', icon: 'none' }); } }); } } }); } }, // 在线聊天 onChat(e) { console.log('在线咨询事件:', e); const { id } = e.currentTarget.dataset; if (!id) return; // 获取商品联系人信息 const contactName = this.data.goodsDetail.product_contact; const contactPhone = this.data.goodsDetail.contact_phone; // 检查是否有联系电话 if (!contactPhone) { wx.showToast({ title: '未找到联系电话', icon: 'none' }); return; } // 检查用户登录状态 const openid = wx.getStorageSync('openid'); const userId = wx.getStorageSync('userId'); if (!openid || !userId) { console.log('用户未登录,显示登录弹窗'); this.setData({ showOneKeyLoginModal: true }); return; } // 跳转到聊天界面或打开客服窗口 wx.showModal({ title: '在线咨询', content: `将为您连接到 ${contactName || '客服人员'}`, showCancel: true, cancelText: '取消', confirmText: '立即咨询', success: (res) => { if (res.confirm) { // 获取当前用户的手机号 let userPhone = ''; try { // 尝试从不同的存储位置获取手机号 const userInfo = wx.getStorageSync('userInfo'); if (userInfo && userInfo.phoneNumber) { userPhone = userInfo.phoneNumber; } else { // 尝试从其他可能的存储位置获取 const users = wx.getStorageSync('users') || {}; const userId = wx.getStorageSync('userId'); if (userId && users[userId] && users[userId].phoneNumber) { userPhone = users[userId].phoneNumber; } else { userPhone = wx.getStorageSync('phoneNumber'); } } } catch (e) { console.error('获取用户手机号失败:', e); } console.log('当前用户手机号:', userPhone); console.log('联系人信息:', { contactName, contactPhone }); // 验证手机号 if (!userPhone) { wx.showToast({ title: '请先登录获取手机号', icon: 'none' }); return; } // 验证联系人手机号 if (!contactPhone) { console.error('联系人手机号不存在'); wx.showToast({ title: '联系人信息不完整,请稍后重试', icon: 'none' }); return; } console.log('联系人手机号:', contactPhone); // 显示加载提示 wx.showLoading({ title: '正在建立聊天...', }); // 调用API创建聊天记录,确保用户和联系人之间的聊天记录是双向的 API.fixChatRecordsPair(userPhone, contactPhone).then(res => { console.log('聊天建立成功:', JSON.stringify(res, null, 2)); // 隐藏加载提示 wx.hideLoading(); // 使用联系人手机号作为聊天会话ID const chatSessionId = contactPhone; // 跳转到聊天页面,确保正确传递联系人手机号和用户名 wx.navigateTo({ url: `/pages/chat-detail/index?userId=${chatSessionId}&userName=${encodeURIComponent(contactName || '联系人')}&phone=${contactPhone}&isManager=true`, success: function () { console.log('成功跳转到聊天详情页'); }, fail: function (error) { console.error('跳转到聊天详情页失败:', error); wx.showToast({ title: '聊天功能开发中', icon: 'none' }); } }); }).catch(err => { console.error('建立聊天失败:', err); // 隐藏加载提示 wx.hideLoading(); wx.showToast({ title: '建立聊天失败,请重试', icon: 'none' }); }); } } }); }, /* 已移除:我想要(预约)功能 onClickWantInDetail(e) { console.log('我想要事件:', e); const { id } = e.currentTarget.dataset; if (!id) return; // 从本地存储获取openid const openid = wx.getStorageSync('openid'); console.log('openid:', openid); // 检查是否已登录 if (!openid) { // 如果未登录,显示授权登录弹窗 this.setData({ showAuthModal: true }); return; } // 获取已预约商品ID列表 let reservedGoodsIds = wx.getStorageSync('reservedGoodsIds') || []; // 检查是否已经预约过 if (reservedGoodsIds.some(itemId => String(itemId) === String(id))) { wx.showToast({ title: '您已经预约过该商品', icon: 'none', duration: 1500 }); return; } // 添加到已预约列表 reservedGoodsIds.push(id); wx.setStorageSync('reservedGoodsIds', reservedGoodsIds); // 更新页面状态 this.setData({ 'goodsDetail.isReserved': true }); // 调用API记录预约 API.reserveProduct({ id: id }) .then(res => { console.log('预约成功:', res); wx.showToast({ title: '预约成功', icon: 'success', duration: 1500 }); }) .catch(err => { console.error('预约失败:', err); // 如果API调用失败,从本地列表中移除 reservedGoodsIds = reservedGoodsIds.filter(itemId => String(itemId) !== String(id)); wx.setStorageSync('reservedGoodsIds', reservedGoodsIds); // 更新页面状态 this.setData({ 'goodsDetail.isReserved': false }); wx.showToast({ title: '预约失败,请重试', icon: 'none', duration: 1500 }); }); }, */ // 关闭登录弹窗 closeOneKeyLoginModal() { this.setData({ showOneKeyLoginModal: false }); }, // 处理手机号授权结果 onPhoneNumberResult(e) { console.log('getPhoneNumber响应:', e.detail); // 关闭登录弹窗 this.setData({ showOneKeyLoginModal: false }); // 用户点击拒绝授权 if (e.detail.errMsg === 'getPhoneNumber:fail user deny') { wx.showToast({ title: '需要授权手机号才能使用', icon: 'none', duration: 2000 }); return; } // 处理没有权限的情况 if (e.detail.errMsg === 'getPhoneNumber:fail no permission') { wx.showToast({ title: '当前环境无法获取手机号权限', icon: 'none', duration: 3000 }); return; } // 这里可以添加完整的登录处理逻辑 // 参考首页的 onGetPhoneNumber 函数 console.log('手机号授权成功,需要完整的登录流程处理'); // 由于详情页的登录处理比较复杂,建议跳转到首页处理 // 或者可以触发一个全局事件,让其他页面处理登录逻辑 const app = getApp(); if (app && app.globalData) { app.globalData.pendingPhoneAuth = e.detail; // 可以跳转到首页处理登录 wx.switchTab({ url: '/pages/index/index', success: () => { // 可以发送事件通知首页处理登录 wx.showToast({ title: '请在首页完成登录', icon: 'none', duration: 2000 }); } }); } }, // 返回上一页 goBack() { wx.navigateBack(); } });