Page({ data: { productName: '', specifications: [], loading: false, error: '' }, onLoad(options) { let productName = ''; // 首先检查URL参数 if (options.productName) { productName = options.productName; } else { // 然后检查本地存储(用于wx.switchTab导航) productName = wx.getStorageSync('selectedProductName') || ''; // 清除本地存储中的商品名称,避免影响下次进入 if (productName) { wx.removeStorageSync('selectedProductName'); } } if (productName) { this.setData({ productName: productName }); this.loadSpecifications(productName); } else { // 如果没有商品名称参数,跳转到商品列表页面 wx.redirectTo({ url: '/pages/evaluate1/product-list' }); } }, loadSpecifications(productName) { this.setData({ loading: true, specifications: [] }); // 直接从本地存储获取商品数据,避免重复请求 const localGoods = wx.getStorageSync('goods') || []; console.log('从本地存储获取的商品数量:', localGoods.length); if (localGoods.length > 0) { this.processSpecifications(productName, localGoods); } else { // 如果本地没有数据,再请求服务器 const api = require('../../utils/api'); api.getProducts().then(products => { this.processSpecifications(productName, products); }).catch(err => { console.error('获取规格失败:', err); this.setData({ error: '获取规格失败,请稍后重试', loading: false }); }); } }, // 解析规格,提取类型(净重/毛重)和数值范围 parseSpecification(spec) { const weightMatch = spec.match(/(净重|毛重)(\d+)-(\d+)/); if (weightMatch) { const type = weightMatch[1]; // 净重或毛重 const min = parseFloat(weightMatch[2]); const max = parseFloat(weightMatch[3]); const avg = (min + max) / 2; return { type: type, min: min, max: max, avg: avg }; } return null; }, processSpecifications(productName, products) { console.log('处理的商品数据数量:', products.length); console.log('当前处理的商品名称:', productName); // 检查products是否为空 if (!products || products.length === 0) { console.error('商品数据为空'); this.setData({ error: '商品数据为空', loading: false }); return; } // 过滤出当前商品名称的所有商品 const filteredProducts = products.filter(product => { const match = product.productName === productName; console.log('商品:', product.productName, '规格:', product.specification, '价格:', product.price, '匹配:', match); return match; }); console.log('过滤后的商品数量:', filteredProducts.length); console.log('过滤后的商品详情:', filteredProducts); // 检查filteredProducts是否为空 if (filteredProducts.length === 0) { console.error('未找到商品名称为"' + productName + '"的商品'); this.setData({ error: '未找到对应商品名称的商品', loading: false }); return; } // 提取规格和价格,处理可能的空值和空格 const specPriceMap = {}; filteredProducts.forEach((product, productIndex) => { const specStr = (product.specification || product.spec || '').trim(); const price = product.price || ''; console.log(`处理第${productIndex + 1}个商品: 规格字符串='${specStr}', 价格字符串='${price}'`); if (specStr.length > 0) { // 处理逗号分隔的多个规格,确保每个规格都被正确分割 // 首先按逗号分割 let specs = specStr.split(',').map(spec => spec.trim()).filter(spec => spec.length > 0); // 进一步处理规格,确保每个规格都是独立的 const processedSpecs = []; specs.forEach(spec => { // 检查规格是否包含多个规格(例如:"净重29-30,净重31-32") if (spec.includes(',')) { // 按中文逗号分割 const subSpecs = spec.split(',').map(s => s.trim()).filter(s => s.length > 0); processedSpecs.push(...subSpecs); } else { processedSpecs.push(spec); } }); specs = processedSpecs; // 处理逗号分隔的多个价格 const prices = (price || '').split(',').map(p => p.trim()); console.log(`规格数组:`, specs); console.log(`价格数组:`, prices); // 将规格和价格配对 specs.forEach((spec, index) => { if (spec.length > 0) { // 确保价格索引不超出范围 const priceIndex = index % prices.length; const matchedPrice = prices[priceIndex] || ''; console.log(`规格'${spec}' 配对价格: '${matchedPrice}'`); // 只有当价格不为空时才添加该规格 if (matchedPrice) { // 收集相同规格的所有价格,以便计算平均值 if (!specPriceMap[spec]) { specPriceMap[spec] = []; } specPriceMap[spec].push(matchedPrice); } else { console.log(`规格'${spec}' 价格为空,不添加`); } } }); } }); // 计算每个规格的平均价格 const specAvgPriceMap = {}; Object.keys(specPriceMap).forEach(spec => { const prices = specPriceMap[spec]; // 过滤掉非数字价格 const validPrices = prices.filter(price => !isNaN(parseFloat(price))); if (validPrices.length > 0) { // 计算平均价格 const sum = validPrices.reduce((acc, price) => acc + parseFloat(price), 0); const avgPrice = sum / validPrices.length; specAvgPriceMap[spec] = avgPrice.toFixed(2); console.log(`规格'${spec}' 的平均价格: ${specAvgPriceMap[spec]} (基于 ${validPrices.length} 个价格)`); } else { // 如果没有有效价格,使用第一个价格(可能是非数字) specAvgPriceMap[spec] = prices[0] || ''; console.log(`规格'${spec}' 没有有效价格,使用: ${specAvgPriceMap[spec]}`); } }); console.log('规格平均价格映射:', specAvgPriceMap); console.log('规格价格映射:', specPriceMap); // 检查specAvgPriceMap是否为空 if (Object.keys(specAvgPriceMap).length === 0) { console.error('未提取到商品名称为"' + productName + '"的有效规格'); this.setData({ error: '未提取到商品名称为"' + productName + '"的有效规格', loading: false }); return; } // 转换为规格对象数组 const specifications = Object.keys(specAvgPriceMap).map(spec => { const price = specAvgPriceMap[spec]; console.log(`最终规格'${spec}' 对应平均价格: '${price}'`); // 解析规格 const specInfo = this.parseSpecification(spec); let finalPrice = price; let finalPriceText = price; // 根据规格类型和价格水平计算最终价格 if (specInfo && parseFloat(price) < 10) { if (specInfo.type === '净重') { // 净重:规格平均值 × 价格 finalPrice = specInfo.avg * parseFloat(price); finalPriceText = finalPrice.toFixed(2); console.log(`规格'${spec}' 是净重,计算最终价格: ${finalPriceText}`); } else if (specInfo.type === '毛重') { // 毛重:(规格平均值 - 5) × 价格 finalPrice = (specInfo.avg - 5) * parseFloat(price); finalPriceText = finalPrice.toFixed(2); console.log(`规格'${spec}' 是毛重,计算最终价格: ${finalPriceText}`); } } return { name: spec, price: price, priceText: price, finalPrice: finalPrice, finalPriceText: finalPriceText }; }); console.log('提取的规格和价格:', specifications); this.setData({ specifications: specifications, error: '', // 清除之前的错误 loading: false }); }, // 跳转到规格详情页面 goToSpecDetail(e) { const specItem = e.currentTarget.dataset.spec; wx.navigateTo({ url: `/pages/evaluate1/spec-detail?productName=${encodeURIComponent(this.data.productName)}&specification=${encodeURIComponent(specItem.name)}&price=${encodeURIComponent(specItem.finalPrice)}` }); }, // 返回上一页 goBack() { wx.navigateBack(); }, // 返回商品列表页面 goBackToProductList() { wx.redirectTo({ url: '/pages/evaluate1/product-list' }); } });