// pages/goods-update/goods-update.js const API = require('../../utils/api.js') // 根据sourceType获取对应的颜色 function getSourceTypeColor(sourceType) { const colorMap = { '三方认证': '#4d9dff', '三方未认证': '#ff4d4f', '平台货源': '#2ad21f' }; return colorMap[sourceType] || '#4d9dff'; } // 媒体类型判断函数 function isVideoUrl(url) { if (!url || typeof url !== 'string') { return false; } // 转换为小写,确保大小写不敏感 const lowerUrl = url.toLowerCase(); // 支持的视频格式 const videoExtensions = ['.mp4', '.mov', '.avi', '.wmv', '.flv', '.webm', '.m4v', '.3gp']; // 检查URL是否以视频扩展名结尾 for (const ext of videoExtensions) { if (lowerUrl.endsWith(ext)) { return true; } } return false; } // 预处理媒体URL,返回包含type字段的媒体对象数组 function processMediaUrls(urls) { if (!urls || !Array.isArray(urls)) { return []; } return urls.map(url => { return { url: url, type: isVideoUrl(url) ? 'video' : 'image' }; }); } // 格式化毛重显示的辅助函数 function formatGrossWeight(grossWeight, weight) { if (grossWeight !== null && grossWeight !== undefined && grossWeight !== '') { return grossWeight; } if (weight !== null && weight !== undefined && weight !== '') { return weight; } 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; } // 格式化日期时间函数 function formatDateTime(dateString) { if (!dateString) return ''; // 尝试解析日期字符串 const date = new Date(dateString); // 检查是否是有效的日期对象 if (isNaN(date.getTime())) { // 如果解析失败,返回原始字符串 return dateString; } // 如果是 ISO 格式的字符串(包含 T 字符),则转换为本地时间格式 if (typeof dateString === 'string' && dateString.includes('T')) { const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); return `${year}-${month}-${day} ${hours}:${minutes}`; } // 对于其他格式的字符串,直接返回,不进行转换 return dateString; } // 处理净重件数对应数据 function processWeightAndQuantityData(weightSpecString, quantityString, specString) { console.log('===== 处理净重、件数和规格数据 ====='); console.log('输入参数:'); console.log('- weightSpecString:', weightSpecString, '(类型:', typeof weightSpecString, ')'); console.log('- quantityString:', quantityString, '(类型:', typeof quantityString, ')'); console.log('- specString:', specString, '(类型:', typeof specString, ')'); // 如果没有数据,返回空数组 if (!weightSpecString && !quantityString && !specString) { console.log('没有数据,返回空数组'); return []; } // 处理净重/规格字符串(它可能包含净重信息) let weightSpecArray = []; if (weightSpecString && typeof weightSpecString === 'string') { // 支持多种逗号分隔符:英文逗号、中文逗号、全角逗号 weightSpecArray = weightSpecString.split(/[,,、]/).map(item => item.trim()).filter(item => item); console.log('从字符串分割得到净重规格数组:', weightSpecArray); } else if (weightSpecString) { weightSpecArray = [String(weightSpecString)]; console.log('将净重规格转换为数组:', weightSpecArray); } // 处理件数字符串 let quantityArray = []; if (quantityString && typeof quantityString === 'string') { // 支持多种逗号分隔符:英文逗号、中文逗号、全角逗号 quantityArray = quantityString.split(/[,,、]/).map(item => item.trim()).filter(item => item); console.log('从字符串分割得到数量数组:', quantityArray); } else if (quantityString) { quantityArray = [String(quantityString)]; console.log('将数量转换为数组:', quantityArray); } // 获取最大长度,确保一一对应 const maxLength = Math.max(weightSpecArray.length, quantityArray.length); console.log('最大长度:', maxLength); const result = []; for (let i = 0; i < maxLength; i++) { const weightSpec = weightSpecArray[i] || ''; const quantity = quantityArray[i] || ''; console.log(`处理第${i}组数据: weightSpec=${weightSpec}, quantity=${quantity}`); // 处理净重规格显示格式 - 根据内容类型添加相应前缀 let weightSpecDisplay = ''; if (weightSpec) { if (weightSpec.includes('净重') || weightSpec.includes('毛重')) { // 如果已包含"净重"或"毛重"前缀,保持不变 weightSpecDisplay = weightSpec; } else { // 否则,根据内容自动判断添加前缀 if (weightSpec.includes('-')) { // 如果包含"-",认为是净重范围,添加"净重"前缀 weightSpecDisplay = `净重${weightSpec}`; } else { // 否则,认为是毛重,添加"毛重"前缀 weightSpecDisplay = `毛重${weightSpec}`; } } } // 处理件数显示格式 let quantityDisplay = quantity; if (quantity && !quantity.includes('件')) { // 如果不包含"件"后缀,添加"件"后缀 quantityDisplay = `${quantity}件`; } // 构建显示文本 let displayText = ''; if (weightSpecDisplay && quantityDisplay) { // 如果有净重和件数,格式为:净重XX-XX——XXX件 displayText = `${weightSpecDisplay}——${quantityDisplay}`; } else if (weightSpecDisplay) { // 只有净重 displayText = weightSpecDisplay; } else if (quantityDisplay) { // 只有件数 displayText = quantityDisplay; } if (displayText) { result.push({ display: displayText }); console.log(`添加显示文本: ${displayText}`); } } console.log('净重件数对应数据处理结果:', result); return result; } Page({ // 分享给朋友/群聊 onShareAppMessage() { const goodsDetail = this.data.goodsDetail || {}; const title = goodsDetail.name ? `优质鸡蛋 - ${goodsDetail.name}` : '优质鸡蛋货源'; return { title: title, path: `/pages/goods-update/goods-update?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, // 当前预览图片的索引 showEditModal: false, // 控制编辑弹窗显示 showSpecSelectModal: false, // 控制规格选择弹窗显示 modalSpecSearchKeyword: '', // 规格弹窗中的搜索关键词 filteredModalSpecOptions: [], // 弹窗中过滤后的规格选项 selectedModalSpecIndex: -1, // 弹窗中选中的规格索引 currentSpecMode: 'edit', // 当前规格选择模式:create 或 edit showNameSelectModal: false, // 控制商品名称选择弹窗显示 showYolkSelectModal: false, // 控制蛋黄选择弹窗显示 selectedNameIndex: -1, // 商品名称弹窗中选中的索引 selectedYolkIndex: -1,//蛋黄弹窗中选中的索引, // 商品名称选项列表 productNameOptions: ['罗曼粉', '伊莎粉', '罗曼灰', '海蓝灰', '海蓝褐', '绿壳', '粉一', '粉二', '粉八', '京粉1号', '京红', '京粉6号', '京粉3号', '农大系列', '黑鸡土蛋', '双黄蛋', '大午金凤', '黑凤'], // 蛋黄选项 yolkOptions: ['红心', '黄心', '双色'], // 规格选项 specOptions: ['格子装', '散托', '不限规格', '净重47+', '净重46-47', '净重45-46', '净重44-45', '净重43-44', '净重42-43', '净重41-42', '净重40-41', '净重39-40', '净重38-39', '净重37-39', '净重37-38', '净重36-38', '净重36-37', '净重35-36', '净重34-35', '净重33-34', '净重32-33', '净重32-34', '净重31-32', '净重30-35', '净重30-34', '净重30-32', '净重30-31', '净重29-31', '净重29-30', '净重28-29', '净重28以下', '毛重52以上', '毛重50-51', '毛重48-49', '毛重47-48', '毛重46-47', '毛重45-47', '毛重45-46', '毛重44-45', '毛重43-44', '毛重42-43', '毛重41-42', '毛重40-41', '毛重38-39', '毛重36-37', '毛重34-35', '毛重32-33', '毛重30-31', '毛重30以下'], // 编辑货源数据 editSupply: { id: '', imageUrls: [], name: '', price: '', minOrder: '', yolk: '', spec: '', region: '', grossWeight: '' }, // 图片缩放相关状态 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); // 解析传入的商品数据 let goodsData = null; if (options.goodsData) { try { goodsData = JSON.parse(decodeURIComponent(options.goodsData)); console.log('解析后的商品数据:', goodsData); // 优先使用传入的商品数据 this.setData({ goodsDetail: goodsData }); } catch (error) { console.error('解析商品数据失败:', error); } } // 从商品数据中提取商品ID let productId; if (goodsData && goodsData.productId) { // 优先使用字符串类型的productId productId = goodsData.productId; } else if (options.productId) { productId = options.productId; } else if (goodsData && goodsData.id) { // 如果没有productId,再尝试使用id productId = goodsData.id; } 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); }, 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) { const product = res.data; // 只过滤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值 const finalReservationCount = product.reservedCount || 0; // 确保imageUrls是数组 let imageUrls = product.imageUrls || []; if (!Array.isArray(imageUrls)) { console.error('imageUrls不是数组,转换为数组'); imageUrls = [imageUrls]; } // 处理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 = '预售'; } // 预处理媒体URL,添加类型信息 const mediaItems = processMediaUrls(imageUrls || []); console.log('预处理后的媒体数据:', mediaItems); // 处理净重、件数据和规格数据,获取一一对应的显示数组 // 注意:数据库中的规格字段包含净重信息,我们需要与件数数据正确匹配 // 首先处理净重和规格数据(它们可能都在spec字段中) let weightSpecString = ''; let quantityString = ''; // 检查规格字段是否包含净重或毛重信息 console.log('=== 数据库字段调试信息 ==='); console.log('product.spec:', product.spec); console.log('product.specification:', product.specification); console.log('product.quantity:', product.quantity); console.log('product.minOrder:', product.minOrder); if (product.spec && typeof product.spec === 'string' && (product.spec.includes('净重') || product.spec.includes('毛重'))) { // 如果规格字段包含净重或毛重信息,则使用该字段作为重量规格数据 weightSpecString = product.spec; console.log('使用规格字段作为重量规格数据:', weightSpecString); } else if (product.specification && typeof product.specification === 'string' && (product.specification.includes('净重') || product.specification.includes('毛重'))) { // 检查specification字段 weightSpecString = product.specification; console.log('使用specification字段作为重量规格数据:', weightSpecString); } else if (grossWeightValue) { // 如果有单独的重量字段,则使用该字段 weightSpecString = grossWeightValue; console.log('使用重量字段作为重量规格数据:', weightSpecString); } else { console.log('未找到重量规格数据'); } // 处理件数数据 console.log('=== 件数数据调试信息 ==='); console.log('原始件数数据:', product.quantity); console.log('原始minOrder数据:', product.minOrder); // 修复:与格式化数据保持一致,优先使用minOrder if (product.minOrder) { quantityString = String(product.minOrder); console.log('使用minOrder作为件数数据:', quantityString); } else if (product.quantity && typeof product.quantity === 'string') { quantityString = product.quantity; console.log('件数数据为字符串:', quantityString); } else if (product.quantity) { // 如果件数不是字符串,转换为字符串 quantityString = String(product.quantity); console.log('件数数据转换为字符串:', quantityString); } else { console.log('未找到件数数据'); } console.log('准备传递给processWeightAndQuantityData的数据:', { weightSpecString: weightSpecString, quantityString: quantityString }); const weightQuantityData = processWeightAndQuantityData(weightSpecString, quantityString, ''); console.log('=== 处理结果调试信息 ==='); console.log('weightSpecString:', weightSpecString); console.log('quantityString:', quantityString); console.log('weightQuantityData处理结果:', weightQuantityData); // 处理规格信息,生成格式化的specInfo let specInfo = []; const spec = product.spec || product.specification || ''; const minOrder = product.minOrder || product.quantity; // 生成格式化的规格信息 if (spec && minOrder) { // 如果有规格和件数,生成格式:"毛重48-49——200件" if (grossWeightValue) { specInfo.push(`毛重${grossWeightValue}——${minOrder}件`); } else { specInfo.push(`${spec}——${minOrder}件`); } } else if (spec) { specInfo.push(spec); } else if (grossWeightValue) { specInfo.push(`毛重${grossWeightValue}`); } // 确定creatorName - 优先使用预加载数据,然后使用与goods页面相同的逻辑 console.log('产品seller信息:', JSON.stringify(product.seller)); console.log('预加载数据:', preloadedData); // 优先使用预加载数据中的creatorName,如果没有则使用API返回的数据 let creatorName; if (preloadedData && preloadedData.creatorName) { creatorName = preloadedData.creatorName; console.log('使用预加载数据中的creatorName:', creatorName); } else { creatorName = product.seller?.nickName || product.seller?.sellerNickName || product.seller?.name || product.name || '未知'; console.log('使用API返回数据生成creatorName:', creatorName); } // 格式化创建时间 const createdAt = preloadedData?.created_at || preloadedData?.createdAt || product.created_at || product.createdAt; const formattedCreatedAt = formatDateTime(createdAt); console.log('formattedCreatedAt:', formattedCreatedAt); // 详细追踪地区信息 console.log('=== 地区信息详细追踪 ==='); console.log('预加载数据中的region:', preloadedData?.region); console.log('原始product.region:', product.region, '(类型:', typeof product.region, ')'); console.log('product是否有region属性:', 'region' in product); // 确定最终的地区值 - 优先使用预加载数据 const finalRegion = preloadedData?.region || product.region || product.area || product.location || '暂无'; console.log('finalRegion:', finalRegion); // 转换商品数据格式 const formattedGoods = { id: productIdStr, productId: productIdStr, // 直接使用数据库字段名 name: product.productName || product.name || '商品名称', price: product.price, minOrder: minOrder, yolk: product.yolk, spec: spec, specInfo: specInfo, // 添加格式化的规格信息 // 保留原始字段引用,确保数据完整性 imageUrls: imageUrls || [], // 添加预处理后的媒体数据,包含类型信息 mediaItems: mediaItems, displayGrossWeight: formatGrossWeight(grossWeightValue, product.weight), 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), // 添加净重和件数的一一对应数据 weightQuantityData: weightQuantityData, // 格式化创建时间 formattedCreatedAt: formattedCreatedAt, // 创建者信息 creatorName: creatorName, // 地区信息(先设置,后面会被覆盖) region: finalRegion, // 复制原始产品对象中的所有字段,确保不丢失任何数据 ...product, // 添加产品包装字段(放在product之后,确保不被覆盖) producting: product.producting || '', // 添加货源描述字段 description: product.description || product.remark || '', // 直接使用数据库字段名,确保与表结构完全一致,放在后面覆盖前面的值 product_contact: product.product_contact || '联系人信息暂不可用', contact_phone: product.contact_phone || '暂无联系电话', // 确保地区信息正确显示,放在最后覆盖所有来源的值 region: finalRegion, // 确保reservedCount字段使用我们计算得到的值,放在最后以覆盖其他来源的值 reservedCount: finalReservationCount, // 添加新鲜程度字段 freshness: product.freshness || '' }; console.log('最终formattedGoods.region:', formattedGoods.region); // 调试输出完整的formattedGoods对象 console.log('最终格式化的商品数据:', JSON.stringify(formattedGoods, null, 2)); this.setData({ goodsDetail: formattedGoods }); } else { wx.showToast({ title: '获取商品详情失败', icon: 'none', duration: 2000 }); } }) .catch(err => { console.error('获取商品详情失败:', err); wx.showToast({ title: '获取商品详情失败', icon: 'none', duration: 2000 }); }) .finally(() => { wx.hideLoading(); }); }, // 显示编辑弹窗 showEditModal: function() { console.log('显示编辑弹窗'); const goodsDetail = this.data.goodsDetail; // 设置编辑数据 this.setData({ editSupply: { id: goodsDetail.id || goodsDetail.productId, imageUrls: goodsDetail.imageUrls || [], name: goodsDetail.name || '', price: goodsDetail.price || '', minOrder: goodsDetail.minOrder || '', yolk: goodsDetail.yolk || '', spec: goodsDetail.spec || '', region: goodsDetail.region || '', grossWeight: goodsDetail.grossWeight || '' }, showEditModal: true }); }, // 隐藏编辑弹窗 hideEditModal: function() { this.setData({ showEditModal: false }); }, // 保存编辑 saveEdit: function() { console.log('保存编辑'); const editSupply = this.data.editSupply; // 验证必填字段 if (!editSupply.name) { wx.showToast({ title: '请填写商品名称', icon: 'none', duration: 2000 }); return; } if (!editSupply.price) { wx.showToast({ title: '请填写价格', icon: 'none', duration: 2000 }); return; } wx.showLoading({ title: '保存中...', mask: true }); // 调用API更新商品 const productId = editSupply.productId || editSupply.id; API.editProduct(productId, { productName: editSupply.name, price: editSupply.price, quantity: Number(editSupply.minOrder), grossWeight: editSupply.grossWeight !== undefined && editSupply.grossWeight !== null && editSupply.grossWeight !== '' ? editSupply.grossWeight : "", yolk: editSupply.yolk, specification: editSupply.spec || '', region: editSupply.region || '', imageUrls: editSupply.imageUrls || [], }) .then(res => { wx.hideLoading(); console.log('更新商品成功:', res); if (res && res.code === 200) { wx.showToast({ title: '更新成功', icon: 'success', duration: 2000 }); // 隐藏编辑弹窗 this.hideEditModal(); // 重新加载商品详情 this.loadGoodsDetail(productId); } else { wx.showToast({ title: '更新失败', icon: 'none', duration: 2000 }); } }) .catch(err => { wx.hideLoading(); console.error('更新商品失败:', err); wx.showToast({ title: '更新失败', icon: 'none', duration: 2000 }); }); }, // 准备上架 preparePublishSupply: function() { console.log('准备上架商品'); const goodsDetail = this.data.goodsDetail; const productId = goodsDetail.id || goodsDetail.productId; wx.showModal({ title: '确认上架', content: '确定要上架此商品吗?', success: (res) => { if (res.confirm) { this.publishSupply(productId); } } }); }, // 上架商品 publishSupply: function(productId) { console.log('上架商品,productId:', productId); wx.showLoading({ title: '上架中...', mask: true }); // 获取商品数据 const goodsDetail = this.data.goodsDetail; // 调用API上架商品 API.publishProduct(goodsDetail) .then(res => { wx.hideLoading(); console.log('上架商品成功:', res); if (res && res.code === 200) { wx.showToast({ title: '上架成功', icon: 'success', duration: 2000 }); // 重新加载商品详情 this.loadGoodsDetail(productId); } else { wx.showToast({ title: '上架失败', icon: 'none', duration: 2000 }); } }) .catch(err => { wx.hideLoading(); console.error('上架商品失败:', err); wx.showToast({ title: '上架失败', icon: 'none', duration: 2000 }); }); }, // 编辑输入处理 onEditInput: function(e) { const field = e.currentTarget.dataset.field; const value = e.detail.value; this.setData({ [`editSupply.${field}`]: value }); }, // 打开规格选择弹窗(编辑模式) onEditSpecChange: function() { console.log('打开规格选择弹窗(编辑模式)'); const editSupply = this.data.editSupply; const specOptions = this.data.specOptions; // 查找当前规格在选项中的索引 const currentSpecIndex = specOptions.indexOf(editSupply.spec); this.setData({ showSpecSelectModal: true, currentSpecMode: 'edit', selectedModalSpecIndex: currentSpecIndex >= 0 ? currentSpecIndex : -1, modalSpecSearchKeyword: '', filteredModalSpecOptions: specOptions }); }, // 关闭规格选择弹窗 closeSpecSelectModal: function() { this.setData({ showSpecSelectModal: false }); }, // 规格弹窗搜索输入 onModalSpecSearchInput: function(e) { const keyword = e.detail.value; const specOptions = this.data.specOptions; // 过滤规格选项 const filteredOptions = specOptions.filter(option => { return option.includes(keyword); }); this.setData({ modalSpecSearchKeyword: keyword, filteredModalSpecOptions: filteredOptions, selectedModalSpecIndex: -1 }); }, // 清除规格弹窗搜索关键词 clearModalSpecSearch: function() { this.setData({ modalSpecSearchKeyword: '', filteredModalSpecOptions: this.data.specOptions, selectedModalSpecIndex: -1 }); }, // 选择规格 onModalSpecSelect: function(e) { const index = e.currentTarget.dataset.index; this.setData({ selectedModalSpecIndex: index }); }, // 确认规格选择 confirmSpecSelection: function() { const selectedIndex = this.data.selectedModalSpecIndex; const filteredOptions = this.data.filteredModalSpecOptions; const currentSpecMode = this.data.currentSpecMode; if (selectedIndex >= 0 && selectedIndex < filteredOptions.length) { const selectedSpec = filteredOptions[selectedIndex]; if (currentSpecMode === 'edit') { // 编辑模式 this.setData({ [`editSupply.spec`]: selectedSpec }); } this.closeSpecSelectModal(); } }, // 打开商品名称选择弹窗 openNameSelectModal: function() { console.log('打开商品名称选择弹窗'); const editSupply = this.data.editSupply; const productNameOptions = this.data.productNameOptions; // 查找当前商品名称在选项中的索引 const currentNameIndex = productNameOptions.indexOf(editSupply.name); this.setData({ showNameSelectModal: true, selectedNameIndex: currentNameIndex >= 0 ? currentNameIndex : -1 }); }, // 关闭商品名称选择弹窗 closeNameSelectModal: function() { this.setData({ showNameSelectModal: false }); }, // 选择商品名称 onNameSelect: function(e) { const index = e.currentTarget.dataset.index; this.setData({ selectedNameIndex: index }); }, // 确认商品名称选择 confirmNameSelection: function() { const selectedIndex = this.data.selectedNameIndex; const productNameOptions = this.data.productNameOptions; if (selectedIndex >= 0 && selectedIndex < productNameOptions.length) { const selectedName = productNameOptions[selectedIndex]; this.setData({ [`editSupply.name`]: selectedName, showNameSelectModal: false }); } }, // 打开蛋黄选择弹窗 openYolkSelectModal: function() { console.log('打开蛋黄选择弹窗'); const editSupply = this.data.editSupply; const yolkOptions = this.data.yolkOptions; // 查找当前蛋黄在选项中的索引 const currentYolkIndex = yolkOptions.indexOf(editSupply.yolk); this.setData({ showYolkSelectModal: true, selectedYolkIndex: currentYolkIndex >= 0 ? currentYolkIndex : -1 }); }, // 关闭蛋黄选择弹窗 closeYolkSelectModal: function() { this.setData({ showYolkSelectModal: false }); }, // 选择蛋黄 onYolkSelect: function(e) { const index = e.currentTarget.dataset.index; this.setData({ selectedYolkIndex: index }); }, // 确认蛋黄选择 confirmYolkSelection: function() { const selectedIndex = this.data.selectedYolkIndex; const yolkOptions = this.data.yolkOptions; if (selectedIndex >= 0 && selectedIndex < yolkOptions.length) { const selectedYolk = yolkOptions[selectedIndex]; this.setData({ [`editSupply.yolk`]: selectedYolk, showYolkSelectModal: false }); } }, // 选择图片 chooseImage: function(e) { const type = e.currentTarget.dataset.type; const maxCount = 5; const currentCount = type === 'edit' ? this.data.editSupply.imageUrls.length : 0; const canChooseCount = maxCount - currentCount; if (canChooseCount <= 0) { wx.showToast({ title: '最多只能上传5张图片', icon: 'none', duration: 2000 }); return; } wx.chooseImage({ count: canChooseCount, sizeType: ['compressed'], sourceType: ['album', 'camera'], success: (res) => { const tempFilePaths = res.tempFilePaths; // 上传图片到服务器 this.uploadImages(tempFilePaths, type); }, fail: (err) => { console.error('选择图片失败:', err); } }); }, // 上传图片 uploadImages: function(filePaths, type) { console.log('上传图片,type:', type); wx.showLoading({ title: '上传中...', mask: true }); // 这里应该调用API上传图片,获取图片URL // 由于没有具体的上传API,这里模拟上传成功 setTimeout(() => { wx.hideLoading(); // 模拟上传成功,使用临时文件路径作为图片URL if (type === 'edit') { const editSupply = this.data.editSupply; const newImageUrls = [...editSupply.imageUrls, ...filePaths]; this.setData({ [`editSupply.imageUrls`]: newImageUrls }); } wx.showToast({ title: '上传成功', icon: 'success', duration: 1500 }); }, 1500); }, // 删除图片 deleteImage: function(e) { const index = e.currentTarget.dataset.index; const type = e.currentTarget.dataset.type; if (type === 'edit') { const editSupply = this.data.editSupply; const newImageUrls = editSupply.imageUrls.filter((item, idx) => idx !== index); this.setData({ [`editSupply.imageUrls`]: newImageUrls }); } }, // 预览图片 previewImage: function(e) { const urls = e.currentTarget.dataset.urls; const index = e.currentTarget.dataset.index; if (!urls || urls.length === 0) { wx.showToast({ title: '没有内容可预览', icon: 'none' }); return; } this.setData({ showImagePreview: true, previewImageUrls: urls, previewImageIndex: parseInt(index || 0) }); this.resetZoom(); }, // 关闭图片预览 closeImagePreview: function() { this.setData({ showImagePreview: false }); this.resetZoom(); }, // 重置缩放状态 resetZoom: function() { this.setData({ scale: 1, lastScale: 1, offsetX: 0, offsetY: 0, initialTouch: null }); }, // 图片预览切换 onPreviewImageChange: function(e) { this.setData({ previewImageIndex: e.detail.current }); // 切换图片时重置缩放状态 this.resetZoom(); }, // 处理图片点击事件(单击/双击判断) handleImageTap: function(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: function(touch1, touch2) { const dx = touch2.clientX - touch1.clientX; const dy = touch2.clientY - touch1.clientY; return Math.sqrt(dx * dx + dy * dy); }, // 处理触摸开始事件 handleTouchStart: function(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: function(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: function(e) { this.setData({ isScaling: false, lastScale: this.data.scale, initialTouch: null }); } });