Compare commits

...

32 Commits
Xfy ... main

Author SHA1 Message Date
TraeAI 6eb320c202 feat: 优化运费计算器功能,支持多个规格选择和自动匹配车型 3 minutes ago
TraeAI 03e6d805c0 优化运费计算器功能:调整价格计算逻辑,添加自动匹配车型功能 45 minutes ago
TraeAI 426f56affa 优化运费计算器功能:1. 自动匹配车型优先选择高栏车和平板车 2. 修复市场参考价过高问题 3. 优化布局显示 4. 删除费用明细和预计时效 4 hours ago
TraeAI fdbd49a0ae 修复售空状态下规格显示错误的问题 6 hours ago
TraeAI 71011970b9 恢复出发地自动设置功能 22 hours ago
TraeAI 297079020a 修改运费估算页面:从商品详情页进入时不再自动设置出发地 22 hours ago
TraeAI 263854cb0e 更新物流计算器页面:添加头像、优化标签样式、更新物流人员信息 23 hours ago
Default User 43b350a60f update 1 day ago
Trae AI 4d8710fd00 物流样式优化 2 days ago
User 16e319c302 添加跳转 2 days ago
Default User 5431341886 Merge branch 'main' of http://8.137.125.67:4000/SwtTt29/Mini-Program 2 days ago
Default User f92b8b768e 优化运费估算功能,将估算历史记录写入数据库 2 days ago
Trae AI b9c6c93599 优化对比和商品详情页面 2 days ago
User 23e59cd082 比价 2 days ago
Default User 4709720d19 修改售空未售空状态下的数量展示 3 days ago
Trae AI 715f007e89 修改商品详情整体布局和样式 3 days ago
Trae AI 339c155ce6 调整对比商品卡片展示数据 3 days ago
Trae AI c6e7f507e0 Merge branch 'main' of http://8.137.125.67:4000/SwtTt29/Mini-Program 4 days ago
Trae AI 610c70ee1c 优化字体 4 days ago
User 64e1b8cded Merge branch 'main' of http://8.137.125.67:4000/SwtTt29/Mini-Program 4 days ago
User 4b1461ed77 重写新接口api,添加查询速率 4 days ago
Trae AI f7358d2994 前端ui组件优化 4 days ago
Default User bcf5df3d08 进行限制,不对外展示运费估算功能 4 days ago
Trae AI f0202060b3 修改版本信息 4 days ago
Trae AI 4a6939d895 添加功能使用踪迹接口并写入数据库 4 days ago
Trae AI 43fbb57cd7 优化货源描述容器不兼容 4 days ago
Trae AI 0982db2b2e Merge branch 'main' of http://8.137.125.67:4000/SwtTt29/Mini-Program 4 days ago
Trae AI 3f844a2c43 对比价格ui优化 4 days ago
Default User 79aa3ef0a2 修复内部消息重复问题并使用followup_at作为跟进时间 4 days ago
Trae AI 1599530766 Merge branch 'main' of http://8.137.125.67:4000/SwtTt29/Mini-Program 4 days ago
Trae AI 8ca89d22a3 优化对比页面的选择步骤 4 days ago
User 6efd3fbd84 删除估价 4 days ago
  1. 8
      app.json
  2. 58
      custom-tab-bar/index.js
  3. 4
      custom-tab-bar/index.wxml
  4. 628
      pages/compare_price/index.js
  5. 51
      pages/compare_price/index.wxml
  6. 183
      pages/compare_price/index.wxss
  7. 552
      pages/evaluate2/index.js
  8. 5
      pages/evaluate2/index.json
  9. 108
      pages/evaluate2/index.wxml
  10. 671
      pages/evaluate2/index.wxss
  11. 845
      pages/evaluate2/one.js
  12. 5
      pages/evaluate2/one.json
  13. 221
      pages/evaluate2/one.wxml
  14. 857
      pages/evaluate2/one.wxss
  15. 526
      pages/evaluate2/product-list.js
  16. 6
      pages/evaluate2/product-list.json
  17. 97
      pages/evaluate2/product-list.wxml
  18. 608
      pages/evaluate2/product-list.wxss
  19. 125
      pages/evaluate2/spec-detail.js
  20. 5
      pages/evaluate2/spec-detail.json
  21. 82
      pages/evaluate2/spec-detail.wxml
  22. 465
      pages/evaluate2/spec-detail.wxss
  23. 2009
      pages/freight-calculator/index.js
  24. 263
      pages/freight-calculator/index.wxml
  25. 121
      pages/freight-calculator/index.wxss
  26. 483
      pages/goods-detail/goods-detail.js
  27. 99
      pages/goods-detail/goods-detail.wxml
  28. 225
      pages/goods-detail/goods-detail.wxss
  29. 13
      pages/index/index.js
  30. 8
      pages/index/index.wxml
  31. 8
      pages/index/index.wxss
  32. 4
      pages/profile/index.wxml
  33. 589
      server-example/server-mysql.js
  34. 479
      utils/api.js

8
app.json

@ -1,10 +1,6 @@
{
"pages": [
"pages/index/index",
"pages/evaluate2/index",
"pages/evaluate2/one",
"pages/evaluate2/product-list",
"pages/evaluate2/spec-detail",
"pages/settlement/index",
"pages/buyer/index",
"pages/profile/index",
@ -59,10 +55,6 @@
"pagePath": "pages/chat/index",
"text": "消息"
},
{
"pagePath": "pages/evaluate2/index",
"text": "估"
},
{
"pagePath": "pages/favorites/index",
"text": "收藏"

58
custom-tab-bar/index.js

@ -16,7 +16,6 @@ Component({
tabBarItems: [
{ key: 'index', route: 'pages/index/index' },
{ key: 'chat', route: 'pages/chat/index', badgeKey: 'chat' },
{ key: 'evaluate', route: 'pages/evaluate2/one' },
{ key: 'favorites', route: 'pages/favorites/index' },
{ key: 'profile', route: 'pages/profile/index' }
]
@ -113,7 +112,6 @@ Component({
const tabBarPages = [
'pages/index/index',
'pages/chat/index',
'pages/evaluate2/one',
'pages/favorites/index',
'pages/profile/index'
];
@ -197,62 +195,6 @@ Component({
});
},
// 跳转到估价页面
goToEvaluatePage() {
this.navigateLock(() => {
console.log('点击了估价按钮,跳转到evaluate2/one页面')
// 检查用户登录状态
const openid = wx.getStorageSync('openid');
const userId = wx.getStorageSync('userId');
if (!openid || !userId) {
console.log('用户未登录,显示登录提示');
wx.showToast({
title: '请先登录',
icon: 'none',
duration: 2000
});
return;
}
wx.switchTab({
url: '/pages/evaluate2/one',
success: (res) => {
console.log('switchTab到evaluate2/one成功:', res)
// 更新选中状态
this.setData({ selected: 'evaluate' })
// 更新全局数据
const app = getApp()
if (app && app.globalData) {
app.globalData.currentTab = 'evaluate'
}
},
fail: (err) => {
console.error('switchTab到evaluate2/one失败:', err)
// 失败时尝试使用reLaunch
console.log('尝试使用reLaunch跳转到evaluate2/one...')
wx.reLaunch({
url: '/pages/evaluate2/one',
success: (res) => {
console.log('reLaunch到evaluate2/one成功:', res)
// 更新选中状态
this.setData({ selected: 'evaluate' })
// 更新全局数据
const app = getApp()
if (app && app.globalData) {
app.globalData.currentTab = 'evaluate'
}
},
fail: (err) => {
console.error('reLaunch到evaluate2/one也失败:', err)
}
})
}
})
});
},
// 从全局数据同步状态的方法 - 增强版
syncFromGlobalData() {
try {

4
custom-tab-bar/index.wxml

@ -22,8 +22,8 @@
</view>
</view>
<!-- 鸡蛋估价按钮 -->
<view class="tab-bar-center" bindtap="goToEvaluatePage">
<!-- 鸡蛋估价按钮(UI占位,无点击功能) -->
<view class="tab-bar-center">
<view class="egg-button">
<view class="egg-icon" style="position: absolute; left: 1rpx; top: 30rpx">🥚</view>
<view class="egg-text" style="position: absolute; left: 60rpx; top: 83rpx">估</view>

628
pages/compare_price/index.js

@ -59,6 +59,64 @@ function formatPrice(price) {
return numPrice.toFixed(1);
}
// 计算单位价格
function calculateUnitPrice(price, spec) {
if (!price || !spec) {
return null;
}
// 转换价格为数字
const numPrice = parseFloat(price);
if (isNaN(numPrice)) {
return null;
}
// 检查是否需要计算单位价格(价格低于10元)
if (numPrice >= 10) {
return null;
}
// 提取重量范围
const weightMatch = spec.match(/(\d+)-(\d+)/);
if (!weightMatch) {
return null;
}
const minWeight = parseFloat(weightMatch[1]);
const maxWeight = parseFloat(weightMatch[2]);
if (isNaN(minWeight) || isNaN(maxWeight)) {
return null;
}
// 计算平均重量
const avgWeight = (minWeight + maxWeight) / 2;
// 检查是否是毛重
const isGrossWeight = spec.includes('毛重');
// 计算单位价格
let unitPrice;
if (isGrossWeight) {
unitPrice = (avgWeight - 5) * numPrice;
} else {
unitPrice = avgWeight * numPrice;
}
return unitPrice.toFixed(1);
}
// 获取商品状态信息
function getStatusInfo(status) {
switch (status) {
case 'published':
return { text: '在售', color: '#10B981' };
case 'sold_out':
return { text: '售罄', color: '#666666' };
default:
return { text: '未知', color: '#666666' };
}
}
Page({
data: {
// 页面数据
@ -72,7 +130,9 @@ Page({
currentGoods: null,
currentSwiperIndex: 0,
currentPage: 1,
hasMore: true
pageSize: 10, // 每页展示10条数据
hasMore: true,
allGoods: [] // 存储所有符合条件的商品
},
onLoad: function (options) {
@ -142,6 +202,9 @@ Page({
}
}
// 计算当前商品的单位价格
goodsData.unitPrice = calculateUnitPrice(goodsData.price, specWeight || goodsData.specification);
// 保存选择的种类、规格和当前商品数据到页面数据
this.setData({
selectedCategory: selectedCategory,
@ -429,308 +492,283 @@ Page({
loadingMore: page > 1 ? true : false
});
API.getProducts(page, 20, 'all', '')
.then(res => {
console.log('获取商品列表成功:', res);
console.log('选择的种类:', selectedCategory);
console.log('选择的规格:', specWeight);
let filteredGoods = [];
if (res && res.products) {
console.log('原始商品数量:', res.products.length);
// 获取当前商品的唯一标识符
const currentGoodsId = goodsData.productId || goodsData.id || goodsData._id;
console.log('当前商品ID:', currentGoodsId);
// 过滤商品
filteredGoods = res.products.filter(item => {
// 1. 排除当前商品
const itemId = item.productId || item.id || item._id;
if (currentGoodsId && itemId && currentGoodsId === itemId) {
console.log('排除当前商品:', itemId);
return false;
}
// 如果是第一页,获取所有符合条件的商品
if (page === 1) {
// 使用新的API接口获取相同规格的商品数据
API.getProductsBySpecification(specWeight)
.then(comparisonProducts => {
console.log('获取到的对比商品数据:', comparisonProducts);
console.log('选择的种类:', selectedCategory);
console.log('选择的规格:', specWeight);
let filteredGoods = [];
if (comparisonProducts && Array.isArray(comparisonProducts)) {
console.log('原始商品数量:', comparisonProducts.length);
// 获取当前商品的唯一标识符
const currentGoodsId = goodsData.productId || goodsData.id || goodsData._id;
console.log('当前商品ID:', currentGoodsId);
// 过滤商品
filteredGoods = comparisonProducts.filter(item => {
// 1. 排除当前商品
const itemId = item.productId || item.id || item._id;
if (currentGoodsId && itemId && currentGoodsId === itemId) {
console.log('排除当前商品:', itemId);
return false;
}
// 2. 检查商品状态和价格
if ((item.status !== 'published' && item.status !== 'sold_out') || item.price === null || item.price === undefined) {
return false;
}
// 3. 过滤种类
if (selectedCategory && selectedCategory !== '全部' && item.category !== selectedCategory) {
return false;
}
// 2. 检查商品状态和价格
if ((item.status !== 'published' && item.status !== 'sold_out') || item.price === null || item.price === undefined) {
return false;
return true;
});
console.log('过滤后的商品数量:', filteredGoods.length);
console.log('过滤后的商品:', filteredGoods);
}
// 处理商品数据
const processedGoods = filteredGoods.map(item => {
// 首先清理 imageUrls 字段(如果存在)
if (item.imageUrls && Array.isArray(item.imageUrls)) {
item.imageUrls = item.imageUrls.map(url => {
return url.trim().replace(/[`]/g, '');
});
// 使用processMediaUrls函数处理媒体数据
item.mediaItems = processMediaUrls(item.imageUrls);
// 确保图片优先显示:将图片类型的媒体项移到数组前面
if (item.mediaItems && item.mediaItems.length > 1) {
const imageItems = item.mediaItems.filter(media => media.type === 'image');
const videoItems = item.mediaItems.filter(media => media.type === 'video');
item.mediaItems = [...imageItems, ...videoItems];
}
}
// 3. 过滤种类
if (selectedCategory && selectedCategory !== '全部' && item.category !== selectedCategory) {
return false;
// 清理 mediaItems 中的 URL
if (item.mediaItems && Array.isArray(item.mediaItems)) {
item.mediaItems = item.mediaItems.map(media => {
if (media.url) {
// 去除 URL 中的反引号和空格
media.url = media.url.trim().replace(/[`]/g, '');
// 确保媒体类型正确
if (!media.type) {
media.type = isVideoUrl(media.url) ? 'video' : 'image';
}
}
return media;
});
}
// 4. 过滤规格
// 处理商品价格和库存,使用选中规格的价格和库存
if (specWeight) {
// 检查多个可能存储重量信息的字段
const fieldsToCheck = [
item.specification,
item.grossWeight,
item.weightQuantityData,
item.spec // 检查spec字段
];
let hasMatchingSpec = false;
for (const field of fieldsToCheck) {
if (!field) continue;
if (typeof field === 'string') {
// 处理字符串格式的规格数据
console.log('检查字符串规格:', field, '是否包含', specWeight);
// 处理逗号分隔的规格字符串
const specs = field.split(/[,,、]/).map(s => s.trim());
if (specs.some(spec => spec.includes(specWeight))) {
hasMatchingSpec = true;
break;
if (item.weightQuantityData && Array.isArray(item.weightQuantityData)) {
// 尝试从weightQuantityData中找到对应规格的价格和库存
const matchingSpec = item.weightQuantityData.find(spec => {
if (spec.weightSpec) {
return spec.weightSpec.trim() === specWeight;
}
} else if (Array.isArray(field)) {
// 处理数组格式的规格数据
console.log('检查数组规格:', field);
if (field.some(spec => {
if (typeof spec === 'string') {
console.log('检查数组元素(字符串):', spec, '是否包含', specWeight);
return spec.includes(specWeight);
} else if (typeof spec === 'object') {
// 检查对象格式的规格数据
const specStr = spec.weightSpec || spec.display || spec.spec || '';
console.log('检查数组元素(对象):', specStr, '是否包含', specWeight);
return specStr.includes(specWeight);
}
return false;
})) {
hasMatchingSpec = true;
break;
return false;
});
if (matchingSpec) {
// 确保价格是一个单一的值,而不是多个价格的组合
if (matchingSpec.price) {
item.price = matchingSpec.price;
}
} else if (typeof field === 'object') {
// 处理对象格式的规格数据
console.log('检查对象规格:', field);
const specStr = field.weightSpec || field.display || field.spec || '';
console.log('检查对象规格值:', specStr, '是否包含', specWeight);
if (specStr.includes(specWeight)) {
hasMatchingSpec = true;
break;
// 确保库存是对应规格的库存
if (matchingSpec.quantity) {
item.specStock = matchingSpec.quantity;
}
}
}
}
// 如果没有找到匹配的规格,尝试进行更宽松的匹配
if (!hasMatchingSpec) {
console.log('尝试更宽松的匹配...');
// 提取规格中的数字部分进行匹配
const weightNum = specWeight.replace(/[^0-9-]/g, '');
console.log('提取的重量数字:', weightNum);
for (const field of fieldsToCheck) {
if (!field) continue;
if (typeof field === 'string') {
console.log('检查字符串字段:', field, '是否包含', weightNum);
if (field.includes(weightNum)) {
hasMatchingSpec = true;
break;
}
} else if (Array.isArray(field)) {
console.log('检查数组字段:', field);
if (field.some(spec => {
const specStr = typeof spec === 'string' ? spec : (spec.weightSpec || spec.display || spec.spec || '');
console.log('检查数组元素:', specStr, '是否包含', weightNum);
return specStr.includes(weightNum);
})) {
hasMatchingSpec = true;
break;
}
} else if (typeof field === 'object') {
console.log('检查对象字段:', field);
const specStr = field.weightSpec || field.display || field.spec || '';
console.log('检查对象字段值:', specStr, '是否包含', weightNum);
if (specStr.includes(weightNum)) {
hasMatchingSpec = true;
break;
}
}
}
// 清理价格字段,确保只显示单一价格
if (item.price) {
// 如果价格是字符串且包含逗号,只取第一个价格
if (typeof item.price === 'string' && item.price.includes(',')) {
item.price = item.price.split(',')[0].trim();
}
if (!hasMatchingSpec) {
return false;
// 如果价格是数组,只取第一个价格
if (Array.isArray(item.price)) {
item.price = item.price[0];
}
}
return true;
});
console.log('过滤后的商品数量:', filteredGoods.length);
console.log('过滤后的商品:', filteredGoods);
}
// 处理商品数据
const processedGoods = filteredGoods.map(item => {
// 首先清理 imageUrls 字段(如果存在)
if (item.imageUrls && Array.isArray(item.imageUrls)) {
item.imageUrls = item.imageUrls.map(url => {
return url.trim().replace(/[`]/g, '');
});
// 使用processMediaUrls函数处理媒体数据
item.mediaItems = processMediaUrls(item.imageUrls);
// 确保图片优先显示:将图片类型的媒体项移到数组前面
if (item.mediaItems && item.mediaItems.length > 1) {
const imageItems = item.mediaItems.filter(media => media.type === 'image');
const videoItems = item.mediaItems.filter(media => media.type === 'video');
item.mediaItems = [...imageItems, ...videoItems];
// 处理规格信息,将多个净重信息分割成数组
item.processedSpecs = [];
if (item.specification) {
item.processedSpecs = processSpecifications(item.specification);
} else if (item.weightSpec) {
item.processedSpecs = processSpecifications(item.weightSpec);
} else if (item.grossWeight) {
item.processedSpecs = processSpecifications(item.grossWeight);
} else if (selectedSpec) {
item.processedSpecs = processSpecifications(selectedSpec);
}
}
// 清理 mediaItems 中的 URL
if (item.mediaItems && Array.isArray(item.mediaItems)) {
item.mediaItems = item.mediaItems.map(media => {
if (media.url) {
// 去除 URL 中的反引号和空格
media.url = media.url.trim().replace(/[`]/g, '');
// 确保媒体类型正确
if (!media.type) {
media.type = isVideoUrl(media.url) ? 'video' : 'image';
}
}
return media;
});
}
// 处理库存显示逻辑
// 优先使用对应规格的库存,如果没有则使用默认库存
let quantity = item.specStock || item.quantity || item.minOrder || item.stock || item.inventory || item.availableStock || item.totalAvailable;
// 处理商品价格,使用选中规格的价格
if (specWeight) {
if (item.weightQuantityData && Array.isArray(item.weightQuantityData)) {
// 尝试从weightQuantityData中找到对应规格的价格
const matchingSpec = item.weightQuantityData.find(spec => {
if (spec.weightSpec) {
return spec.weightSpec.trim() === specWeight;
}
return false;
});
if (matchingSpec && matchingSpec.price) {
// 确保价格是一个单一的值,而不是多个价格的组合
item.price = matchingSpec.price;
// 清理库存字段,确保只显示单一值
if (quantity) {
// 如果库存是字符串且包含逗号,只取第一个库存
if (typeof quantity === 'string' && quantity.includes(',')) {
quantity = quantity.split(',')[0].trim();
}
// 如果库存是数组,只取第一个库存
if (Array.isArray(quantity)) {
quantity = quantity[0];
}
// 转换为数字
quantity = Number(quantity);
}
}
// 清理价格字段,确保只显示单一价格
if (item.price) {
// 如果价格是字符串且包含逗号,只取第一个价格
if (typeof item.price === 'string' && item.price.includes(',')) {
item.price = item.price.split(',')[0].trim();
}
// 如果价格是数组,只取第一个价格
if (Array.isArray(item.price)) {
item.price = item.price[0];
const totalStock = quantity;
let displayStock;
if (totalStock >= 10000) {
// 库存>=10000时显示"库存充足"
displayStock = '充足';
} else if (totalStock === 0) {
// 库存=0时显示"暂无"
displayStock = '暂无';
} else {
// 其他情况显示具体数字
displayStock = totalStock;
}
}
// 处理规格信息,将多个净重信息分割成数组
item.processedSpecs = [];
if (item.specification) {
item.processedSpecs = processSpecifications(item.specification);
} else if (item.weightSpec) {
item.processedSpecs = processSpecifications(item.weightSpec);
} else if (item.grossWeight) {
item.processedSpecs = processSpecifications(item.grossWeight);
} else if (selectedSpec) {
item.processedSpecs = processSpecifications(selectedSpec);
}
// 更新商品的库存显示
item.totalStock = displayStock;
item.originalTotalStock = totalStock;
// 处理库存显示逻辑
const quantity = item.quantity || item.minOrder || item.stock || item.inventory || item.availableStock || item.totalAvailable;
const totalStock = quantity;
let displayStock;
if (totalStock >= 10000) {
// 库存>=10000时显示"库存充足"
displayStock = '充足';
} else if (totalStock === 0) {
// 库存=0时显示"暂无"
displayStock = '暂无';
} else {
// 其他情况显示具体数字
displayStock = totalStock;
}
// 添加当前对比的规格信息
if (specWeight) {
item.currentSpec = specWeight;
}
// 更新商品的库存显示
item.totalStock = displayStock;
item.originalTotalStock = totalStock;
// 处理地区信息,只显示省份
if (item.region) {
// 提取省份信息
const provinceRegex = /^([^省]+省|[^自治区]+自治区|[^直辖市]+直辖市|[^特别行政区]+特别行政区)/;
const match = item.region.match(provinceRegex);
if (match) {
item.region = match[1];
}
}
// 添加当前对比的规格信息
if (specWeight) {
item.currentSpec = specWeight;
}
// 计算单位价格
item.unitPrice = calculateUnitPrice(item.price, item.currentSpec || item.specification || (item.processedSpecs && item.processedSpecs.length > 0 ? item.processedSpecs.join(' | ') : ''));
// 处理地区信息,只显示省份
if (item.region) {
// 提取省份信息
const provinceRegex = /^([^省]+省|[^自治区]+自治区|[^直辖市]+直辖市|[^特别行政区]+特别行政区)/;
const match = item.region.match(provinceRegex);
if (match) {
item.region = match[1];
}
}
// 计算价格涨幅
if (goodsData.price) {
// 获取当前商品的价格(使用单位价格如果低于10元)
let currentPrice = parseFloat(goodsData.price);
if (goodsData.unitPrice) {
currentPrice = parseFloat(goodsData.unitPrice);
}
// 计算价格涨幅
if (goodsData.price) {
const currentPrice = parseFloat(goodsData.price);
const itemPrice = parseFloat(item.price);
if (!isNaN(currentPrice) && !isNaN(itemPrice)) {
const priceDiff = itemPrice - currentPrice;
const pricePercent = ((priceDiff / currentPrice) * 100).toFixed(1);
item.priceDiff = priceDiff;
item.pricePercent = pricePercent;
}
}
// 获取对比商品的价格(根据规则使用合适的价格)
let itemPrice = parseFloat(item.price);
if (currentPrice >= 10 && item.unitPrice) {
// 如果当前商品价格高于10元,对比商品使用单位价格
itemPrice = parseFloat(item.unitPrice);
} else if (currentPrice < 10 && itemPrice < 10) {
// 如果两者都低于10元,使用原始价格
itemPrice = parseFloat(item.price);
} else if (currentPrice < 10 && itemPrice >= 10) {
// 如果当前商品低于10元,对比商品高于10元,当前商品使用单位价格
currentPrice = parseFloat(goodsData.unitPrice || goodsData.price);
}
return item;
});
if (!isNaN(currentPrice) && !isNaN(itemPrice)) {
const priceDiff = itemPrice - currentPrice;
const pricePercent = ((priceDiff / currentPrice) * 100).toFixed(1);
item.priceDiff = parseFloat(priceDiff.toFixed(1));
item.pricePercent = pricePercent;
}
}
// 合并商品数据
const newGoods = page === 1 ? processedGoods : [...this.data.goods, ...processedGoods];
return item;
});
// 检查是否还有更多数据
const hasMore = res && res.products && res.products.length >= 20;
// 存储所有符合条件的商品
this.setData({
allGoods: processedGoods
});
// 设置商品数据
this.setData({
goods: newGoods,
loading: false,
loadingMore: false,
currentPage: page,
hasMore: hasMore,
selectedOption: selectedCategory || '对比价格',
showTips: false
});
// 计算当前页应该显示的商品
const { pageSize } = this.data;
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
const currentPageGoods = processedGoods.slice(startIndex, endIndex);
// 检查是否还有更多数据
const hasMore = endIndex < processedGoods.length;
// 设置商品数据
this.setData({
goods: currentPageGoods,
loading: false,
loadingMore: false,
currentPage: page,
hasMore: hasMore,
selectedOption: selectedCategory || '对比价格',
showTips: false
});
console.log('对比价格数据加载完成:', newGoods);
console.log('对比价格数据加载完成:', currentPageGoods);
// 如果符合条件的数据少于5条,自动加载更多数据
if (newGoods.length < 5 && hasMore) {
console.log('符合条件的数据少于5条,自动加载更多数据');
this.loadGoodsData(page + 1, selectedCategory, specWeight, goodsData);
} else if (page === 1) {
// 显示提示信息
wx.showToast({
title: `找到${newGoods.length}个符合条件的商品`,
title: `找到${processedGoods.length}个符合条件的商品`,
icon: 'success',
duration: 2000
});
}
})
.catch(err => {
console.error('获取商品列表失败:', err);
this.setData({
loading: false,
loadingMore: false
});
wx.showToast({
title: '获取商品失败,请稍后重试',
icon: 'none'
})
.catch(err => {
console.error('获取商品列表失败:', err);
this.setData({
loading: false,
loadingMore: false
});
wx.showToast({
title: '获取商品失败,请稍后重试',
icon: 'none'
});
});
} else {
// 如果不是第一页,从allGoods中获取数据
const { allGoods, pageSize } = this.data;
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
const currentPageGoods = allGoods.slice(startIndex, endIndex);
// 检查是否还有更多数据
const hasMore = endIndex < allGoods.length;
// 合并商品数据
const newGoods = [...this.data.goods, ...currentPageGoods];
// 设置商品数据
this.setData({
goods: newGoods,
loading: false,
loadingMore: false,
currentPage: page,
hasMore: hasMore
});
console.log('加载更多数据完成:', currentPageGoods);
}
},
// 加载更多数据
@ -750,5 +788,73 @@ Page({
wx.navigateBack({
delta: 1
});
},
// 选择规格
selectSpec: function (e) {
const selectedSpec = e.currentTarget.dataset.spec;
if (!selectedSpec) {
return;
}
const specWeight = selectedSpec.weightSpec.trim();
const currentGoods = this.data.currentGoods;
// 更新选中的规格
this.setData({
selectedSpec: specWeight,
loading: true
});
// 处理当前商品的价格,使用选中规格的价格
let currentPrice = currentGoods.price;
if (selectedSpec && selectedSpec.price) {
// 如果selectedSpec包含价格信息,使用它
currentPrice = selectedSpec.price;
} else if (currentGoods.weightQuantityData && Array.isArray(currentGoods.weightQuantityData)) {
// 如果weightQuantityData存在,尝试从中找到对应规格的价格
const matchingSpec = currentGoods.weightQuantityData.find(spec => {
if (spec.weightSpec) {
return spec.weightSpec.trim() === specWeight;
}
return false;
});
if (matchingSpec && matchingSpec.price) {
currentPrice = matchingSpec.price;
}
}
// 更新currentGoods的价格
currentGoods.price = currentPrice;
// 清理价格字段,确保只显示单一价格
if (currentGoods.price) {
// 如果价格是字符串且包含逗号,只取第一个价格
if (typeof currentGoods.price === 'string' && currentGoods.price.includes(',')) {
currentGoods.price = currentGoods.price.split(',')[0].trim();
}
// 如果价格是数组,只取第一个价格
if (Array.isArray(currentGoods.price)) {
currentGoods.price = currentGoods.price[0];
}
}
// 计算当前商品的单位价格
currentGoods.unitPrice = calculateUnitPrice(currentGoods.price, specWeight || currentGoods.specification);
// 更新currentGoods
this.setData({
currentGoods: currentGoods
});
// 初始化商品数据
this.setData({
goods: [],
currentPage: 1,
hasMore: true
});
// 加载商品数据
this.loadGoodsData(1, this.data.selectedCategory, specWeight, currentGoods);
}
});

51
pages/compare_price/index.wxml

@ -2,6 +2,25 @@
<view class="page-container">
<scroll-view class="scroll-view" scroll-y="true" enable-back-to-top="true">
<!-- 规格选择器 -->
<view wx:if="{{currentGoods && currentGoods.weightQuantityData && currentGoods.weightQuantityData.length > 1}}" class="spec-selector">
<view class="spec-selector-header">
<text class="spec-selector-title">选择规格</text>
</view>
<view class="spec-selector-list">
<view
wx:for="{{currentGoods.weightQuantityData}}"
wx:key="index"
class="spec-item {{selectedSpec === (item.weightSpec ? item.weightSpec.trim() : '') ? 'active' : ''}}"
bindtap="selectSpec"
data-spec="{{item}}"
>
<text class="spec-item-text">{{item.display || item.weightSpec}}</text>
<view wx:if="{{selectedSpec === (item.weightSpec ? item.weightSpec.trim() : '')}}" class="spec-item-check">✓</view>
</view>
</view>
</view>
<!-- 步骤完成提示区 -->
<view class="tips-section">
<view class="tips-container">
@ -27,14 +46,17 @@
</view>
<view class="current-goods-card">
<view class="goods-header">
<view class="brand-tag">品牌</view>
<view class="brand-tag">{{currentGoods.category || '品种'}}</view>
<text class="goods-name">{{currentGoods.productName || currentGoods.name || '商品'}}</text>
<view class="status-badge" style="color: {{currentGoods.status === 'published' ? '#10B981' : currentGoods.status === 'sold_out' ? '#FF4D4F' : '#666666'}}">{{currentGoods.status === 'published' ? '在售' : currentGoods.status === 'sold_out' ? '售罄' : '未知'}}</view>
<view class="price-container">
<text class="currency-symbol" style="color: {{currentGoods.priceDiff > 0 ? '#FF4D4F' : currentGoods.priceDiff < 0 ? '#10B981' : '#666666'}}">¥</text>
<text class="price-amount" style="color: {{currentGoods.priceDiff > 0 ? '#FF4D4F' : currentGoods.priceDiff < 0 ? '#10B981' : '#666666'}}">{{currentGoods.price}}</text>
<text class="price-amount" style="color: {{currentGoods.priceDiff > 0 ? '#FF4D4F' : currentGoods.priceDiff < 0 ? '#10B981' : '#666666'}}">{{currentGoods.price}}元{{currentGoods.price > 10 ? '' : '/'}}</text>
<text wx:if="{{currentGoods.unitPrice}}" class="unit-price">
{{currentGoods.unitPrice}}元(件价)
</text>
</view>
</view>
<text class="spec-info">{{currentGoods.specification || selectedSpec || '净重43-44g'}} | {{currentGoods.yolk || '绿壳'}} | 库存:{{currentGoods.totalStock || '450'}}</text>
<text class="spec-info">{{currentGoods.specification || selectedSpec || '净重43-44g'}} | {{currentGoods.category || '绿壳'}} | {{currentGoods.yolk || '蛋黄颜色'}} | 库存:{{currentGoods.totalStock || '450'}}</text>
<view class="merchant-info">
<view class="merchant-left">
<text class="merchant-icon">🏪</text>
@ -53,10 +75,6 @@
<view class="section-title">
<text class="title-icon">⚖</text>
<text class="title-text">同类商品价格对比</text>
<view class="filter-btn">
<text class="filter-text">筛选</text>
<text class="filter-icon">☰</text>
</view>
</view>
<view class="compare-list">
<view
@ -67,16 +85,17 @@
bindtap="navigateToGoodsDetail"
>
<view class="compare-item-header">
<view class="compare-item-name-container">
<text class="compare-item-name">{{item.productName || item.name}}</text>
<text wx:if="{{item.status === 'sold_out'}}" class="sold-out-tag">已售空</text>
</view>
<view class="brand-tag">{{item.category || '品种'}}</view>
<text class="compare-item-name">{{item.productName || item.name}}</text>
<view class="status-badge" style="color: {{item.status === 'published' ? '#10B981' : item.status === 'sold_out' ? '#FF4D4F' : '#666666'}}">{{item.status === 'published' ? '在售' : item.status === 'sold_out' ? '售罄' : '未知'}}</view>
<view class="compare-item-price">
<text class="currency-symbol" style="color: {{item.priceDiff > 0 ? '#FF4D4F' : item.priceDiff < 0 ? '#10B981' : '#666666'}}">¥</text>
<text class="compare-price-amount" style="color: {{item.priceDiff > 0 ? '#FF4D4F' : item.priceDiff < 0 ? '#10B981' : '#666666'}}">{{item.price}}</text>
<text class="compare-price-amount" style="color: {{item.priceDiff > 0 ? '#FF4D4F' : item.priceDiff < 0 ? '#10B981' : '#666666'}}">{{item.price}}元{{item.price > 10 ? '' : '/'}}</text>
<text wx:if="{{item.unitPrice}}" class="unit-price">
{{item.unitPrice}}元(件价)
</text>
</view>
</view>
<text class="compare-item-spec">{{item.currentSpec || item.specification || (item.processedSpecs && item.processedSpecs.length > 0 ? item.processedSpecs.join(' | ') : '净重:45-50g')}} | {{item.category || '绿壳'}} | {{item.yolk || '无'}} | 库存:{{item.totalStock || '450'}}</text>
<text class="compare-item-spec">{{item.currentSpec || item.specification || (item.processedSpecs && item.processedSpecs.length > 0 ? item.processedSpecs.join(' | ') : '净重:45-50g')}} | {{item.category || '品种'}} | {{item.yolk || '无'}} | 库存:{{item.totalStock || '450'}}</text>
<view class="compare-item-footer">
<view class="merchant-region">
<text class="compare-item-merchant">🏪 {{item.sourceType || '生态农场'}}</text>
@ -85,6 +104,8 @@
<view class="price-comparison" wx:if="{{item.pricePercent}}">
<text class="price-trend-icon" style="color: {{item.priceDiff > 0 ? '#EF4444' : item.priceDiff < 0 ? '#10B981' : '#666666'}}">{{item.priceDiff > 0 ? '↑' : item.priceDiff < 0 ? '↓' : '→'}}</text>
<text class="price-trend-text" style="color: {{item.priceDiff > 0 ? '#FF4D4F' : item.priceDiff < 0 ? '#10B981' : '#666666'}}">{{item.priceDiff > 0 ? '+' : ''}}{{item.pricePercent}}%</text>
<text wx:if="{{item.priceDiff < 0}}" class="price-save" style="color: #10B981; margin-left: 8px;">省¥{{-item.priceDiff}}</text>
<text wx:if="{{item.priceDiff > 0}}" class="price-save" style="color: #FF4D4F; margin-left: 8px;">涨¥{{item.priceDiff}}</text>
</view>
</view>
</view>

183
pages/compare_price/index.wxss

@ -100,6 +100,90 @@
line-height: 1.4;
}
/* 规格选择器 */
.spec-selector {
padding: 0 16px 12px;
}
.spec-selector-header {
margin-bottom: 8px;
}
.spec-selector-title {
font-size: 14px;
color: #1A1A1A;
font-weight: 500;
}
.spec-selector-list {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.spec-item {
padding: 6px 12px;
border: 1px solid #E5E7EB;
border-radius: 8px;
background-color: #FFFFFF;
font-size: 14px;
color: #666666;
cursor: pointer;
transition: all 0.3s ease;
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.spec-item:active {
transform: scale(0.98);
}
.spec-item.active {
border-color: #165DFF;
background-color: #EFF6FF;
color: #165DFF;
box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.2);
}
.spec-item-text {
white-space: nowrap;
flex: 1;
font-weight: 500;
}
.spec-item-check {
width: 18px;
height: 18px;
border-radius: 50%;
background-color: #165DFF;
color: #FFFFFF;
font-size: 14px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
font-weight: bold;
box-shadow: 0 1px 3px rgba(22, 93, 255, 0.3);
animation: pulse 0.3s ease-in-out;
}
@keyframes pulse {
0% {
transform: scale(0.8);
opacity: 0.5;
}
50% {
transform: scale(1.1);
opacity: 1;
}
100% {
transform: scale(1);
opacity: 1;
}
}
/* 内容容器 */
.content-container {
padding: 0 16px;
@ -243,6 +327,15 @@
flex-shrink: 0;
}
.status-badge {
background-color: #F3F4F6;
border-radius: 9999px;
padding: 2px 8px;
font-size: 12px;
flex-shrink: 0;
font-weight: 500;
}
.goods-name {
font-size: 16px;
color: #1A1A1A;
@ -252,19 +345,37 @@
}
.price-container {
display: flex;
align-items: baseline;
gap: 4px;
display: block;
flex-shrink: 0;
position: relative;
}
.currency-symbol {
font-size: 14px;
.price-amount {
display: inline-flex;
align-items: center;
justify-content: center;
margin-bottom: -5px;
font-size: 26px;
font-weight: 700;
color: #ff4d4f;
letter-spacing: -0.5px;
}
.price-amount {
.unit-price {
display: block;
margin-left: 10px;
margin-top: -5px;
}
.currency-symbol {
font-size: 24px;
font-weight: bold;
margin-right: 2px;
}
.unit-price {
font-size: 16px;
color: #666666;
white-space: nowrap;
}
.spec-info {
@ -332,52 +443,47 @@
.compare-item-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.compare-item-name-container {
flex: 1;
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.compare-item-name {
font-size: 15px;
font-size: 16px;
color: #1A1A1A;
font-weight: 500;
flex: 1;
min-width: 0;
white-space: normal;
word-break: break-word;
line-height: 1.4;
}
.sold-out-tag {
background-color: #FEE2E2;
color: #EF4444;
font-size: 12px;
padding: 2px 8px;
border-radius: 9999px;
flex-shrink: 0;
}
.compare-item-price {
display: flex;
align-items: baseline;
gap: 4px;
display: block;
flex-shrink: 0;
position: relative;
}
.compare-price-amount {
font-size: 18px;
font-weight: bold;
display: inline-flex;
align-items: center;
justify-content: center;
margin-bottom: -5px;
font-size: 26px;
font-weight: 700;
color: #ff4d4f;
letter-spacing: -0.5px;
}
.compare-item-price .unit-price {
display: block;
margin-left: 10px;
margin-top: -5px;
}
.compare-item-spec {
font-size: 12px;
color: #999999;
font-size: 14px;
color: #666666;
white-space: normal;
word-break: break-word;
margin-top: 4px;
@ -397,13 +503,13 @@
}
.compare-item-merchant {
font-size: 12px;
color: #999999;
font-size: 14px;
color: #666666;
}
.compare-item-region {
font-size: 12px;
color: #999999;
font-size: 14px;
color: #666666;
}
.price-comparison {
@ -427,6 +533,11 @@
color: #FF4D4F;
}
.price-save {
font-size: 12px;
font-weight: 500;
}
/* 价格趋势图 */
.trend-section {
margin-bottom: 20px;

552
pages/evaluate2/index.js

@ -1,552 +0,0 @@
Page({
data: {
productName: '',
category: '',
specifications: [],
selectedSpec: '',
loading: false,
error: '',
navigating: false
},
// 导航锁机制,防止多次点击导致多次跳转
navigateLock: function(cb) {
if (this.data.navigating) {
return false;
}
this.setData({ navigating: true });
cb();
// 延迟重置导航锁,确保导航操作有足够时间完成
setTimeout(() => {
this.setData({ navigating: false });
}, 1000);
return true;
},
onLoad(options) {
let productName = '';
let category = '';
// 首先检查URL参数
if (options.productName) {
productName = options.productName;
} else {
// 然后检查本地存储(用于wx.switchTab导航)
productName = wx.getStorageSync('selectedProductName') || '';
// 清除本地存储中的商品名称,避免影响下次进入
if (productName) {
wx.removeStorageSync('selectedProductName');
}
}
// 获取分类信息
category = wx.getStorageSync('selectedCategory') || '';
if (productName) {
this.setData({
productName: productName,
category: category
});
this.loadSpecifications(productName);
} else {
// 如果没有商品名称参数,跳转到商品列表页面
wx.redirectTo({
url: '/pages/evaluate2/product-list'
});
}
},
loadSpecifications(productName) {
this.setData({
loading: true,
specifications: [],
error: '' // 清空错误信息,确保加载时只显示加载状态
});
// 尝试从本地存储获取商品规格映射数据
const productSpecsMap = wx.getStorageSync('evaluate2ProductSpecsMap') || {};
if (productSpecsMap && productSpecsMap[productName]) {
console.log('从本地存储获取商品规格数据');
// 提取该商品的规格和价格信息
const productSpecs = productSpecsMap[productName];
// 处理规格数据
const specPriceMap = {};
productSpecs.forEach(item => {
const specStr = item.specification;
const price = item.price;
// 价格为空的不参与计算
if (!price || price.trim() === '') {
return;
}
if (specStr.length > 0) {
// 处理逗号分隔的多个规格
let specs = specStr.split(',').map(spec => spec.trim()).filter(spec => spec.length > 0);
// 进一步处理规格,确保每个规格都是独立的
const processedSpecs = [];
specs.forEach(spec => {
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()).filter(p => p && p.trim() !== '');
// 价格为空的不参与计算
if (prices.length === 0) {
return;
}
// 将规格和价格配对
specs.forEach((spec, index) => {
if (spec.length > 0) {
// 确保价格索引不超出范围
const priceIndex = index % prices.length;
const matchedPrice = prices[priceIndex] || '';
// 只有当价格不为空时才添加该规格
if (matchedPrice && matchedPrice.trim() !== '') {
// 收集相同规格的所有价格,以便计算平均值
if (!specPriceMap[spec]) {
specPriceMap[spec] = [];
}
specPriceMap[spec].push(matchedPrice);
}
}
});
}
});
// 转换为规格对象数组
const specifications = Object.keys(specPriceMap).map(spec => {
const prices = specPriceMap[spec];
// 解析规格
const specInfo = this.parseSpecification(spec);
// 处理每个价格
const processedPrices = prices.map(price => {
if (!price || price.trim() === '' || isNaN(parseFloat(price))) {
return 0;
}
const priceValue = parseFloat(price);
// 价格<10的需要按照公式计算
if (priceValue < 10 && specInfo) {
if (specInfo.type === '净重') {
// 净重:规格平均值 × 价格
return specInfo.avg * priceValue;
} else if (specInfo.type === '毛重') {
// 毛重:(规格平均值 - 5) × 价格
return (specInfo.avg - 5) * priceValue;
}
}
// 价格>=10的直接使用
return priceValue;
}).filter(price => price > 0); // 过滤掉0值
// 计算处理后价格的平均值
let finalPrice = 0;
let finalPriceText = '';
if (processedPrices.length > 0) {
const sum = processedPrices.reduce((acc, price) => acc + price, 0);
finalPrice = sum / processedPrices.length;
finalPriceText = finalPrice.toFixed(2);
}
const specObj = {
name: spec,
price: finalPriceText,
priceText: finalPriceText,
finalPrice: finalPrice,
finalPriceText: finalPriceText
};
return specObj;
});
// 对规格进行排序
specifications.sort((a, b) => {
// 解析两个规格
const specA = this.parseSpecification(a.name);
const specB = this.parseSpecification(b.name);
// 如果有一个规格解析失败,保持原顺序
if (!specA || !specB) {
return 0;
}
// 1. 按类型排序:净重在前,毛重在后
if (specA.type !== specB.type) {
return specA.type === '净重' ? -1 : 1;
}
// 2. 按规格最小值排序:从小到大
return specA.min - specB.min;
});
this.setData({
specifications: specifications,
error: '', // 清除之前的错误
loading: false
});
// 结束下拉刷新
wx.stopPullDownRefresh();
} else {
// 如果本地存储中没有数据,尝试从本地存储获取原始商品数据
const allProducts = wx.getStorageSync('allProducts') || [];
if (allProducts.length > 0) {
console.log('从本地存储获取原始商品数据');
this.processSpecifications(productName, allProducts);
} else {
// 如果本地没有数据,再请求服务器
console.log('本地存储中没有数据,请求服务器获取商品数据');
const api = require('../../utils/api');
api.getProducts(1, 1000, 'all', '').then(result => {
// 从返回对象中提取products数组
const products = result.products || [];
this.processSpecifications(productName, products);
}).catch(err => {
console.error('获取规格失败:', err);
this.setData({
error: '获取规格失败,请稍后重试',
loading: false
});
// 结束下拉刷新
wx.stopPullDownRefresh();
});
}
}
},
// 解析规格,提取类型(净重/毛重)和数值范围
parseSpecification(spec) {
// 匹配 "净重X-Y" 或 "毛重X-Y" 格式
const rangeMatch = spec.match(/(净重|毛重)(\d+)-(\d+)/);
if (rangeMatch) {
const type = rangeMatch[1]; // 净重或毛重
const min = parseFloat(rangeMatch[2]);
const max = parseFloat(rangeMatch[3]);
const avg = (min + max) / 2;
return {
type: type,
min: min,
max: max,
avg: avg
};
}
// 匹配 "净重X+" 或 "毛重X+" 格式
const plusMatch = spec.match(/(净重|毛重)(\d+)\+/);
if (plusMatch) {
const type = plusMatch[1]; // 净重或毛重
const value = parseFloat(plusMatch[2]);
return {
type: type,
min: value,
max: value,
avg: value
};
}
// 匹配 "净重X" 或 "毛重X" 格式
const singleMatch = spec.match(/(净重|毛重)(\d+)/);
if (singleMatch) {
const type = singleMatch[1]; // 净重或毛重
const value = parseFloat(singleMatch[2]);
return {
type: type,
min: value,
max: value,
avg: value
};
}
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 (!price || price.trim() === '') {
console.log(`商品价格为空,跳过处理`);
return;
}
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()).filter(p => p && p.trim() !== '');
console.log(`规格数组:`, specs);
console.log(`价格数组:`, prices);
// 价格为空的不参与计算
if (prices.length === 0) {
console.log(`价格数组为空,跳过处理`);
return;
}
// 将规格和价格配对
specs.forEach((spec, index) => {
if (spec.length > 0) {
// 确保价格索引不超出范围
const priceIndex = index % prices.length;
const matchedPrice = prices[priceIndex] || '';
console.log(`规格'${spec}' 配对价格: '${matchedPrice}'`);
// 只有当价格不为空时才添加该规格
if (matchedPrice && matchedPrice.trim() !== '') {
// 收集相同规格的所有价格,以便计算平均值
if (!specPriceMap[spec]) {
specPriceMap[spec] = [];
}
specPriceMap[spec].push(matchedPrice);
} else {
console.log(`规格'${spec}' 价格为空,不添加`);
}
}
});
}
});
// 转换为规格对象数组
const specifications = Object.keys(specPriceMap).map(spec => {
const prices = specPriceMap[spec];
console.log(`规格'${spec}' 的所有原始价格:`, prices);
// 解析规格
const specInfo = this.parseSpecification(spec);
// 处理每个价格
const processedPrices = prices.map(price => {
if (!price || price.trim() === '' || isNaN(parseFloat(price))) {
return 0;
}
const priceValue = parseFloat(price);
console.log(`处理价格: ${priceValue}`);
// 价格<10的需要按照公式计算
if (priceValue < 10 && specInfo) {
console.log(`价格 ${priceValue} < 10,按照公式计算`);
if (specInfo.type === '净重') {
// 净重:规格平均值 × 价格
return specInfo.avg * priceValue;
} else if (specInfo.type === '毛重') {
// 毛重:(规格平均值 - 5) × 价格
return (specInfo.avg - 5) * priceValue;
}
}
// 价格>=10的直接使用
return priceValue;
}).filter(price => price > 0); // 过滤掉0值
console.log(`规格'${spec}' 处理后的价格:`, processedPrices);
// 计算处理后价格的平均值
let finalPrice = 0;
let finalPriceText = '';
if (processedPrices.length > 0) {
const sum = processedPrices.reduce((acc, price) => acc + price, 0);
finalPrice = sum / processedPrices.length;
finalPriceText = finalPrice.toFixed(2);
console.log(`规格'${spec}' 处理后价格的平均值: ${finalPriceText} (基于 ${processedPrices.length} 个价格)`);
} else {
console.log(`规格'${spec}' 没有有效价格`);
}
const specObj = {
name: spec,
price: finalPriceText,
priceText: finalPriceText,
finalPrice: finalPrice,
finalPriceText: finalPriceText
};
console.log('创建的规格对象:', specObj);
return specObj;
});
console.log('提取的规格和价格:', specifications);
// 对规格进行排序
specifications.sort((a, b) => {
// 解析两个规格
const specA = this.parseSpecification(a.name);
const specB = this.parseSpecification(b.name);
// 如果有一个规格解析失败,保持原顺序
if (!specA || !specB) {
return 0;
}
// 1. 按类型排序:净重在前,毛重在后
if (specA.type !== specB.type) {
return specA.type === '净重' ? -1 : 1;
}
// 2. 按规格最小值排序:从小到大
return specA.min - specB.min;
});
console.log('排序后的规格:', specifications);
this.setData({
specifications: specifications,
error: '', // 清除之前的错误
loading: false
});
// 结束下拉刷新
wx.stopPullDownRefresh();
},
// 选择规格
selectSpec(e) {
this.navigateLock(() => {
const specItem = e.currentTarget.dataset.spec;
this.setData({
selectedSpec: specItem.name
});
console.log('选择的规格项:', specItem);
console.log('传递的价格:', specItem.finalPriceText);
console.log('传递的分类:', this.data.category);
wx.navigateTo({
url: `/pages/evaluate2/spec-detail?productName=${encodeURIComponent(this.data.productName)}&specification=${encodeURIComponent(specItem.name)}&price=${encodeURIComponent(specItem.finalPriceText)}&category=${encodeURIComponent(this.data.category)}`
});
});
},
// 跳转到规格详情页面
goToSpecDetail(e) {
this.selectSpec(e);
},
// 返回上一页
goBack() {
this.navigateLock(() => {
wx.navigateBack();
});
},
// 返回商品列表页面
goBackToProductList() {
this.navigateLock(() => {
// 从本地存储中获取之前选择的分类
const selectedCategory = wx.getStorageSync('selectedCategory') || '';
console.log('返回商品列表页面,之前选择的分类:', selectedCategory);
// 构建跳转URL,如果有分类参数就传递
let url = '/pages/evaluate2/product-list';
if (selectedCategory) {
url += '?category=' + encodeURIComponent(selectedCategory);
}
wx.redirectTo({
url: url
});
});
},
// 下拉刷新
onPullDownRefresh() {
console.log('开始下拉刷新');
if (this.data.productName) {
this.loadSpecifications(this.data.productName);
} else {
wx.stopPullDownRefresh();
}
},
// 分享配置
onShareAppMessage() {
return {
title: '专业的估价平台,专为估蛋而生',
imageUrl: 'https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BD%97%E6%9B%BC%E7%81%B0/image/c00cbcbfd12d747b44621701aed2ae02.jpeg',
path: '/pages/evaluate2/index'
};
},
// 朋友圈分享配置
onShareTimeline() {
return {
title: '专业的估价平台,专为估蛋而生',
imageUrl: 'https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BD%97%E6%9B%BC%E7%81%B0/image/c00cbcbfd12d747b44621701aed2ae02.jpeg',
query: ''
};
}
});

5
pages/evaluate2/index.json

@ -1,5 +0,0 @@
{
"usingComponents": {},
"enablePullDownRefresh": true,
"backgroundTextStyle": "dark"
}

108
pages/evaluate2/index.wxml

@ -1,108 +0,0 @@
<view class="container">
<!-- 步骤指示器 -->
<view class="step-indicator">
<view class="step-item active">
<view class="step-number">1</view>
<text class="step-text">选择品种</text>
</view>
<view class="step-line active"></view>
<view class="step-item active">
<view class="step-number">2</view>
<text class="step-text">选择产品</text>
</view>
<view class="step-line active"></view>
<view class="step-item active">
<view class="step-number">3</view>
<text class="step-text">选择规格</text>
</view>
<view class="step-line"></view>
<view class="step-item">
<view class="step-number">4</view>
<text class="step-text">查看估价</text>
</view>
</view>
<!-- 头部导航栏 -->
<view class="header">
<view class="header-content">
<button class="back-button" bindtap="goBackToProductList">
<text class="back-icon" style="position: relative; left: -139rpx; top: 2rpx; width: 62rpx; display: block; box-sizing: border-box">←</text>
</button>
<text class="title">规格选择</text>
<view class="header-right"></view> <!-- 占位,保持标题居中 -->
</view>
</view>
<view class="content">
<!-- 加载中状态 -->
<view wx:if="{{loading}}" class="loading">
<view class="loading-spinner"></view>
<text class="loading-text">正在加载规格数据...</text>
</view>
<!-- 错误提示 -->
<view wx:if="{{error}}" class="error-card">
<view class="error-icon">⚠️</view>
<text class="error-text">{{error}}</text>
<view class="button-group">
<button bindtap="loadSpecifications" data-product="{{productName}}" class="btn-primary">重新加载</button>
<button bindtap="goBackToProductList" class="btn-secondary">返回商品列表</button>
</view>
</view>
<!-- 商品信息 -->
<view wx:else class="product-card">
<view class="product-info-container">
<view class="product-info-row">
<view class="product-image-container">
<image
src="../../images/OIP-C.png"
mode="aspectFill"
class="product-image"
/>
</view>
<view class="product-details">
<text class="product-name">{{productName}}</text>
<text class="product-hint">请选择重量规格</text>
</view>
</view>
</view>
</view>
<!-- 规格列表 -->
<view wx:if="{{!loading && !error && specifications.length > 0}}" class="spec-section">
<view class="section-header">
<text class="section-title">可用规格</text>
<text class="section-count">({{specifications.length}})</text>
</view>
<view class="spec-list">
<view
wx:for="{{specifications}}"
wx:key="item.name"
class="spec-item"
data-spec="{{item}}"
bindtap="selectSpec"
>
<view class="spec-info">
<text class="spec-name">{{item.name}}</text>
</view>
<view class="spec-radio {{selectedSpec === item.name ? 'selected' : ''}}">
<view wx:if="selectedSpec === item.name" class="radio-inner"></view>
</view>
</view>
</view>
<!-- 暂无更多规格提示 -->
<view wx:if="{{specifications.length > 0}}" class="no-more">
<text class="no-more-text">已经到底啦</text>
</view>
</view>
<!-- 无规格提示 -->
<view wx:if="{{!loading && !error && specifications.length === 0}}" class="empty-state">
<view class="empty-icon">📋</view>
<text class="empty-text">该商品暂无可用规格</text>
<text class="empty-subtext">试试其他商品吧</text>
<button bindtap="goBackToProductList" class="btn-secondary">返回商品列表</button>
</view>
</view>
</view>

671
pages/evaluate2/index.wxss

@ -1,671 +0,0 @@
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
background: linear-gradient(135deg, #F9FAFB 0%, #F2F4F8 100%);
font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}
/* 步骤指示器 */
.step-indicator {
display: flex;
align-items: center;
justify-content: space-between;
padding: 32rpx;
background: #FFFFFF;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
margin-bottom: 24rpx;
width: 100%;
box-sizing: border-box;
}
.step-item {
display: flex;
flex-direction: column;
align-items: center;
flex: 1;
}
.step-number {
width: 48rpx;
height: 48rpx;
border-radius: 50%;
background: #E5E5E5;
display: flex;
align-items: center;
justify-content: center;
font-size: 24rpx;
font-weight: 600;
color: #999;
margin-bottom: 8rpx;
transition: all 0.3s ease;
}
.step-text {
font-size: 20rpx;
color: #999;
transition: all 0.3s ease;
}
.step-item.active .step-number {
background: #007AFF;
color: #FFFFFF;
box-shadow: 0 0 0 8rpx rgba(0,122,255,0.1);
}
.step-item.active .step-text {
color: #007AFF;
font-weight: 500;
}
.step-line {
flex: 1;
height: 2rpx;
background: #E5E5E5;
margin: 0 16rpx;
transition: all 0.3s ease;
}
.step-line.active {
background: #007AFF;
}
.header {
background: #FFFFFF;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
position: sticky;
top: 0;
z-index: 10;
width: 100%;
box-sizing: border-box;
}
.header-content {
display: flex;
align-items: center;
padding: 24rpx 32rpx;
width: 100%;
box-sizing: border-box;
height: 100rpx;
max-width: 100%;
position: relative;
}
.back-button {
width: 100rpx;
height: 60rpx;
line-height: 60rpx;
font-size: 36rpx;
color: #4a90e2;
background: transparent;
border: none;
padding: 0 16rpx 0 0;
margin: 0;
display: flex;
align-items: center;
justify-content: flex-start;
border-radius: 8rpx;
transition: all 0.3s ease;
flex-shrink: 0;
overflow: visible;
}
.back-button:hover {
color: #3b82f6;
background: rgba(74, 144, 226, 0.1);
}
.back-icon {
margin-right: 8rpx;
font-size: 36rpx;
font-weight: 600;
transition: all 0.3s ease;
display: inline-block;
}
.back-button:hover .back-icon {
transform: translateX(-12rpx);
font-weight: 700;
}
.back-text {
font-size: 36rpx;
font-weight: 700;
}
.title {
font-size: 36rpx;
font-weight: 700;
color: #2c3e50;
letter-spacing: 2rpx;
text-align: center;
margin: 0;
padding: 0;
position: absolute;
left: 50%;
transform: translateX(-50%);
width: 100%;
max-width: 300rpx;
}
.header-right {
width: 60rpx;
flex-shrink: 0;
}
.content {
flex: 1;
padding: 32rpx;
display: flex;
flex-direction: column;
width: 100%;
box-sizing: border-box;
overflow-x: hidden;
}
/* 加载状态 */
.loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.9);
z-index: 9999;
width: 100%;
box-sizing: border-box;
}
.loading-spinner {
width: 80rpx;
height: 80rpx;
border: 8rpx solid rgba(74, 144, 226, 0.2);
border-top: 8rpx solid #4a90e2;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 32rpx;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading-text {
font-size: 28rpx;
color: #666;
font-weight: 500;
}
/* 错误提示卡片 */
.error-card {
background: #fff;
border-radius: 16rpx;
padding: 48rpx;
margin: 32rpx 0;
box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.08);
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
}
.error-icon {
font-size: 80rpx;
margin-bottom: 24rpx;
}
.error-text {
font-size: 28rpx;
color: #e74c3c;
margin-bottom: 32rpx;
line-height: 1.5;
}
/* 按钮样式 */
.button-group {
display: flex;
gap: 16rpx;
width: 100%;
}
.btn-primary {
flex: 1;
height: 80rpx;
line-height: 80rpx;
font-size: 32rpx;
font-weight: 600;
border-radius: 40rpx;
background: linear-gradient(135deg, #007AFF 0%, #0051D5 100%);
color: #fff;
border: none;
box-shadow: 0 4rpx 8rpx rgba(0,122,255,0.2);
transition: all 0.3s ease;
padding: 0 48rpx;
}
.btn-primary:hover {
transform: translateY(-2rpx);
box-shadow: 0 6rpx 16rpx rgba(0,122,255,0.3);
}
.btn-secondary {
flex: 1;
height: 80rpx;
line-height: 80rpx;
font-size: 32rpx;
font-weight: 600;
border-radius: 40rpx;
background: #fff;
color: #007AFF;
border: 1rpx solid #007AFF;
transition: all 0.3s ease;
padding: 0 48rpx;
}
.btn-secondary:hover {
background: rgba(0,122,255,0.05);
transform: translateY(-2rpx);
}
.btn-change-product {
display: flex;
align-items: center;
justify-content: center;
padding: 12rpx 24rpx;
font-size: 28rpx;
color: #007AFF;
background: transparent;
border: 1rpx solid #007AFF;
border-radius: 20rpx;
transition: all 0.3s ease;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}
.btn-change-product:hover {
background: rgba(0,122,255,0.1);
transform: translateY(-2rpx);
box-shadow: 0 4rpx 12rpx rgba(0,122,255,0.2);
}
.btn-change-product-text {
font-size: 28rpx;
}
/* 商品信息卡片 */
.product-card {
background: #FFFFFF;
border-radius: 12rpx;
padding: 32rpx;
margin: 24rpx 0 32rpx;
width: 100%;
box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.04);
transition: all 0.3s ease;
}
.product-info-container {
width: 100%;
box-sizing: border-box;
}
.product-info-row {
display: flex;
align-items: center;
width: 100%;
box-sizing: border-box;
}
.product-image-container {
width: 120rpx;
height: 120rpx;
border-radius: 8rpx;
overflow: hidden;
margin-right: 24rpx;
background: #F5F5F5;
flex-shrink: 0;
}
.product-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.product-details {
flex: 1;
display: flex;
flex-direction: column;
gap: 8rpx;
}
.product-name {
font-size: 32rpx;
font-weight: 600;
color: #333;
line-height: 1.4;
word-break: break-word;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.product-hint {
font-size: 24rpx;
color: #999;
line-height: 1.4;
}
/* 规格列表区域 */
.spec-section {
margin-top: 32rpx;
width: 100%;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24rpx;
padding: 0;
width: 100%;
}
.section-title {
font-size: 32rpx;
font-weight: 600;
color: #333;
padding-left: 16rpx;
border-left: 6rpx solid #007AFF;
border-radius: 4rpx;
line-height: 32rpx;
}
.section-count {
font-size: 28rpx;
color: #999;
}
/* 规格列表布局 */
.spec-list {
margin-top: 16rpx;
display: flex;
flex-direction: column;
gap: 16rpx;
width: 100%;
}
/* 规格项 */
.spec-item {
background: #FFFFFF;
border: 1rpx solid #E5E5E5;
border-radius: 12rpx;
padding: 32rpx 32rpx;
cursor: pointer;
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
box-sizing: border-box;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.02);
transition: all 0.3s ease;
}
.spec-radio {
width: 32rpx;
height: 32rpx;
border: 2rpx solid #E5E5E5;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
transition: all 0.3s ease;
margin-left: 16rpx;
}
.spec-item:hover {
box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
transform: translateY(-2rpx);
}
.spec-item:active {
background: #F5F5F5;
}
.spec-item.selected {
border: 2rpx solid #007AFF;
box-shadow: 0 0 0 4rpx rgba(0,122,255,0.1);
}
.spec-info {
flex: 1;
display: flex;
flex-direction: column;
gap: 8rpx;
}
.spec-name {
font-size: 30rpx;
font-weight: 500;
color: #333;
line-height: 1.4;
word-break: break-word;
padding: 0 8rpx;
}
.spec-details {
font-size: 24rpx;
color: #666;
line-height: 1.4;
padding: 0 8rpx;
}
.spec-radio {
width: 32rpx;
height: 32rpx;
border: 2rpx solid #E5E5E5;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
transition: all 0.3s ease;
}
.spec-radio.selected {
border-color: #007AFF;
background: #007AFF;
}
.radio-inner {
width: 16rpx;
height: 16rpx;
border-radius: 50%;
background: #FFFFFF;
transition: all 0.3s ease;
}
/* 空状态 */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 120rpx 0;
text-align: center;
width: 100%;
}
.empty-icon {
font-size: 120rpx;
margin-bottom: 40rpx;
opacity: 0.6;
color: #CCC;
}
.empty-text {
font-size: 32rpx;
font-weight: 600;
color: #333;
margin-bottom: 16rpx;
line-height: 1.4;
padding: 0 40rpx;
}
.empty-subtext {
font-size: 28rpx;
color: #999;
margin-bottom: 48rpx;
line-height: 1.4;
padding: 0 40rpx;
}
/* 响应式设计 */
@media (max-width: 750rpx) {
.content {
padding: 24rpx;
}
.product-card {
padding: 28rpx;
}
.title {
font-size: 32rpx;
}
.section-title {
font-size: 28rpx;
}
.product-name {
font-size: 28rpx;
}
.button-group {
flex-direction: column;
gap: 12rpx;
}
.btn-primary,
.btn-secondary {
width: 100%;
}
.spec-item {
padding: 28rpx 20rpx;
}
.spec-name {
font-size: 28rpx;
}
.spec-details {
font-size: 22rpx;
}
.spec-list {
gap: 16rpx;
}
.product-image-container {
width: 100rpx;
height: 100rpx;
}
.product-name {
font-size: 28rpx;
}
.product-hint {
font-size: 22rpx;
}
}
/* 小屏幕设备适配 */
@media (max-width: 414rpx) {
.content {
padding: 24rpx;
}
.title {
font-size: 32rpx;
}
.section-title {
font-size: 28rpx;
}
.product-name {
font-size: 26rpx;
}
.spec-item {
padding: 24rpx 16rpx;
}
.spec-name {
font-size: 24rpx;
}
.spec-details {
font-size: 20rpx;
}
.btn-change-product {
padding: 10rpx 20rpx;
}
.btn-change-product-text {
font-size: 26rpx;
}
.spec-list {
gap: 12rpx;
}
.product-image-container {
width: 80rpx;
height: 80rpx;
}
.product-name {
font-size: 26rpx;
}
.product-hint {
font-size: 20rpx;
}
}
/* 暂无更多规格提示 */
.no-more {
display: flex;
align-items: center;
justify-content: center;
padding: 48rpx 0;
margin-top: 32rpx;
margin-bottom: 40rpx;
width: 100%;
}
.no-more::before,
.no-more::after {
content: '';
flex: 1;
height: 1rpx;
background: #E5E5E5;
margin: 0 16rpx;
}
.no-more-text {
font-size: 24rpx;
color: #BBB;
font-weight: 500;
white-space: nowrap;
}

845
pages/evaluate2/one.js

@ -1,845 +0,0 @@
Page({
data: {
productName: '',
specifications: [],
loading: false,
error: '',
categories: [],
selectedCategory: '',
showOneKeyLoginModal: false, // 是否显示登录弹窗
categoryDescriptions: {
'粉壳': '粉壳蛋由白壳与褐壳蛋鸡杂交而成,蛋壳呈粉红色,表面清洁带白霜。其蛋清浓稠、蛋黄大而饱满,营养丰富且口感细腻',
'绿壳': '绿壳蛋是我国特有珍稀鸡种所产的蛋,具有"五黑一绿"特点(黑毛、黑皮、黑骨、黑内脏,产绿壳蛋)。其蛋黄大、蛋清稠,氨基酸含量比普通鸡蛋高5-10倍,被誉为"保健蛋"',
'褐壳': '褐壳蛋是我国市场上最常见的鸡蛋类型,由洛岛红、新汉夏等褐壳蛋鸡品种产出。蛋壳呈褐色至深褐色,质地厚实耐运输,蛋黄比例大,适合家庭日常烹饪。常见品种有海兰褐、罗曼褐等。',
'土鸡蛋': '土鸡蛋指农家散养鸡在自然环境中觅食所产的蛋,个头较小、蛋壳较薄,蛋清粘稠、蛋黄饱满。口感风味浓郁。'
}
},
onLoad(options) {
let productName = '';
// 首先检查URL参数
if (options.productName) {
productName = options.productName;
} else {
// 然后检查本地存储(用于wx.switchTab导航)
productName = wx.getStorageSync('selectedProductName') || '';
// 清除本地存储中的商品名称,避免影响下次进入
if (productName) {
wx.removeStorageSync('selectedProductName');
}
}
// 增加用户估价点击次数(进入页面时自动增加)
const API = require('../../utils/api');
API.incrementAppraisalNum().then(res => {
console.log('增加估价次数成功:', res);
}).catch(err => {
console.error('增加估价次数失败:', err);
// 即使失败也不影响主流程
});
if (productName) {
this.setData({ productName: productName });
this.loadSpecifications(productName);
} else {
// 如果没有商品名称参数,加载所有商品数据并计算
this.loadAllData();
}
},
// 下拉刷新
onPullDownRefresh() {
console.log('开始下拉刷新');
this.loadAllData();
},
// 加载所有商品数据并计算
loadAllData() {
this.setData({
loading: true,
categories: [] // 清空分类数据,确保加载时只显示加载状态
});
const api = require('../../utils/api');
// 使用正确的参数调用getProducts方法
api.getProducts(1, 1000, 'all', '').then(result => {
console.log('API返回结果:', result);
// 从返回对象中提取products数组,如果不存在则使用空数组
const products = result.products || [];
console.log('提取的products数组:', products);
console.log('products数组长度:', products.length);
// 存储原始商品数据到本地存储
wx.setStorageSync('allProducts', products);
// 过滤出有有效category字段的商品(忽略空字符串和仅包含空格的分类)
const productsWithCategory = products.filter(product => {
if (!product.category) return false;
const categoryStr = String(product.category).trim();
return categoryStr !== '';
});
console.log('有有效category的商品:', productsWithCategory);
console.log('有有效category的商品数量:', productsWithCategory.length);
// 提取所有分类(去除前后空格)
const categories = [...new Set(productsWithCategory.map(product => {
let category = String(product.category).trim();
// 将"白壳"替换为"土鸡蛋"
if (category === '白壳') {
category = '土鸡蛋';
}
return category;
}))];
console.log('提取的分类数组:', categories);
console.log('分类数量:', categories.length);
// 存储分类数据到本地存储
wx.setStorageSync('evaluate2Categories', categories);
// 计算每个分类下的商品名称列表
const categoryProductsMap = {};
categories.forEach(category => {
// 过滤出该分类下的商品
const categoryProducts = productsWithCategory.filter(product => {
const productCategory = String(product.category).trim();
return productCategory === category;
});
// 提取商品名称(去除前后空格,去重)
const productNames = [...new Set(categoryProducts.map(product => {
// 尝试从多个字段获取商品名称
const nameFields = [product.productName, product.name, product.product];
for (const field of nameFields) {
if (field) {
const trimmedName = String(field).trim();
if (trimmedName !== '') {
return trimmedName;
}
}
}
return '';
}).filter(name => name !== ''))];
categoryProductsMap[category] = productNames;
});
// 存储分类商品映射到本地存储
wx.setStorageSync('evaluate2CategoryProductsMap', categoryProductsMap);
// 计算每个商品的规格和价格信息
const productSpecsMap = {};
products.forEach(product => {
// 尝试从多个字段获取商品名称
const nameFields = [product.productName, product.name, product.product];
let productName = '';
for (const field of nameFields) {
if (field) {
const trimmedName = String(field).trim();
if (trimmedName !== '') {
productName = trimmedName;
break;
}
}
}
if (productName) {
if (!productSpecsMap[productName]) {
productSpecsMap[productName] = [];
}
// 提取规格和价格
const specStr = (product.specification || product.spec || '').trim();
const price = product.price || '';
if (specStr && price) {
productSpecsMap[productName].push({
specification: specStr,
price: price
});
}
}
});
// 存储商品规格映射到本地存储
wx.setStorageSync('evaluate2ProductSpecsMap', productSpecsMap);
// 加载分类数据到页面
this.setData({
categories: categories,
loading: false
});
// 结束下拉刷新
wx.stopPullDownRefresh();
}).catch(err => {
console.error('获取商品数据失败:', err);
this.setData({
error: '获取商品数据失败,请稍后重试',
loading: false
});
// 结束下拉刷新
wx.stopPullDownRefresh();
});
},
// 加载商品分类数据
loadCategories() {
this.setData({ loading: true });
// 尝试从本地存储中获取分类数据
let categories = wx.getStorageSync('evaluate2Categories') || [];
// 处理分类数据,将"白壳"替换为"土鸡蛋"
categories = categories.map(category => {
if (category === '白壳') {
return '土鸡蛋';
}
return category;
});
if (categories.length > 0) {
// 如果本地存储中有分类数据,直接使用
console.log('从本地存储获取分类数据:', categories);
this.setData({
categories: categories,
loading: false
});
} else {
// 如果本地存储中没有分类数据,重新加载所有数据
this.loadAllData();
}
},
loadSpecifications(productName) {
if (!productName) {
this.setData({
error: '请先选择商品',
loading: false
});
return;
}
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');
// 使用正确的参数调用getProducts方法
api.getProducts(1, 1000, 'all', '').then(result => {
// 从返回对象中提取products数组
const products = result.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 (!price || price.trim() === '') {
console.log(`商品价格为空,跳过处理`);
return;
}
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()).filter(p => p && p.trim() !== '');
console.log(`规格数组:`, specs);
console.log(`价格数组:`, prices);
// 价格为空的不参与计算
if (prices.length === 0) {
console.log(`价格数组为空,跳过处理`);
return;
}
// 将规格和价格配对
specs.forEach((spec, index) => {
if (spec.length > 0) {
// 确保价格索引不超出范围
const priceIndex = index % prices.length;
const matchedPrice = prices[priceIndex] || '';
console.log(`规格'${spec}' 配对价格: '${matchedPrice}'`);
// 只有当价格不为空时才添加该规格
if (matchedPrice && matchedPrice.trim() !== '') {
// 收集相同规格的所有价格,以便计算平均值
if (!specPriceMap[spec]) {
specPriceMap[spec] = [];
}
specPriceMap[spec].push(matchedPrice);
} else {
console.log(`规格'${spec}' 价格为空,不添加`);
}
}
});
}
});
// 转换为规格对象数组
const specifications = Object.keys(specPriceMap).map(spec => {
const prices = specPriceMap[spec];
console.log(`规格'${spec}' 的所有原始价格:`, prices);
// 解析规格
const specInfo = this.parseSpecification(spec);
// 处理每个价格
const processedPrices = prices.map(price => {
if (!price || price.trim() === '' || isNaN(parseFloat(price))) {
return 0;
}
const priceValue = parseFloat(price);
console.log(`处理价格: ${priceValue}`);
// 价格<10的需要按照公式计算
if (priceValue < 10 && specInfo) {
console.log(`价格 ${priceValue} < 10,按照公式计算`);
if (specInfo.type === '净重') {
// 净重:规格平均值 × 价格
return specInfo.avg * priceValue;
} else if (specInfo.type === '毛重') {
// 毛重:(规格平均值 - 5) × 价格
return (specInfo.avg - 5) * priceValue;
}
}
// 价格>=10的直接使用
return priceValue;
}).filter(price => price > 0); // 过滤掉0值
console.log(`规格'${spec}' 处理后的价格:`, processedPrices);
// 计算处理后价格的平均值
let finalPrice = 0;
let finalPriceText = '';
if (processedPrices.length > 0) {
const sum = processedPrices.reduce((acc, price) => acc + price, 0);
finalPrice = sum / processedPrices.length;
finalPriceText = finalPrice.toFixed(2);
console.log(`规格'${spec}' 处理后价格的平均值: ${finalPriceText} (基于 ${processedPrices.length} 个价格)`);
} else {
console.log(`规格'${spec}' 没有有效价格`);
}
const specObj = {
name: spec,
price: finalPriceText,
priceText: finalPriceText,
finalPrice: finalPrice,
finalPriceText: finalPriceText
};
console.log('创建的规格对象:', specObj);
return specObj;
});
console.log('提取的规格和价格:', specifications);
// 对规格进行排序
specifications.sort((a, b) => {
// 解析两个规格
const specA = this.parseSpecification(a.name);
const specB = this.parseSpecification(b.name);
// 如果有一个规格解析失败,保持原顺序
if (!specA || !specB) {
return 0;
}
// 1. 按类型排序:净重在前,毛重在后
if (specA.type !== specB.type) {
return specA.type === '净重' ? -1 : 1;
}
// 2. 按规格最小值排序:从小到大
return specA.min - specB.min;
});
console.log('排序后的规格:', specifications);
this.setData({
specifications: specifications,
error: '', // 清除之前的错误
loading: false
});
},
// 跳转到规格详情页面
goToSpecDetail(e) {
const specItem = e.currentTarget.dataset.spec;
console.log('点击的规格项:', specItem);
console.log('传递的价格:', specItem.finalPriceText);
// 增加用户估价点击次数
const API = require('../../utils/api');
API.incrementAppraisalNum().then(res => {
console.log('增加估价次数成功:', res);
}).catch(err => {
console.error('增加估价次数失败:', err);
// 即使失败也不影响主流程
});
wx.navigateTo({
url: `/pages/evaluate1/spec-detail?productName=${encodeURIComponent(this.data.productName)}&specification=${encodeURIComponent(specItem.name)}&price=${encodeURIComponent(specItem.finalPriceText)}`
});
},
// 返回上一页
goBack() {
wx.navigateBack();
},
// 返回商品列表页面
goBackToProductList() {
wx.redirectTo({
url: '/pages/evaluate1/product-list'
});
},
// 选择分类,跳转到商品列表页面
selectCategory(e) {
const category = e.currentTarget.dataset.category;
console.log('选择分类:', category);
// 检查用户登录状态
const openid = wx.getStorageSync('openid');
const userId = wx.getStorageSync('userId');
if (!openid || !userId) {
// 用户未登录,显示登录弹窗
console.log('用户未登录,显示登录弹窗');
this.setData({
showOneKeyLoginModal: true
});
return;
}
// 记录用户点击分类的踪迹
const API = require('../../utils/api');
const traceData = {
action: 'click_category',
category: category,
timestamp: new Date().toISOString(),
page: 'evaluate2/one'
};
// 调用用户踪迹记录API
API.addUserTrace(traceData).then(res => {
console.log('用户分类点击记录成功:', res);
}).catch(err => {
console.error('用户分类点击记录失败:', err);
// 即使记录失败,也不影响主流程
});
// 跳过合作状态检查,直接跳转到商品列表页面
// 跳转到商品列表页面,并传递分类参数
wx.redirectTo({
url: `/pages/evaluate2/product-list?category=${encodeURIComponent(category)}`
});
},
// 关闭登录弹窗
closeOneKeyLoginModal() {
this.setData({
showOneKeyLoginModal: false
});
},
// 处理登录授权
async onGetPhoneNumber(e) {
console.log('收到手机号授权事件:', 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;
}
// 检查是否已经登录,避免重复授权
const existingOpenid = wx.getStorageSync('openid');
const existingUserId = wx.getStorageSync('userId');
const existingUserInfo = wx.getStorageSync('userInfo');
if (existingOpenid && existingUserId && existingUserInfo && existingUserInfo.phoneNumber) {
console.log('用户已登录且手机号有效,登录流程已完成');
wx.showToast({
title: '您已登录',
icon: 'success',
duration: 1500
});
return;
}
wx.showLoading({ title: '登录中...', mask: true });
try {
if (e.detail.errMsg === 'getPhoneNumber:ok') {
// 用户同意授权,实际处理授权流程
console.log('用户同意授权获取手机号');
// 1. 先执行微信登录获取code
const loginRes = await new Promise((resolve, reject) => {
wx.login({
success: resolve,
fail: reject
});
});
if (!loginRes.code) {
throw new Error('获取登录code失败');
}
console.log('获取登录code成功:', loginRes.code);
// 2. 使用code换取openid
const API = require('../../utils/api');
const openidRes = await API.getOpenid(loginRes.code);
// 改进错误处理逻辑,更宽容地处理服务器返回格式
let openid = null;
let userId = null;
console.log('openidRes完整响应:', JSON.stringify(openidRes));
if (openidRes && typeof openidRes === 'object') {
// 适配服务器返回格式:{success: true, code: 200, message: '获取openid成功', data: {openid, userId}}
if (openidRes.data && typeof openidRes.data === 'object') {
console.log('识别到标准服务器返回格式,从data字段提取信息');
openid = openidRes.data.openid || openidRes.data.OpenID || null;
userId = openidRes.data.userId || null;
} else {
// 尝试从响应对象中直接提取openid
console.log('尝试从根对象直接提取openid');
openid = openidRes.openid || openidRes.OpenID || null;
userId = openidRes.userId || null;
}
}
if (!openid) {
console.error('无法从服务器响应中提取openid,完整响应:', JSON.stringify(openidRes));
throw new Error(`获取openid失败: 服务器返回数据格式可能不符合预期`);
}
console.log('获取openid成功:', openid);
// 3. 存储openid和session_key
wx.setStorageSync('openid', openid);
// 从服务器返回中获取session_key
if (openidRes && openidRes.session_key) {
wx.setStorageSync('sessionKey', openidRes.session_key);
} else if (openidRes && openidRes.data && openidRes.data.session_key) {
wx.setStorageSync('sessionKey', openidRes.data.session_key);
}
// 优先使用从服务器响应data字段中提取的userId
if (userId) {
wx.setStorageSync('userId', userId);
console.log('使用从服务器data字段提取的userId:', userId);
} else if (openidRes && openidRes.userId) {
wx.setStorageSync('userId', openidRes.userId);
console.log('使用服务器根对象中的userId:', openidRes.userId);
} else {
// 生成临时userId
const tempUserId = 'user_' + Date.now();
wx.setStorageSync('userId', tempUserId);
console.log('生成临时userId:', tempUserId);
}
// 4. 上传手机号加密数据到服务器解密
const phoneData = {
...e.detail,
openid: openid
};
console.log('准备上传手机号加密数据到服务器');
const phoneRes = await API.uploadPhoneNumberData(phoneData);
// 改进手机号解密结果的处理逻辑
if (!phoneRes || (!phoneRes.success && !phoneRes.phoneNumber)) {
// 如果服务器返回格式不标准但包含手机号,也接受
if (phoneRes && phoneRes.phoneNumber) {
console.warn('服务器返回格式可能不符合预期,但成功获取手机号');
} else {
throw new Error('获取手机号失败: ' + (phoneRes && phoneRes.message ? phoneRes.message : '未知错误'));
}
}
// 检查是否有手机号冲突
const hasPhoneConflict = phoneRes.phoneNumberConflict || false;
const isNewPhone = phoneRes.isNewPhone || true;
const phoneNumber = phoneRes.phoneNumber || null;
// 如果有手机号冲突且没有返回手机号,使用实际返回的手机号
const finalPhoneNumber = phoneNumber;
console.log('手机号解密结果:', {
phoneNumber: finalPhoneNumber,
hasPhoneConflict: hasPhoneConflict,
isNewPhone: isNewPhone
});
// 5. 获取用户微信名称和头像
let userProfile = null;
try {
userProfile = await new Promise((resolve, reject) => {
wx.getUserProfile({
desc: '用于完善会员资料',
success: resolve,
fail: reject
});
});
console.log('获取用户信息成功:', userProfile);
} catch (err) {
console.warn('获取用户信息失败:', err);
// 如果获取失败,使用默认值
}
// 6. 创建用户信息
const tempUserInfo = {
name: userProfile ? (userProfile.userInfo.name || userProfile.userInfo.nickName) : '微信用户',
// 获取微信头像失败时使用微信默认头像
avatarUrl: userProfile ? userProfile.userInfo.avatarUrl : 'https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E6%B5%B7%E8%93%9D%E7%81%B0/image/7a2a8a17a83ba4d3d4270828531e2041.jpeg',
gender: userProfile ? userProfile.userInfo.gender : 0,
country: userProfile ? userProfile.userInfo.country : '',
province: userProfile ? userProfile.userInfo.province : '',
city: userProfile ? userProfile.userInfo.city : '',
language: userProfile ? userProfile.userInfo.language : 'zh_CN',
phoneNumber: finalPhoneNumber
};
// 7. 保存用户信息
const storedUserId = wx.getStorageSync('userId');
const users = wx.getStorageSync('users') || {};
const currentUserType = users[storedUserId] && users[storedUserId].type ? users[storedUserId].type : 'buyer';
console.log('用户身份类型:', currentUserType);
// 8. 保存用户信息到本地和服务器
console.log('开始保存用户信息...');
await this.saveUserInfo(tempUserInfo, currentUserType);
console.log('用户信息保存完成');
wx.hideLoading();
// 根据服务器返回的结果显示不同的提示
if (phoneRes && phoneRes.phoneNumberConflict) {
wx.showModal({
title: '登录成功',
content: '您的手机号已被其他账号绑定',
showCancel: false,
confirmText: '我知道了',
success(res) {
if (res.confirm) {
console.log('用户点击了我知道了');
}
}
});
}
// 1. 登录成功提示
wx.showToast({
title: '登录成功',
icon: 'success',
duration: 1500
});
// 2. 从服务器获取最新用户信息
const userInfoRes = await API.getUserInfo(openid);
// 3. 获取服务器返回的partnerstatus
const serverUserInfo = userInfoRes.data;
const partnerStatus = serverUserInfo.partnerstatus || 'pending';
// 4. 更新本地缓存
const localUserInfo = wx.getStorageSync('userInfo') || {};
const updatedUserInfo = {
...localUserInfo,
partnerstatus: partnerStatus
};
wx.setStorageSync('userInfo', updatedUserInfo);
// 跳过合作状态检查,不再显示入驻提示
}
} catch (error) {
wx.hideLoading();
console.error('登录失败:', error);
wx.showToast({
title: '登录失败,请重试',
icon: 'none',
duration: 2000
});
}
},
// 保存用户信息
async saveUserInfo(userInfo, userType = 'buyer') {
return new Promise(async (resolve, reject) => {
try {
const storedUserId = wx.getStorageSync('userId');
const users = wx.getStorageSync('users') || {};
// 更新用户信息
users[storedUserId] = {
...users[storedUserId],
...userInfo,
type: userType,
lastLogin: new Date().toISOString()
};
// 保存到本地存储
wx.setStorageSync('users', users);
wx.setStorageSync('userInfo', userInfo);
// 上传用户信息到服务器
const API = require('../../utils/api');
const submitData = {
openid: wx.getStorageSync('openid'),
userId: storedUserId,
...userInfo,
type: userType
};
await API.request('/api/user/update', 'POST', submitData).then(res => {
console.log('用户信息上传成功:', res);
resolve({ success: true, message: '用户信息保存成功' });
}).catch(err => {
console.error('用户信息上传失败:', err);
// 即使服务器上传失败,也继续流程,只在本地保存
resolve({ success: false, message: '本地保存成功,服务器同步失败' });
});
} catch (error) {
console.error('保存用户信息失败:', error);
reject(error);
}
});
},
// 分享配置
onShareAppMessage() {
return {
title: '专业的估价平台,专为估蛋而生',
imageUrl: 'https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BD%97%E6%9B%BC%E7%81%B0/image/c00cbcbfd12d747b44621701aed2ae02.jpeg',
path: '/pages/evaluate2/one'
};
},
// 朋友圈分享配置
onShareTimeline() {
return {
title: '专业的估价平台,专为估蛋而生',
imageUrl: 'https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BD%97%E6%9B%BC%E7%81%B0/image/c00cbcbfd12d747b44621701aed2ae02.jpeg',
query: ''
};
}
});

5
pages/evaluate2/one.json

@ -1,5 +0,0 @@
{
"usingComponents": {},
"enablePullDownRefresh": true,
"backgroundTextStyle": "dark"
}

221
pages/evaluate2/one.wxml

@ -1,221 +0,0 @@
<view class="container">
<!-- 步骤指示器 -->
<view class="step-indicator">
<view class="step-item active">
<view class="step-number">1</view>
<text class="step-text">选择品种</text>
</view>
<view class="step-line"></view>
<view class="step-item">
<view class="step-number">2</view>
<text class="step-text">选择产品</text>
</view>
<view class="step-line"></view>
<view class="step-item">
<view class="step-number">3</view>
<text class="step-text">选择规格</text>
</view>
<view class="step-line"></view>
<view class="step-item">
<view class="step-number">4</view>
<text class="step-text">查看估价</text>
</view>
</view>
<!-- 登录弹窗 -->
<view wx:if="{{showOneKeyLoginModal}}" class="auth-modal-overlay">
<view class="auth-modal-container">
<view class="auth-modal-title">授权登录</view>
<view class="auth-modal-content">授权您的手机号后才能使用完整功能</view>
<view class="auth-modal-buttons">
<button
class="auth-primary-button"
open-type="getPhoneNumber"
bindgetphonenumber="onGetPhoneNumber"
>
授权手机号
</button>
<button
class="auth-cancel-button"
bindtap="closeOneKeyLoginModal"
>
取消
</button>
</view>
</view>
</view>
<view class="content">
<!-- 加载中状态 -->
<view wx:if="{{loading}}" class="loading">
<view class="loading-spinner"></view>
<text class="loading-text">正在加载数据...</text>
</view>
<!-- 错误提示 -->
<view wx:if="{{error}}" class="error-card">
<view class="error-icon">⚠️</view>
<text class="error-text">{{error}}</text>
<view class="button-group">
<button bindtap="loadCategories" class="btn-primary">重新加载</button>
<button bindtap="goBackToProductList" class="btn-secondary">返回商品列表</button>
</view>
</view>
<!-- 分类选择区域 -->
<view wx:else class="category-section">
<view class="section-header">
<text class="section-title">商品分类</text>
<text class="section-count">{{categories.length}}个</text>
</view>
<view class="category-grid">
<view
wx:for="{{categories}}"
wx:key="item"
class="category-card {{item === '粉壳' ? 'pink-shell-card' : item === '绿壳' ? 'green-shell-card' : item === '褐壳' ? 'brown-shell-card' : 'free-range-card'}}"
data-category="{{item}}"
bindtap="selectCategory"
>
<!-- 标签系统 -->
<view class="card-labels">
<view class="feature-label">
<text class="feature-label-text">{{item === '绿壳' ? '珍稀品种' : item === '粉壳' ? '杂交品种' : item === '褐壳' ? '常见品种' : '农家散养'}}</text>
</view>
<view class="category-label">
<text class="category-label-text">{{item}}系列</text>
</view>
</view>
<!-- 产品图片区域 -->
<view class="product-image-container">
<image
src="../../images/OIP-C.png"
mode="aspectFill"
class="product-image"
/>
</view>
<!-- 文字信息区域 -->
<view class="card-content">
<text class="product-title">{{item}}鸡蛋</text>
<text class="product-description">{{categoryDescriptions[item] || '点击选择此类型查看相关商品'}}</text>
<!-- 卖点标签 -->
<view class="selling-points">
<!-- 粉壳鸡蛋卖点 -->
<view wx:if="{{item === '粉壳'}}" class="selling-point">
<text class="selling-point-icon">🧬</text>
<text class="selling-point-text">杂交品种</text>
</view>
<view wx:if="{{item === '粉壳'}}" class="selling-point">
<text class="selling-point-icon">🌸</text>
<text class="selling-point-text">粉红蛋壳</text>
</view>
<view wx:if="{{item === '粉壳'}}" class="selling-point">
<text class="selling-point-icon">👅</text>
<text class="selling-point-text">口感细腻</text>
</view>
<!-- 绿壳鸡蛋卖点 -->
<view wx:if="{{item === '绿壳'}}" class="selling-point">
<text class="selling-point-icon">🍃</text>
<text class="selling-point-text">五黑一绿</text>
</view>
<view wx:if="{{item === '绿壳'}}" class="selling-point">
<text class="selling-point-icon">💪</text>
<text class="selling-point-text">高氨基酸</text>
</view>
<view wx:if="{{item === '绿壳'}}" class="selling-point">
<text class="selling-point-icon">🏥</text>
<text class="selling-point-text">保健功效</text>
</view>
<!-- 褐壳鸡蛋卖点 -->
<view wx:if="{{item === '褐壳'}}" class="selling-point">
<text class="selling-point-icon">🔥</text>
<text class="selling-point-text">常见品种</text>
</view>
<view wx:if="{{item === '褐壳'}}" class="selling-point">
<text class="selling-point-icon">📦</text>
<text class="selling-point-text">耐运输</text>
</view>
<view wx:if="{{item === '褐壳'}}" class="selling-point">
<text class="selling-point-icon">🍳</text>
<text class="selling-point-text">日常烹饪</text>
</view>
<!-- 土鸡蛋卖点 -->
<view wx:if="{{item === '土鸡蛋'}}" class="selling-point">
<text class="selling-point-icon">🌾</text>
<text class="selling-point-text">自然觅食</text>
</view>
<view wx:if="{{item === '土鸡蛋'}}" class="selling-point">
<text class="selling-point-icon">🥚</text>
<text class="selling-point-text">蛋黄饱满</text>
</view>
<view wx:if="{{item === '土鸡蛋'}}" class="selling-point">
<text class="selling-point-icon">🥘</text>
<text class="selling-point-text">风味浓郁</text>
</view>
</view>
<!-- 按钮区域 -->
<view class="card-footer">
<button class="select-button" bindtap="selectCategory" data-category="{{item}}">
<text class="select-button-icon">→</text>
<text class="select-button-text">选择</text>
</button>
</view>
</view>
</view>
</view>
</view>
<!-- 商品信息 (当有productName时显示) -->
<view wx:if="{{productName}}" class="product-card">
<view class="product-info-container">
<view class="product-info-row">
<text class="product-label">商品名称</text>
<button bindtap="goBackToProductList" class="btn-back">
<text class="btn-back-icon">←</text>
<text class="btn-back-text">更换商品</text>
</button>
</view>
<text class="product-name">{{productName}}</text>
</view>
</view>
<!-- 规格列表 (当有specifications时显示) -->
<view wx:if="{{!loading && !error && specifications.length > 0}}" class="spec-section">
<view class="section-header">
<text class="section-title">可用规格</text>
<text class="section-count">{{specifications.length}}个</text>
</view>
<view class="spec-grid">
<view
wx:for="{{specifications}}"
wx:key="item.name"
class="spec-card"
data-spec="{{item}}"
bindtap="goToSpecDetail"
>
<view class="spec-info">
<text class="spec-name">{{item.name}}</text>
</view>
</view>
</view>
<!-- 暂无更多规格提示 -->
<view wx:if="{{specifications.length > 0}}" class="no-more">
<text class="no-more-text">暂无更多规格选择</text>
</view>
</view>
<!-- 无规格提示 -->
<view wx:if="{{!loading && !error && specifications.length === 0 && productName}}" class="empty-state">
<view class="empty-icon">📋</view>
<text class="empty-text">该商品暂无可用规格</text>
<button bindtap="goBackToProductList" class="btn-secondary">返回商品列表</button>
</view>
</view>
</view>

857
pages/evaluate2/one.wxss

@ -1,857 +0,0 @@
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}
/* 步骤指示器 */
.step-indicator {
display: flex;
align-items: center;
justify-content: space-between;
padding: 32rpx;
background: #FFFFFF;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
margin-bottom: 24rpx;
width: 100%;
box-sizing: border-box;
}
.step-item {
display: flex;
flex-direction: column;
align-items: center;
flex: 1;
}
.step-number {
width: 48rpx;
height: 48rpx;
border-radius: 50%;
background: #E5E5E5;
display: flex;
align-items: center;
justify-content: center;
font-size: 24rpx;
font-weight: 600;
color: #999;
margin-bottom: 8rpx;
transition: all 0.3s ease;
}
.step-text {
font-size: 20rpx;
color: #999;
transition: all 0.3s ease;
}
.step-item.active .step-number {
background: #007AFF;
color: #FFFFFF;
box-shadow: 0 0 0 8rpx rgba(0,122,255,0.1);
}
.step-item.active .step-text {
color: #007AFF;
font-weight: 500;
}
.step-line {
flex: 1;
height: 2rpx;
background: #E5E5E5;
margin: 0 16rpx;
transition: all 0.3s ease;
}
.step-line.active {
background: #007AFF;
}
.header {
background: #FFFFFF;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
position: sticky;
top: 0;
z-index: 10;
width: 100%;
box-sizing: border-box;
}
.header-content {
padding: 24rpx 32rpx;
text-align: center;
width: 100%;
box-sizing: border-box;
height: 100rpx;
display: flex;
align-items: center;
justify-content: center;
max-width: 100%;
}
.title {
font-size: 36rpx;
font-weight: 700;
color: #2c3e50;
letter-spacing: 2rpx;
margin: 0;
padding: 0;
}
.content {
flex: 1;
padding: 32rpx;
width: 100%;
box-sizing: border-box;
overflow-x: hidden;
}
/* 加载状态 */
.loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.9);
z-index: 9999;
width: 100%;
box-sizing: border-box;
}
.loading-spinner {
width: 80rpx;
height: 80rpx;
border: 8rpx solid rgba(74, 144, 226, 0.2);
border-top: 8rpx solid #4a90e2;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 32rpx;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading-text {
font-size: 28rpx;
color: #666;
font-weight: 500;
}
/* 错误提示卡片 */
.error-card {
background: #fff;
border-radius: 16rpx;
padding: 48rpx;
margin: 32rpx 0;
box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.08);
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
width: 100%;
box-sizing: border-box;
}
.error-icon {
font-size: 80rpx;
margin-bottom: 24rpx;
}
.error-text {
font-size: 28rpx;
color: #e74c3c;
margin-bottom: 32rpx;
line-height: 1.5;
}
/* 按钮样式 */
.button-group {
display: flex;
gap: 16rpx;
width: 100%;
box-sizing: border-box;
}
.btn-primary {
flex: 1;
height: 80rpx;
line-height: 80rpx;
font-size: 28rpx;
font-weight: 600;
border-radius: 40rpx;
background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%);
color: #fff;
border: none;
box-shadow: 0 4rpx 12rpx rgba(96, 165, 250, 0.4);
transition: all 0.3s ease;
box-sizing: border-box;
}
.btn-primary:hover {
transform: translateY(-2rpx);
box-shadow: 0 6rpx 16rpx rgba(74, 144, 226, 0.5);
}
.btn-secondary {
flex: 1;
height: 80rpx;
line-height: 80rpx;
font-size: 28rpx;
font-weight: 600;
border-radius: 40rpx;
background: #fff;
color: #4a90e2;
border: 2rpx solid #4a90e2;
transition: all 0.3s ease;
box-sizing: border-box;
}
.btn-back {
display: flex;
align-items: center;
justify-content: center;
padding: 8rpx 24rpx;
font-size: 24rpx;
color: #4a90e2;
background: transparent;
border: 1rpx solid #4a90e2;
border-radius: 20rpx;
transition: all 0.3s ease;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}
.btn-back:hover {
background: rgba(74, 144, 226, 0.1);
transform: translateY(-2rpx);
box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.2);
}
.btn-back-icon {
margin-right: 8rpx;
font-size: 20rpx;
}
.btn-back-text {
font-size: 22rpx;
}
/* 商品信息卡片 */
.product-card {
background: rgba(255, 255, 255, 0.95);
border-radius: 20rpx;
padding: 32rpx;
margin-bottom: 24rpx;
box-shadow: 0 6rpx 20rpx rgba(0,0,0,0.08);
backdrop-filter: blur(8rpx);
border: 1rpx solid rgba(255, 255, 255, 0.3);
}
.product-info-container {
width: 100%;
box-sizing: border-box;
}
.product-info-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16rpx;
width: 100%;
box-sizing: border-box;
}
.product-label {
font-size: 24rpx;
color: #666;
font-weight: 500;
flex: 1;
}
.product-name {
font-size: 32rpx;
font-weight: 700;
color: #2c3e50;
line-height: 1.4;
word-break: break-word;
margin-top: 12rpx;
padding: 12rpx 0;
border-top: 1rpx solid #f1f5f9;
}
/* 规格列表区域 */
.spec-section {
margin-top: 24rpx;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24rpx;
padding: 0 8rpx;
}
.section-title {
font-size: 30rpx;
font-weight: 700;
color: #2c3e50;
padding-left: 16rpx;
border-left: 6rpx solid #4a90e2;
}
.section-count {
font-size: 24rpx;
color: #999;
background: rgba(74, 144, 226, 0.1);
padding: 6rpx 16rpx;
border-radius: 20rpx;
}
/* 规格网格布局 */
.spec-grid {
display: flex;
flex-direction: column;
gap: 16rpx;
margin-top: 16rpx;
}
/* 规格卡片 */
.spec-card {
background: #f5f5f5;
border-radius: 12rpx;
padding: 40rpx 24rpx;
cursor: pointer;
min-height: 120rpx;
display: flex;
align-items: center;
justify-content: center;
}
.spec-info {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.spec-name {
font-size: 30rpx;
font-weight: 500;
color: #333;
line-height: 1.4;
word-break: break-word;
text-align: center;
padding-right: 0;
}
/* 空状态 */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 160rpx 0;
text-align: center;
}
.empty-icon {
font-size: 160rpx;
margin-bottom: 40rpx;
opacity: 0.6;
}
.empty-text {
font-size: 32rpx;
color: #666;
margin-bottom: 48rpx;
line-height: 1.4;
padding: 0 40rpx;
}
/* 响应式设计 */
@media (max-width: 750rpx) {
.content {
padding: 20rpx;
}
.spec-grid {
gap: 16rpx;
}
.product-card {
padding: 28rpx;
}
.spec-card {
padding: 36rpx 20rpx;
min-height: 110rpx;
}
.title {
font-size: 32rpx;
}
.section-title {
font-size: 28rpx;
}
.product-name {
font-size: 28rpx;
}
.button-group {
flex-direction: column;
gap: 12rpx;
}
.btn-primary,
.btn-secondary {
width: 100%;
}
}
/* 小屏幕设备适配 */
@media (max-width: 414rpx) {
.spec-grid {
gap: 12rpx;
}
.spec-card {
padding: 32rpx 16rpx;
min-height: 100rpx;
}
.spec-name {
font-size: 24rpx;
}
}
/* 暂无更多规格提示 */
.no-more {
display: flex;
justify-content: center;
align-items: center;
padding: 48rpx 0;
margin-top: 16rpx;
margin-bottom: 100rpx; /* 添加底部边距,避免被导航栏遮挡 */
}
.no-more-text {
font-size: 24rpx;
color: #999;
background: rgba(0, 0, 0, 0.03);
padding: 12rpx 32rpx;
border-radius: 30rpx;
font-weight: 500;
}
/* 分类选择区域 */
.category-section {
margin-top: 24rpx;
margin-bottom: 40rpx;
width: 100%;
box-sizing: border-box;
}
.category-grid {
display: flex;
flex-direction: column;
margin-top: 16rpx;
width: 100%;
box-sizing: border-box;
}
/* 卡片基础框架 */
.category-card {
background: #ffffff;
border-radius: 20rpx;
padding: 0 32rpx 32rpx;
cursor: pointer;
min-height: 600rpx;
margin-bottom: 32rpx;
transition: all 0.3s ease;
width: 100%;
box-sizing: border-box;
box-shadow: 0 8rpx 16rpx rgba(0,0,0,0.08);
position: relative;
overflow: hidden;
}
.category-card:hover {
transform: translateY(-8rpx);
box-shadow: 0 12rpx 24rpx rgba(0,0,0,0.12);
}
/* 品类专属背景 */
.pink-shell-card {
background: linear-gradient(135deg, #FECDD3 0%, #FDE2E2 100%);
}
.green-shell-card {
background: linear-gradient(135deg, #D1FAE5 0%, #E6F7EE 100%);
}
.brown-shell-card {
background: linear-gradient(135deg, #FEF3C7 0%, #FFF9E6 100%);
}
.free-range-card {
background: linear-gradient(135deg, #FEF3C7 0%, #FFF9E6 100%);
}
/* 标签系统 */
.card-labels {
position: absolute;
top: 20rpx;
left: 20rpx;
right: 20rpx;
display: flex;
justify-content: space-between;
align-items: center;
z-index: 2;
}
.feature-label {
background: rgba(255, 255, 255, 0.9);
padding: 8rpx 16rpx;
border-radius: 20rpx;
display: flex;
align-items: center;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}
.feature-label-text {
font-size: 20rpx;
font-weight: 500;
color: #1E293B;
}
.category-label {
background: rgba(0, 0, 0, 0.7);
padding: 8rpx 16rpx;
border-radius: 20rpx;
display: flex;
align-items: center;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}
.category-label-text {
font-size: 20rpx;
font-weight: 500;
color: #FFFFFF;
}
/* 产品图片区域 */
.product-image-container {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 300rpx;
display: flex;
justify-content: center;
align-items: flex-start;
z-index: 1;
overflow: hidden;
}
.product-image {
width: 100%;
height: 100%;
border-radius: 0;
object-fit: cover;
border: none;
box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.12);
transform: none;
}
/* 文字信息区域 */
.card-content {
width: 100%;
display: flex;
flex-direction: column;
gap: 16rpx;
position: relative;
z-index: 2;
padding-top: 320rpx;
padding-bottom: 20rpx;
}
.product-title {
font-size: 36rpx;
font-weight: 700;
color: #1E293B;
line-height: 48rpx;
text-align: center;
margin-bottom: 8rpx;
}
.product-description {
font-size: 24rpx;
font-weight: 400;
color: #64748B;
line-height: 36rpx;
text-align: center;
margin-bottom: 16rpx;
padding: 0 16rpx;
}
/* 卖点标签 */
.selling-points {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 12rpx;
margin: 16rpx 0 24rpx;
}
.selling-point {
display: flex;
align-items: center;
background: rgba(255, 255, 255, 0.8);
padding: 8rpx 16rpx;
border-radius: 20rpx;
box-shadow: 0 2rpx 4rpx rgba(0,0,0,0.05);
}
.selling-point-icon {
font-size: 20rpx;
margin-right: 8rpx;
}
.selling-point-text {
font-size: 20rpx;
font-weight: 400;
color: #475569;
}
/* 按钮区域 */
.card-footer {
display: flex;
justify-content: center;
align-items: center;
margin-top: 16rpx;
width: 100%;
padding: 0 20rpx;
box-sizing: border-box;
}
.select-button {
background: #4A90E2;
color: #FFFFFF;
border: none;
border-radius: 24rpx;
padding: 12rpx 32rpx;
font-size: 24rpx;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
gap: 8rpx;
box-shadow: 0 4rpx 12rpx rgba(74, 144, 226, 0.3);
transition: all 0.3s ease;
width: 100%;
max-width: 200rpx;
}
.select-button:hover {
background: #3B82F6;
transform: translateY(-2rpx);
box-shadow: 0 6rpx 16rpx rgba(74, 144, 226, 0.4);
}
.select-button-icon {
font-size: 20rpx;
font-weight: 600;
}
.select-button-text {
font-size: 24rpx;
font-weight: 600;
}
/* 响应式设计 */
@media (max-width: 750rpx) {
.category-card {
padding: 0 24rpx 24rpx;
min-height: 550rpx;
margin-bottom: 24rpx;
}
.product-image-container {
height: 280rpx;
}
.card-content {
padding-top: 300rpx;
}
.product-title {
font-size: 32rpx;
line-height: 40rpx;
}
.product-description {
font-size: 22rpx;
line-height: 32rpx;
}
.selling-point {
padding: 6rpx 12rpx;
}
.selling-point-text {
font-size: 18rpx;
}
.select-button {
padding: 10rpx 28rpx;
font-size: 22rpx;
}
}
@media (max-width: 414rpx) {
.category-card {
padding: 0 20rpx 20rpx;
min-height: 500rpx;
margin-bottom: 20rpx;
}
.product-image-container {
height: 240rpx;
}
.card-content {
padding-top: 260rpx;
}
.product-title {
font-size: 28rpx;
line-height: 36rpx;
}
.product-description {
font-size: 20rpx;
line-height: 28rpx;
}
.selling-point {
padding: 4rpx 10rpx;
}
.selling-point-text {
font-size: 16rpx;
}
.select-button {
padding: 8rpx 24rpx;
font-size: 20rpx;
}
}
/* 调整规格网格布局,确保不被导航栏遮挡 */
.spec-section {
margin-bottom: 40rpx;
}
/* 登录弹窗样式 */
.auth-modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 9999;
}
.auth-modal-container {
background: rgba(255, 255, 255, 0.95);
border-radius: 20rpx;
padding: 48rpx;
width: 80%;
max-width: 500rpx;
box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.2);
backdrop-filter: blur(12rpx);
border: 1rpx solid rgba(255, 255, 255, 0.3);
}
.auth-modal-title {
font-size: 36rpx;
font-weight: 700;
text-align: center;
margin-bottom: 24rpx;
color: #2c3e50;
letter-spacing: 2rpx;
}
.auth-modal-content {
font-size: 28rpx;
text-align: center;
margin-bottom: 48rpx;
color: #666;
line-height: 1.5;
padding: 0 20rpx;
}
.auth-modal-buttons {
display: flex;
flex-direction: column;
gap: 24rpx;
}
.auth-primary-button {
background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%);
color: white;
border: none;
border-radius: 12rpx;
padding: 24rpx;
font-size: 30rpx;
font-weight: 700;
min-height: 88rpx;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 4rpx 16rpx rgba(96, 165, 250, 0.4);
transition: all 0.3s ease;
}
.auth-primary-button:hover {
transform: translateY(-2rpx);
box-shadow: 0 8rpx 24rpx rgba(96, 165, 250, 0.6);
}
.auth-cancel-button {
background: rgba(255, 255, 255, 0.9);
color: #2c3e50;
border: 2rpx solid #e2e8f0;
border-radius: 12rpx;
padding: 24rpx;
font-size: 28rpx;
font-weight: 600;
min-height: 88rpx;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}
.auth-cancel-button:hover {
background: rgba(236, 240, 241, 0.8);
transform: translateY(-2rpx);
box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

526
pages/evaluate2/product-list.js

@ -1,526 +0,0 @@
Page({
data: {
productNames: [],
loading: false,
error: '',
category: '',
priceRange: { // 价格范围
min: 0,
max: 0,
hasPrice: 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;
},
onLoad(options) {
// 对分类参数进行 URL 解码
const category = options.category ? decodeURIComponent(options.category) : '';
this.setData({ category: category });
console.log('解码后的分类:', category);
this.loadProductNames();
},
loadProductNames() {
this.setData({
loading: true,
error: '',
productNames: [] // 清空商品名称数据,确保加载时只显示加载状态
});
console.log('开始加载商品列表,当前分类:', this.data.category);
// 尝试从本地存储中获取分类商品映射数据
const categoryProductsMap = wx.getStorageSync('evaluate2CategoryProductsMap') || {};
if (categoryProductsMap && Object.keys(categoryProductsMap).length > 0) {
console.log('从本地存储获取分类商品映射数据');
// 获取当前分类下的商品名称列表
let productNames = [];
if (this.data.category) {
productNames = categoryProductsMap[this.data.category] || [];
console.log(`分类"${this.data.category}"下的商品数量:`, productNames.length);
console.log('商品名称列表:', productNames);
} else {
// 如果没有分类参数,获取所有商品名称
const allProductNames = [];
Object.values(categoryProductsMap).forEach(names => {
allProductNames.push(...names);
});
// 去重
productNames = [...new Set(allProductNames)];
console.log('所有商品数量:', productNames.length);
}
// 计算价格范围
let priceRange = { min: 0, max: 0, hasPrice: false };
// 从原始商品数据中计算价格范围
const allProducts = wx.getStorageSync('allProducts') || [];
console.log('本地存储中的商品总数:', allProducts.length);
console.log('当前分类:', this.data.category);
if (allProducts.length > 0) {
// 过滤出当前分类下的商品
const categoryProducts = allProducts.filter(product => {
if (!product.category) return false;
const productCategory = String(product.category).trim();
return productCategory === this.data.category;
});
console.log('当前分类下的商品数量:', categoryProducts.length);
console.log('当前分类下的商品详情:', categoryProducts);
// 按规格分组计算平均价格
const specPriceMap = {};
categoryProducts.forEach(product => {
console.log('处理商品:', product.productName || product.name, '价格:', product.price, '规格:', product.specification || product.spec);
if (product.price && (product.specification || product.spec)) {
const priceStr = String(product.price).trim();
const specStr = String(product.specification || product.spec).trim();
console.log('商品价格字符串:', priceStr, '规格字符串:', specStr);
// 处理逗号分隔的多个价格
const priceArray = priceStr.split(',').map(p => p.trim()).filter(p => p && p.trim() !== '');
console.log('处理后的价格数组:', priceArray);
// 处理逗号分隔的多个规格
let specs = specStr.split(',').map(spec => spec.trim()).filter(spec => spec.length > 0);
console.log('处理后的规格数组:', specs);
// 进一步处理规格,确保每个规格都是独立的
const processedSpecs = [];
specs.forEach(spec => {
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;
console.log('最终规格数组:', specs);
// 将规格和价格配对
specs.forEach((spec, index) => {
console.log('处理规格:', spec, '对应价格索引:', index);
if (spec.length > 0 && index < priceArray.length) {
const price = priceArray[index];
if (price && price.trim() !== '') {
const priceValue = parseFloat(price);
if (!isNaN(priceValue)) {
// 解析规格
const specInfo = this.parseSpecification(spec);
console.log('解析规格结果:', specInfo);
// 价格<10的需要按照公式计算
let finalPrice = priceValue;
if (priceValue < 10 && specInfo) {
if (specInfo.type === '净重') {
// 净重:规格平均值 × 价格
finalPrice = specInfo.avg * priceValue;
} else if (specInfo.type === '毛重') {
// 毛重:(规格平均值 - 5) × 价格
finalPrice = (specInfo.avg - 5) * priceValue;
}
console.log('价格计算:', priceValue, '->', finalPrice);
}
// 按规格分组存储价格
if (!specPriceMap[spec]) {
specPriceMap[spec] = [];
}
specPriceMap[spec].push(finalPrice);
console.log('存储价格:', finalPrice, '到规格:', spec);
} else {
console.log('价格解析失败:', price);
}
} else {
console.log('价格为空或无效:', price);
}
} else {
console.log('规格长度为0或价格索引超出范围:', spec.length, index, priceArray.length);
}
});
} else {
console.log('商品缺少价格或规格:', !product.price ? '无价格' : '', !product.specification && !product.spec ? '无规格' : '');
}
});
// 计算每个规格的平均价格,然后找出最低和最高
const specAvgPrices = [];
Object.keys(specPriceMap).forEach(spec => {
const prices = specPriceMap[spec];
if (prices.length > 0) {
const avgPrice = prices.reduce((sum, price) => sum + price, 0) / prices.length;
specAvgPrices.push(avgPrice);
}
});
if (specAvgPrices.length > 0) {
priceRange.min = Math.round(Math.min(...specAvgPrices) * 100) / 100;
priceRange.max = Math.round(Math.max(...specAvgPrices) * 100) / 100;
priceRange.hasPrice = true;
}
}
this.setData({
productNames: productNames,
priceRange: priceRange,
loading: false
});
// 结束下拉刷新
wx.stopPullDownRefresh();
} else {
// 如果本地存储中没有数据,尝试从本地存储获取原始商品数据
const allProducts = wx.getStorageSync('allProducts') || [];
if (allProducts.length > 0) {
console.log('从本地存储获取原始商品数据');
// 过滤出有有效category字段的商品
const productsWithCategory = allProducts.filter(product => {
if (!product.category) return false;
const categoryStr = String(product.category).trim();
return categoryStr !== '';
});
// 移除价格过滤,获取所有商品
let filteredProducts = productsWithCategory;
// 如果有分类参数,过滤出该分类下的商品
if (this.data.category) {
console.log('当前分类:', this.data.category);
const targetCategory = String(this.data.category).trim();
filteredProducts = filteredProducts.filter(product => {
if (!product.category) return false;
const productCategory = String(product.category).trim();
return productCategory === targetCategory;
});
}
// 提取商品名称,支持多种字段
const productNames = filteredProducts.map(product => {
// 尝试从多个字段获取商品名称
const nameFields = [product.productName, product.name, product.product];
for (const field of nameFields) {
if (field) {
const trimmedName = String(field).trim();
if (trimmedName !== '') {
return trimmedName;
}
}
}
return '';
}).filter(name => name !== '');
// 去重
const uniqueProductNames = [...new Set(productNames)];
console.log('最终商品名称列表:', uniqueProductNames);
// 计算价格范围
let priceRange = { min: 0, max: 0, hasPrice: false };
// 从过滤后的商品中计算价格范围,按规格分组计算平均价格
const specPriceMap = {};
filteredProducts.forEach(product => {
if (product.price && (product.specification || product.spec)) {
const priceStr = String(product.price).trim();
const specStr = String(product.specification || product.spec).trim();
// 处理逗号分隔的多个价格
const priceArray = priceStr.split(',').map(p => p.trim()).filter(p => p && p.trim() !== '');
// 处理逗号分隔的多个规格
let specs = specStr.split(',').map(spec => spec.trim()).filter(spec => spec.length > 0);
// 进一步处理规格,确保每个规格都是独立的
const processedSpecs = [];
specs.forEach(spec => {
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;
// 将规格和价格配对
specs.forEach((spec, index) => {
if (spec.length > 0 && index < priceArray.length) {
const price = priceArray[index];
if (price && price.trim() !== '') {
const priceValue = parseFloat(price);
if (!isNaN(priceValue)) {
// 解析规格
const specInfo = this.parseSpecification(spec);
// 价格<10的需要按照公式计算
let finalPrice = priceValue;
if (priceValue < 10 && specInfo) {
if (specInfo.type === '净重') {
// 净重:规格平均值 × 价格
finalPrice = specInfo.avg * priceValue;
} else if (specInfo.type === '毛重') {
// 毛重:(规格平均值 - 5) × 价格
finalPrice = (specInfo.avg - 5) * priceValue;
}
}
// 按规格分组存储价格
if (!specPriceMap[spec]) {
specPriceMap[spec] = [];
}
specPriceMap[spec].push(finalPrice);
}
}
}
});
}
});
// 计算每个规格的平均价格,然后找出最低和最高
const specAvgPrices = [];
Object.keys(specPriceMap).forEach(spec => {
const prices = specPriceMap[spec];
if (prices.length > 0) {
const avgPrice = prices.reduce((sum, price) => sum + price, 0) / prices.length;
specAvgPrices.push(avgPrice);
}
});
if (specAvgPrices.length > 0) {
priceRange.min = Math.round(Math.min(...specAvgPrices) * 100) / 100;
priceRange.max = Math.round(Math.max(...specAvgPrices) * 100) / 100;
priceRange.hasPrice = true;
}
this.setData({
productNames: uniqueProductNames,
priceRange: priceRange,
loading: false
});
// 结束下拉刷新
wx.stopPullDownRefresh();
} else {
// 如果本地存储中也没有原始商品数据,调用API获取数据
console.log('本地存储中没有数据,调用API获取商品数据...');
const api = require('../../utils/api');
// 使用正确的参数调用getProducts方法
api.getProducts(1, 1000, 'all', '').then(result => {
console.log('API返回结果:', result);
// 从返回对象中提取products数组,如果不存在则使用空数组
const products = result.products || [];
// 过滤出有有效category字段的商品
const productsWithCategory = products.filter(product => {
if (!product.category) return false;
const categoryStr = String(product.category).trim();
return categoryStr !== '';
});
// 移除价格过滤,获取所有商品
let filteredProducts = productsWithCategory;
// 如果有分类参数,过滤出该分类下的商品
if (this.data.category) {
console.log('当前分类:', this.data.category);
const targetCategory = String(this.data.category).trim();
filteredProducts = filteredProducts.filter(product => {
if (!product.category) return false;
const productCategory = String(product.category).trim();
return productCategory === targetCategory;
});
}
// 提取商品名称,支持多种字段
const productNames = filteredProducts.map(product => {
// 尝试从多个字段获取商品名称
const nameFields = [product.productName, product.name, product.product];
for (const field of nameFields) {
if (field) {
const trimmedName = String(field).trim();
if (trimmedName !== '') {
return trimmedName;
}
}
}
return '';
}).filter(name => name !== '');
// 去重
const uniqueProductNames = [...new Set(productNames)];
console.log('最终商品名称列表:', uniqueProductNames);
// 计算价格范围
let priceRange = { min: 0, max: 0, hasPrice: false };
// 从过滤后的商品中计算价格范围,按规格分组计算平均价格
const specPriceMap = {};
filteredProducts.forEach(product => {
if (product.price && (product.specification || product.spec)) {
const priceStr = String(product.price).trim();
const specStr = String(product.specification || product.spec).trim();
// 处理逗号分隔的多个价格
const priceArray = priceStr.split(',').map(p => p.trim()).filter(p => p && p.trim() !== '');
// 处理逗号分隔的多个规格
let specs = specStr.split(',').map(spec => spec.trim()).filter(spec => spec.length > 0);
// 进一步处理规格,确保每个规格都是独立的
const processedSpecs = [];
specs.forEach(spec => {
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;
// 将规格和价格配对
specs.forEach((spec, index) => {
if (spec.length > 0 && index < priceArray.length) {
const price = priceArray[index];
if (price && price.trim() !== '') {
const priceValue = parseFloat(price);
if (!isNaN(priceValue)) {
// 解析规格
const specInfo = this.parseSpecification(spec);
// 价格<10的需要按照公式计算
let finalPrice = priceValue;
if (priceValue < 10 && specInfo) {
if (specInfo.type === '净重') {
// 净重:规格平均值 × 价格
finalPrice = specInfo.avg * priceValue;
} else if (specInfo.type === '毛重') {
// 毛重:(规格平均值 - 5) × 价格
finalPrice = (specInfo.avg - 5) * priceValue;
}
}
// 按规格分组存储价格
if (!specPriceMap[spec]) {
specPriceMap[spec] = [];
}
specPriceMap[spec].push(finalPrice);
}
}
}
});
}
});
// 计算每个规格的平均价格,然后找出最低和最高
const specAvgPrices = [];
Object.keys(specPriceMap).forEach(spec => {
const prices = specPriceMap[spec];
if (prices.length > 0) {
const avgPrice = prices.reduce((sum, price) => sum + price, 0) / prices.length;
specAvgPrices.push(avgPrice);
}
});
if (specAvgPrices.length > 0) {
priceRange.min = Math.round(Math.min(...specAvgPrices) * 100) / 100;
priceRange.max = Math.round(Math.max(...specAvgPrices) * 100) / 100;
priceRange.hasPrice = true;
}
this.setData({
productNames: uniqueProductNames,
priceRange: priceRange,
loading: false
});
// 结束下拉刷新
wx.stopPullDownRefresh();
}).catch(err => {
console.error('获取商品列表失败:', err);
this.setData({
error: '获取商品列表失败,请稍后重试',
loading: false
});
// 结束下拉刷新
wx.stopPullDownRefresh();
});
}
}
},
selectProduct(e) {
const productName = e.currentTarget.dataset.product;
console.log('选择商品:', productName);
// 将商品名称和当前分类存储到本地存储
wx.setStorageSync('selectedProductName', productName);
wx.setStorageSync('selectedCategory', this.data.category); // 存储当前分类
// 使用wx.switchTab导航到tabBar页面
wx.switchTab({
url: '/pages/evaluate2/index',
success: function(res) {
console.log('跳转成功:', res);
},
fail: function(err) {
console.error('跳转失败:', err);
}
});
},
// 返回分类选择页面
goBackToCategories() {
console.log('返回分类选择页面');
wx.redirectTo({
url: '/pages/evaluate2/one'
});
},
// 下拉刷新
onPullDownRefresh() {
console.log('开始下拉刷新');
this.loadProductNames();
},
// 分享配置
onShareAppMessage() {
return {
title: '专业的估价平台,专为估蛋而生',
imageUrl: 'https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BD%97%E6%9B%BC%E7%81%B0/image/c00cbcbfd12d747b44621701aed2ae02.jpeg',
path: '/pages/evaluate2/product-list'
};
},
// 朋友圈分享配置
onShareTimeline() {
return {
title: '专业的估价平台,专为估蛋而生',
imageUrl: 'https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BD%97%E6%9B%BC%E7%81%B0/image/c00cbcbfd12d747b44621701aed2ae02.jpeg',
query: ''
};
}
});

6
pages/evaluate2/product-list.json

@ -1,6 +0,0 @@
{
"usingComponents": {},
"enablePullDownRefresh": true,
"backgroundTextStyle": "dark",
"disableSwipeBack": true
}

97
pages/evaluate2/product-list.wxml

@ -1,97 +0,0 @@
<view class="container">
<!-- 步骤指示器 -->
<view class="step-indicator">
<view class="step-item active">
<view class="step-number">1</view>
<text class="step-text">选择品种</text>
</view>
<view class="step-line active"></view>
<view class="step-item active">
<view class="step-number">2</view>
<text class="step-text">选择产品</text>
</view>
<view class="step-line"></view>
<view class="step-item">
<view class="step-number">3</view>
<text class="step-text">选择规格</text>
</view>
<view class="step-line"></view>
<view class="step-item">
<view class="step-number">4</view>
<text class="step-text">查看估价</text>
</view>
</view>
<!-- 头部导航栏 -->
<view class="header">
<view class="header-content">
<button class="back-button" bindtap="goBackToCategories">
<text class="back-icon" style="width: 75rpx; display: block; box-sizing: border-box; position: relative; left: -162rpx; top: 2rpx">←</text>
</button>
<text class="title">商品选择</text>
<view class="header-right"></view> <!-- 占位,保持标题居中 -->
</view>
</view>
<view class="content">
<!-- 加载中状态 -->
<view wx:if="{{loading}}" class="loading">
<view class="loading-spinner"></view>
<text class="loading-text">正在加载商品数据...</text>
</view>
<!-- 非加载状态 -->
<view wx:else>
<!-- 错误提示 -->
<view wx:if="{{error}}" class="error-card">
<view class="error-icon">⚠️</view>
<text class="error-text">{{error}}</text>
<button bindtap="loadProductNames" class="btn-primary">重新加载</button>
</view>
<!-- 商品名称列表 -->
<view wx:else class="product-section">
<view class="section-header">
<text class="section-title">{{category}}系列的商品列表</text>
<view class="section-count">{{productNames.length}}个商品</view>
</view>
<view class="section-divider"></view>
<!-- 有商品时显示网格 -->
<view wx:if="{{productNames.length > 0}}" class="product-grid">
<view
wx:for="{{productNames}}"
wx:key="*this"
class="product-card"
data-product="{{item}}"
bindtap="selectProduct"
>
<view class="product-image-container">
<image
src="../../images/OIP-C.png"
mode="aspectFill"
class="product-image"
/>
</view>
<text class="product-name">{{item}}</text>
</view>
</view>
<!-- 无商品时显示空状态 -->
<view wx:if="{{productNames.length === 0}}" class="empty-state">
<view class="empty-icon">📦</view>
<text class="empty-text">
{{category ? '该分类下暂无商品' : '暂无商品'}}
</text>
<text class="empty-subtext">试试其他分类吧</text>
<button bindtap="loadProductNames" class="btn-secondary">刷新</button>
</view>
<!-- 暂无更多商品提示 -->
<view wx:if="{{productNames.length > 0}}" class="no-more">
<text class="no-more-text">已经到底啦</text>
</view>
</view>
</view>
</view>
</view>

608
pages/evaluate2/product-list.wxss

@ -1,608 +0,0 @@
.container {
display: flex;
flex-direction: column;
min-height: 100vh;
background: linear-gradient(135deg, #F9FAFB 0%, #F2F4F8 100%);
font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
overflow-x: hidden;
width: 100%;
box-sizing: border-box;
}
/* 步骤指示器 */
.step-indicator {
display: flex;
align-items: center;
justify-content: space-between;
padding: 32rpx;
background: #FFFFFF;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
margin-bottom: 24rpx;
width: 100%;
box-sizing: border-box;
}
.step-item {
display: flex;
flex-direction: column;
align-items: center;
flex: 1;
}
.step-number {
width: 48rpx;
height: 48rpx;
border-radius: 50%;
background: #E5E5E5;
display: flex;
align-items: center;
justify-content: center;
font-size: 24rpx;
font-weight: 600;
color: #999;
margin-bottom: 8rpx;
transition: all 0.3s ease;
}
.step-text {
font-size: 20rpx;
color: #999;
transition: all 0.3s ease;
}
.step-item.active .step-number {
background: #007AFF;
color: #FFFFFF;
box-shadow: 0 0 0 8rpx rgba(0,122,255,0.1);
}
.step-item.active .step-text {
color: #007AFF;
font-weight: 500;
}
.step-line {
flex: 1;
height: 2rpx;
background: #E5E5E5;
margin: 0 16rpx;
transition: all 0.3s ease;
}
.step-line.active {
background: #007AFF;
}
.header {
background: #FFFFFF;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
position: sticky;
top: 0;
z-index: 10;
width: 100%;
box-sizing: border-box;
}
.header-content {
display: flex;
align-items: center;
padding: 24rpx 32rpx;
width: 100%;
box-sizing: border-box;
height: 100rpx;
max-width: 100%;
}
.title {
font-size: 36rpx;
font-weight: 700;
color: #2c3e50;
letter-spacing: 2rpx;
text-align: center;
margin: 0;
padding: 0;
flex: 1;
position: absolute;
left: 50%;
transform: translateX(-50%);
width: 100%;
max-width: 300rpx;
}
.header-content {
position: relative;
}
/* 返回按钮样式 */
.back-button {
width: 100rpx;
height: 60rpx;
line-height: 60rpx;
font-size: 36rpx;
color: #4a90e2;
background: transparent;
border: none;
padding: 0 16rpx 0 0;
margin: 0;
display: flex;
align-items: center;
justify-content: flex-start;
border-radius: 8rpx;
transition: all 0.3s ease;
flex-shrink: 0;
overflow: visible;
}
.back-button:hover {
color: #3b82f6;
background: rgba(74, 144, 226, 0.1);
}
.back-icon {
margin-right: 8rpx;
font-size: 36rpx;
font-weight: 600;
transition: all 0.3s ease;
display: inline-block;
}
.back-button:hover .back-icon {
transform: translateX(-12rpx);
font-weight: 700;
}
.back-text {
font-size: 36rpx;
font-weight: 700;
}
.title {
font-size: 36rpx;
font-weight: 700;
color: #2c3e50;
letter-spacing: 2rpx;
flex: 1;
text-align: center;
margin: 0;
padding: 0;
}
.header-right {
width: 60rpx;
flex-shrink: 0;
}
.content {
flex: 1;
padding: 32rpx;
width: 100%;
box-sizing: border-box;
overflow-x: hidden;
}
/* 加载状态 */
.loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.9);
z-index: 9999;
width: 100%;
box-sizing: border-box;
}
.loading-spinner {
width: 80rpx;
height: 80rpx;
border: 8rpx solid rgba(74, 144, 226, 0.2);
border-top: 8rpx solid #4a90e2;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 32rpx;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading-text {
font-size: 28rpx;
color: #666;
font-weight: 500;
}
/* 错误提示卡片 */
.error-card {
background: #fff;
border-radius: 16rpx;
padding: 48rpx;
margin: 32rpx 0;
box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.08);
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
width: 100%;
box-sizing: border-box;
}
.error-icon {
font-size: 80rpx;
margin-bottom: 24rpx;
}
.error-text {
font-size: 28rpx;
color: #e74c3c;
margin-bottom: 32rpx;
line-height: 1.5;
}
/* 按钮样式 */
.btn-primary {
width: 240rpx;
height: 80rpx;
line-height: 80rpx;
font-size: 28rpx;
font-weight: 600;
border-radius: 40rpx;
background: linear-gradient(135deg, #60a5fa 0%, #3b82f6 100%);
color: #fff;
border: none;
box-shadow: 0 4rpx 12rpx rgba(96, 165, 250, 0.4);
transition: all 0.3s ease;
box-sizing: border-box;
}
.btn-primary:hover {
transform: translateY(-2rpx);
box-shadow: 0 6rpx 16rpx rgba(74, 144, 226, 0.5);
}
/* 商品列表区域 */
.product-section {
margin-top: 24rpx;
width: 100%;
box-sizing: border-box;
}
/* 当前选择的分类 */
.current-category {
display: flex;
flex-direction: column;
background: #F8F9FA;
padding: 24rpx 32rpx;
border-radius: 16rpx;
margin-bottom: 32rpx;
width: 100%;
box-sizing: border-box;
}
.current-category-content {
display: flex;
align-items: center;
margin-bottom: 8rpx;
width: 100%;
box-sizing: border-box;
}
.current-category-name {
font-size: 36rpx;
font-weight: 600;
color: #333;
width: 100%;
box-sizing: border-box;
}
/* 价格范围 */
.price-range {
display: flex;
align-items: center;
width: 100%;
box-sizing: border-box;
}
.price-range-value {
font-size: 28rpx;
color: #666;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24rpx;
padding: 0;
width: 100%;
box-sizing: border-box;
}
.section-title {
font-size: 32rpx;
font-weight: 600;
color: #2c3e50;
padding-left: 0;
border-left: none;
}
.section-count {
font-size: 28rpx;
color: #999;
background: #F0F0F0;
padding: 8rpx 16rpx;
border-radius: 24rpx;
}
.section-divider {
height: 1rpx;
background: #EDEDED;
margin-bottom: 24rpx;
width: 100%;
box-sizing: border-box;
}
/* 商品网格布局 */
.product-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 24rpx;
margin-top: 0;
width: 100%;
box-sizing: border-box;
overflow-x: hidden;
}
/* 商品卡片 */
.product-card {
background: #FFFFFF;
border-radius: 16rpx;
padding: 16rpx;
cursor: pointer;
min-height: 240rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
width: 100%;
box-sizing: border-box;
box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.04);
transition: all 0.3s ease;
}
.product-image-container {
width: 100%;
height: 160rpx;
margin-bottom: 16rpx;
border-radius: 12rpx;
overflow: hidden;
background: #F5F5F5;
}
.product-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.product-card:hover {
box-shadow: 0 8rpx 20rpx rgba(0,0,0,0.08);
transform: translateY(-2rpx);
}
.product-name {
font-size: 28rpx;
font-weight: 500;
color: #333;
line-height: 1.4;
word-break: break-word;
text-align: center;
padding: 0 8rpx;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
/* 响应式设计 */
@media (max-width: 750rpx) {
.content {
padding: 24rpx;
}
.product-grid {
gap: 20rpx;
}
.product-card {
padding: 16rpx;
min-height: 220rpx;
}
.product-image-container {
height: 140rpx;
}
.title {
font-size: 32rpx;
}
.section-title {
font-size: 28rpx;
}
.product-name {
font-size: 26rpx;
}
.current-category {
padding: 20rpx 24rpx;
}
.current-category-name {
font-size: 32rpx;
}
.price-range-value {
font-size: 24rpx;
}
}
/* 小屏幕设备适配 */
@media (max-width: 414rpx) {
.content {
padding: 24rpx;
}
.product-grid {
gap: 20rpx;
}
.product-card {
padding: 16rpx;
min-height: 200rpx;
}
.product-image-container {
height: 120rpx;
}
.product-name {
font-size: 24rpx;
}
.title {
font-size: 32rpx;
}
.section-title {
font-size: 28rpx;
}
.current-category {
padding: 16rpx 20rpx;
}
.current-category-name {
font-size: 28rpx;
}
.price-range-value {
font-size: 22rpx;
}
}
/* 大屏幕适配 */
@media (min-width: 900px) {
.product-grid {
grid-template-columns: repeat(4, 1fr);
max-width: 1200rpx;
margin: 0 auto;
}
.current-category {
max-width: 1200rpx;
margin: 0 auto 32rpx;
}
.section-header {
max-width: 1200rpx;
margin: 0 auto 24rpx;
}
.section-divider {
max-width: 1200rpx;
margin: 0 auto 24rpx;
}
}
/* 平板适配 */
@media (min-width: 600px) and (max-width: 899px) {
.product-grid {
grid-template-columns: repeat(3, 1fr);
}
}
/* 暂无更多商品提示 */
.no-more {
display: flex;
align-items: center;
justify-content: center;
padding: 48rpx 0;
margin-top: 24rpx;
}
.no-more::before,
.no-more::after {
content: '';
flex: 1;
height: 1rpx;
background: #E5E5E5;
margin: 0 16rpx;
}
.no-more-text {
font-size: 24rpx;
color: #BBB;
font-weight: 500;
white-space: nowrap;
}
/* 空状态 */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 120rpx 0;
text-align: center;
}
.empty-icon {
font-size: 120rpx;
margin-bottom: 40rpx;
opacity: 0.6;
color: #CCC;
}
.empty-text {
font-size: 32rpx;
font-weight: 600;
color: #333;
margin-bottom: 16rpx;
line-height: 1.4;
padding: 0 40rpx;
}
.empty-subtext {
font-size: 28rpx;
color: #999;
margin-bottom: 48rpx;
line-height: 1.4;
padding: 0 40rpx;
}
.btn-secondary {
width: 200rpx;
height: 80rpx;
line-height: 80rpx;
font-size: 32rpx;
font-weight: 600;
border-radius: 48rpx;
background: #fff;
color: #4a90e2;
border: 1rpx solid #4a90e2;
transition: all 0.3s ease;
padding: 0 48rpx;
}
.btn-secondary:hover {
background: rgba(74, 144, 226, 0.05);
transform: translateY(-2rpx);
}

125
pages/evaluate2/spec-detail.js

@ -1,125 +0,0 @@
Page({
data: {
productName: '',
category: '',
specification: '',
price: 0,
quantity: 1,
totalPrice: 0,
loading: false,
error: ''
},
onLoad(options) {
console.log('接收到的参数:', options);
// 即使参数不完整,也要尝试获取并设置
const productName = options.productName ? decodeURIComponent(options.productName) : '';
const category = options.category ? decodeURIComponent(options.category) : '';
const specification = options.specification ? decodeURIComponent(options.specification) : '';
let price = 0;
if (options.price) {
const decodedPrice = decodeURIComponent(options.price);
console.log('解码后的价格:', decodedPrice);
price = parseFloat(decodedPrice) || 0;
}
console.log('解析后的参数:', { productName, category, specification, price });
this.setData({
productName: productName,
category: category,
specification: specification,
price: price,
totalPrice: 0 // 初始时总价为0,不显示
});
},
// 件数输入变化
onQuantityChange(e) {
const quantity = parseInt(e.detail.value) || 1;
this.setData({
quantity: quantity
// 只更新件数,不更新总价,等待点击计算按钮
});
},
// 减少数量
decreaseQuantity() {
if (this.data.quantity > 1) {
this.setData({
quantity: this.data.quantity - 1
});
}
},
// 增加数量
increaseQuantity() {
this.setData({
quantity: this.data.quantity + 1
});
},
// 计算价格
calculatePrice() {
const totalPrice = Math.round(this.data.price * this.data.quantity * 10) / 10;
this.setData({
totalPrice: totalPrice
});
wx.showToast({
title: '计算完成',
icon: 'success',
duration: 1000
});
},
// 返回上一页
goBack() {
wx.navigateBack();
},
// 下拉刷新
onPullDownRefresh() {
console.log('开始下拉刷新');
// 重新加载页面数据
// 由于spec-detail页面的数据是通过URL参数传递的,这里可以重新获取参数并设置数据
const options = this.options || {};
const productName = options.productName ? decodeURIComponent(options.productName) : '';
const category = options.category ? decodeURIComponent(options.category) : '';
const specification = options.specification ? decodeURIComponent(options.specification) : '';
let price = 0;
if (options.price) {
const decodedPrice = decodeURIComponent(options.price);
price = parseFloat(decodedPrice) || 0;
}
this.setData({
productName: productName,
category: category,
specification: specification,
price: price,
totalPrice: 0 // 初始时总价为0,不显示
});
// 结束下拉刷新
wx.stopPullDownRefresh();
},
// 分享配置
onShareAppMessage() {
return {
title: '专业的估价平台,专为估蛋而生',
imageUrl: 'https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BD%97%E6%9B%BC%E7%81%B0/image/c00cbcbfd12d747b44621701aed2ae02.jpeg',
path: '/pages/evaluate2/spec-detail'
};
},
// 朋友圈分享配置
onShareTimeline() {
return {
title: '专业的估价平台,专为估蛋而生',
imageUrl: 'https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BD%97%E6%9B%BC%E7%81%B0/image/c00cbcbfd12d747b44621701aed2ae02.jpeg',
query: ''
};
}
});

5
pages/evaluate2/spec-detail.json

@ -1,5 +0,0 @@
{
"usingComponents": {},
"enablePullDownRefresh": true,
"backgroundTextStyle": "dark"
}

82
pages/evaluate2/spec-detail.wxml

@ -1,82 +0,0 @@
<view class="page-container">
<!-- 步骤指示器 -->
<view class="step-indicator">
<view class="step-item active">
<view class="step-number">1</view>
<text class="step-text">选择品种</text>
</view>
<view class="step-line active"></view>
<view class="step-item active">
<view class="step-number">2</view>
<text class="step-text">选择产品</text>
</view>
<view class="step-line active"></view>
<view class="step-item active">
<view class="step-number">3</view>
<text class="step-text">选择规格</text>
</view>
<view class="step-line active"></view>
<view class="step-item active">
<view class="step-number">4</view>
<text class="step-text">查看估价</text>
</view>
</view>
<!-- 主要内容区域 -->
<view class="main-content">
<!-- 规格信息卡片 -->
<view class="info-card">
<text class="card-subtitle">规格信息</text>
<view class="info-row">
<text class="info-label">分类</text>
<text class="info-value">{{category}}</text>
</view>
<view class="info-row">
<text class="info-label">名称</text>
<text class="info-value">{{productName}}</text>
</view>
<view class="info-row">
<text class="info-label">规格</text>
<text class="info-value">{{specification}}</text>
</view>
<text class="info-hint">您已选择此规格进行估价</text>
</view>
<!-- 数量设置卡片 -->
<view class="control-card">
<text class="card-subtitle">件数设置</text>
<view class="quantity-box">
<button bindtap="decreaseQuantity" class="quantity-btn minus" style="width: 180rpx; display: flex; box-sizing: border-box; left: 0rpx; top: 0rpx">-</button>
<input style="width: 420rpx; display: block; box-sizing: border-box"
class="quantity-input"
type="number"
value="{{quantity}}"
bindinput="onQuantityChange"
min="1"
/>
<button bindtap="increaseQuantity" class="quantity-btn plus" style="width: 180rpx; display: flex; box-sizing: border-box; left: 0rpx; top: 0rpx">+</button>
</view>
</view>
<!-- 计算按钮 -->
<view class="button-section">
<button bindtap="calculatePrice" class="primary-btn" style="height: 120rpx; display: block; box-sizing: border-box; left: 0rpx; top: 0rpx">计算预估价格</button>
</view>
<!-- 结果展示卡片 -->
<view class="result-card" wx:if="{{totalPrice > 0}}">
<text class="card-subtitle">预估结果</text>
<view class="result-row">
<text class="result-label">预估总价</text>
<text class="result-value">¥{{totalPrice}}</text>
</view>
<text class="result-hint">此价格为预估价格,仅供参考,解释权归又鸟蛋平台,实际价格可能会有所变动</text>
</view>
<!-- 返回按钮 -->
<view class="button-section bottom">
<button bindtap="goBack" class="secondary-btn" style="height: 120rpx; display: block; box-sizing: border-box; left: 0rpx; top: 0rpx">返回规格列表</button>
</view>
</view>
</view>

465
pages/evaluate2/spec-detail.wxss

@ -1,465 +0,0 @@
/* 页面容器 */
.page-container {
min-height: 100vh;
background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
/* 步骤指示器 */
.step-indicator {
display: flex;
align-items: center;
justify-content: space-between;
padding: 32rpx;
background: #FFFFFF;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
margin-bottom: 24rpx;
width: 100%;
box-sizing: border-box;
}
.step-item {
display: flex;
flex-direction: column;
align-items: center;
flex: 1;
}
.step-number {
width: 48rpx;
height: 48rpx;
border-radius: 50%;
background: #E5E5E5;
display: flex;
align-items: center;
justify-content: center;
font-size: 24rpx;
font-weight: 600;
color: #999;
margin-bottom: 8rpx;
transition: all 0.3s ease;
}
.step-text {
font-size: 20rpx;
color: #999;
transition: all 0.3s ease;
}
.step-item.active .step-number {
background: #007AFF;
color: #FFFFFF;
box-shadow: 0 0 0 8rpx rgba(0,122,255,0.1);
}
.step-item.active .step-text {
color: #007AFF;
font-weight: 500;
}
.step-line {
flex: 1;
height: 2rpx;
background: #E5E5E5;
margin: 0 16rpx;
transition: all 0.3s ease;
}
.step-line.active {
background: #007AFF;
}
/* 头部样式 */
.page-header {
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(10rpx);
box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
padding: 28rpx 0;
text-align: center;
position: sticky;
top: 0;
z-index: 10;
}
.header-title {
font-size: 30rpx;
font-weight: 700;
color: #2c3e50;
letter-spacing: 1rpx;
}
/* 主要内容区域 */
.main-content {
flex: 1;
padding: 24rpx;
display: flex;
flex-direction: column;
gap: 24rpx;
padding-bottom: 48rpx;
box-sizing: border-box;
}
/* 卡片基础样式 */
.info-card,
.control-card,
.result-card {
background: rgba(255, 255, 255, 0.95);
border-radius: 24rpx;
padding: 32rpx;
box-shadow: 0 6rpx 24rpx rgba(0,0,0,0.08);
backdrop-filter: blur(12rpx);
border: 1rpx solid rgba(255, 255, 255, 0.4);
transition: all 0.3s ease;
box-sizing: border-box;
}
.info-card:hover,
.control-card:hover,
.result-card:hover {
box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.12);
transform: translateY(-4rpx);
background: rgba(255, 255, 255, 0.98);
}
/* 卡片标题 */
.card-subtitle {
font-size: 26rpx;
font-weight: 600;
color: #64748b;
margin-bottom: 24rpx;
padding-bottom: 16rpx;
border-bottom: 1rpx solid #f1f5f9;
}
/* 信息行样式 */
.info-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16rpx 0;
border-bottom: 1rpx solid #f8fafc;
}
.info-row:last-child {
border-bottom: none;
}
.info-label {
font-size: 26rpx;
color: #64748b;
font-weight: 500;
}
.info-value {
font-size: 26rpx;
font-weight: 600;
color: #2c3e50;
}
.info-value.price {
color: #ef4444;
font-size: 32rpx;
font-weight: 700;
}
/* 提示信息 */
.info-hint {
font-size: 22rpx;
color: #94a3b8;
text-align: center;
margin-top: 20rpx;
padding-top: 20rpx;
border-top: 1rpx solid #f1f5f9;
}
/* 数量控制 */
.quantity-box {
display: flex;
align-items: center;
gap: 24rpx;
margin-top: 12rpx;
justify-content: center;
}
.quantity-btn {
width: 80rpx;
height: 80rpx;
border-radius: 40rpx;
font-size: 36rpx;
font-weight: bold;
background: rgba(255, 255, 255, 0.9);
color: #3b82f6;
border: 2rpx solid rgba(96, 165, 250, 0.4);
backdrop-filter: blur(12rpx);
display: flex;
align-items: center;
justify-content: center;
transition: all 0.3s ease;
box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08);
}
.quantity-btn:hover {
background: rgba(59, 130, 246, 0.1);
border-color: rgba(59, 130, 246, 0.6);
transform: scale(1.1);
}
.quantity-btn.minus:hover {
background: rgba(239, 68, 68, 0.1);
border-color: rgba(239, 68, 68, 0.6);
color: #ef4444;
}
.quantity-btn.plus:hover {
background: rgba(16, 185, 129, 0.1);
border-color: rgba(16, 185, 129, 0.6);
color: #10b981;
}
.quantity-input {
width: 160rpx;
height: 80rpx;
border: 2rpx solid rgba(96, 165, 250, 0.4);
border-radius: 16rpx;
padding: 0 24rpx;
font-size: 28rpx;
font-weight: 600;
text-align: center;
color: #2c3e50;
background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(12rpx);
box-shadow: inset 0 2rpx 8rpx rgba(0,0,0,0.08);
box-sizing: border-box;
}
/* 按钮区域 */
.button-section {
margin-top: 12rpx;
}
.button-section.bottom {
margin-top: 20rpx;
}
/* 按钮样式 */
.primary-btn {
width: 100%;
height: 92rpx;
line-height: 92rpx;
font-size: 28rpx;
font-weight: 600;
border-radius: 46rpx;
background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
color: #fff;
border: none;
box-shadow: 0 6rpx 24rpx rgba(59, 130, 246, 0.4);
transition: all 0.3s ease;
text-align: center;
}
.primary-btn:hover {
transform: translateY(-4rpx);
box-shadow: 0 8rpx 32rpx rgba(59, 130, 246, 0.5);
}
.secondary-btn {
width: 100%;
height: 84rpx;
line-height: 84rpx;
font-size: 26rpx;
font-weight: 600;
border-radius: 42rpx;
background: rgba(255, 255, 255, 0.95);
color: #3b82f6;
border: 2rpx solid rgba(59, 130, 246, 0.4);
backdrop-filter: blur(12rpx);
transition: all 0.3s ease;
text-align: center;
box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.08);
}
.secondary-btn:hover {
background: rgba(59, 130, 246, 0.08);
border-color: rgba(59, 130, 246, 0.6);
transform: translateY(-4rpx);
box-shadow: 0 6rpx 24rpx rgba(59, 130, 246, 0.3);
}
/* 结果卡片 */
.result-card {
animation: fadeInUp 0.6s ease-out;
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(30rpx);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* 结果行 */
.result-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 20rpx 0;
}
.result-label {
font-size: 26rpx;
color: #64748b;
font-weight: 500;
}
.result-value {
font-size: 36rpx;
font-weight: 700;
color: #ef4444;
text-shadow: 0 2rpx 4rpx rgba(239, 68, 68, 0.2);
}
/* 结果提示 */
.result-hint {
font-size: 22rpx;
color: #94a3b8;
text-align: center;
margin-top: 16rpx;
padding-top: 16rpx;
border-top: 1rpx solid #f1f5f9;
line-height: 1.5;
}
/* 响应式设计 */
@media (max-width: 750rpx) {
.main-content {
padding: 20rpx;
gap: 20rpx;
}
.info-card,
.control-card,
.result-card {
padding: 28rpx;
}
.header-title {
font-size: 28rpx;
}
.card-subtitle {
font-size: 24rpx;
margin-bottom: 20rpx;
}
.info-label,
.info-value {
font-size: 24rpx;
}
.info-value.price {
font-size: 30rpx;
}
.result-value {
font-size: 32rpx;
}
.quantity-box {
gap: 20rpx;
}
.quantity-btn {
width: 72rpx;
height: 72rpx;
font-size: 32rpx;
}
.quantity-input {
width: 140rpx;
height: 72rpx;
font-size: 26rpx;
}
.primary-btn {
height: 84rpx;
line-height: 84rpx;
font-size: 26rpx;
}
.secondary-btn {
height: 76rpx;
line-height: 76rpx;
font-size: 24rpx;
}
}
/* 小屏幕设备适配 */
@media (max-width: 375rpx) {
.main-content {
padding: 16rpx;
gap: 16rpx;
}
.info-card,
.control-card,
.result-card {
padding: 24rpx;
}
.header-title {
font-size: 26rpx;
}
.card-subtitle {
font-size: 22rpx;
margin-bottom: 16rpx;
}
.info-label,
.info-value {
font-size: 22rpx;
}
.info-value.price {
font-size: 28rpx;
}
.result-value {
font-size: 28rpx;
}
.quantity-box {
gap: 16rpx;
}
.quantity-btn {
width: 64rpx;
height: 64rpx;
font-size: 28rpx;
}
.quantity-input {
width: 120rpx;
height: 64rpx;
font-size: 24rpx;
}
.primary-btn {
height: 76rpx;
line-height: 76rpx;
font-size: 24rpx;
}
.secondary-btn {
height: 68rpx;
line-height: 68rpx;
font-size: 22rpx;
}
}

2009
pages/freight-calculator/index.js

File diff suppressed because it is too large

263
pages/freight-calculator/index.wxml

@ -2,41 +2,30 @@
<view class="container">
<view class="main-content">
<!-- 出发地信息 -->
<view class="section">
<view class="section" wx:if="{{!isFromGoodsDetail}}">
<text class="section-title">出发地</text>
<view class="address-form">
<view class="form-item">
<text class="label">省份</text>
<input class="input" bindinput="bindOriginInput" data-key="province" value="{{origin.province}}" placeholder="请输入省份" />
</view>
<view class="form-item">
<text class="label">城市</text>
<input class="input" bindinput="bindOriginInput" data-key="city" value="{{origin.city}}" placeholder="请输入城市" />
</view>
<view class="form-item">
<text class="label">区县</text>
<input class="input" bindinput="bindOriginInput" data-key="district" value="{{origin.district}}" placeholder="请输入区县" />
<view class="form-item address-row">
<text class="label">省市区</text>
<view class="address-inputs">
<input class="input address-input" bindinput="bindOriginInput" data-key="province" value="{{origin.province}}" placeholder="省份" />
<input class="input address-input" bindinput="bindOriginInput" data-key="city" value="{{origin.city}}" placeholder="城市" />
<input class="input address-input" bindinput="bindOriginInput" data-key="district" value="{{origin.district}}" placeholder="区县" />
</view>
</view>
<view class="form-item">
<text class="label">详细地址</text>
<input class="input" bindinput="bindOriginInput" data-key="detail" value="{{origin.detail}}" placeholder="请输入详细地址" />
</view>
<view class="form-item">
<text class="label">快速选择</text>
<picker
mode="region"
bindchange="bindRegionChange"
data-type="origin"
value="{{[origin.province, origin.city, origin.district]}}"
>
<view class="picker">
{{origin.province && origin.city && origin.district ? origin.province + origin.city + origin.district : '请选择'}}
</view>
</picker>
<view style="display: flex; justify-content: space-between; gap: 12rpx;">
<button class="location-btn" bindtap="useCurrentLocationForOrigin">
<text>使用当前位置</text>
</button>
<button class="location-btn" bindtap="chooseOriginLocation" style="background-color: #1677ff;">
<text>手动选择位置</text>
</button>
</view>
<button class="location-btn" bindtap="chooseOriginLocation" style="background-color: #1677ff;">
<text>手动选择位置</text>
</button>
</view>
</view>
@ -44,35 +33,19 @@
<view class="section">
<text class="section-title">目的地</text>
<view class="address-form">
<view class="form-item">
<text class="label">省份</text>
<input class="input" bindinput="bindDestinationInput" data-key="province" value="{{destination.province}}" placeholder="请输入省份" />
</view>
<view class="form-item">
<text class="label">城市</text>
<input class="input" bindinput="bindDestinationInput" data-key="city" value="{{destination.city}}" placeholder="请输入城市" />
</view>
<view class="form-item">
<text class="label">区县</text>
<input class="input" bindinput="bindDestinationInput" data-key="district" value="{{destination.district}}" placeholder="请输入区县" />
<view class="form-item address-row">
<text class="label">省市区</text>
<view class="address-inputs">
<input class="input address-input" bindinput="bindDestinationInput" data-key="province" value="{{destination.province}}" placeholder="省份" />
<input class="input address-input" bindinput="bindDestinationInput" data-key="city" value="{{destination.city}}" placeholder="城市" />
<input class="input address-input" bindinput="bindDestinationInput" data-key="district" value="{{destination.district}}" placeholder="区县" />
</view>
</view>
<view class="form-item">
<text class="label">详细地址</text>
<input class="input" bindinput="bindDestinationInput" data-key="detail" value="{{destination.detail}}" placeholder="请输入详细地址" />
</view>
<view class="form-item">
<text class="label">快速选择</text>
<picker
mode="region"
bindchange="bindRegionChange"
data-type="destination"
value="{{[destination.province, destination.city, destination.district]}}"
>
<view class="picker">
{{destination.province && destination.city && destination.district ? destination.province + destination.city + destination.district : '请选择'}}
</view>
</picker>
</view>
<view style="display: flex; justify-content: space-between; gap: 12rpx;">
<button class="location-btn" bindtap="useCurrentLocation">
<text>使用当前位置</text>
@ -84,109 +57,126 @@
</view>
</view>
<!-- 物流车辆信息 -->
<!-- 运输参数 -->
<view class="section">
<text class="section-title">物流车辆信息</text>
<view class="vehicle-form">
<text class="section-title">运输参数</text>
<view class="address-form">
<!-- 运输模式 -->
<view class="form-item">
<text class="label">车辆类型</text>
<picker bindchange="bindVehicleTypeChange" range="{{vehicleTypes}}" value="{{selectedVehicleTypeIndex}}">
<text class="label">运输模式</text>
<picker bindchange="bindTransportModeChange" value="{{transportModeIndex}}" range="{{transportModes}}">
<view class="picker">
{{vehicleTypes[selectedVehicleTypeIndex]}}
{{transportModes[transportModeIndex]}}
</view>
</picker>
</view>
<view class="form-item">
<text class="label">载重能力 (吨)</text>
<input class="input" bindinput="bindVehicleInfoInput" data-key="capacity" value="{{vehicleInfo.capacity}}" placeholder="请输入载重能力" type="number" />
</view>
<view class="form-item">
<text class="label">车辆编号</text>
<input class="input" bindinput="bindVehicleInfoInput" data-key="number" value="{{vehicleInfo.number}}" placeholder="请输入车辆编号" />
<!-- 规格选择 -->
<view class="form-item" wx:if="{{specList.length > 0}}">
<text class="label">规格选择</text>
<picker bindchange="bindSpecChange" value="{{selectedSpecIndex}}" range="{{formattedSpecList}}">
<view class="picker">
{{formattedSpecList[selectedSpecIndex]}}
</view>
</picker>
</view>
<!-- 鸡蛋重量 -->
<view class="form-item">
<text class="label">司机姓名</text>
<input class="input" bindinput="bindVehicleInfoInput" data-key="driver" value="{{vehicleInfo.driver}}" placeholder="请输入司机姓名" />
<text class="label">鸡蛋重量(公斤)</text>
<input class="input" type="number" name="weight" placeholder="请输入鸡蛋重量" value="{{weight}}" bindinput="bindWeightInput" />
</view>
<!-- 货物体积 -->
<view class="form-item">
<text class="label">联系电话</text>
<input class="input" bindinput="bindVehicleInfoInput" data-key="phone" value="{{vehicleInfo.phone}}" placeholder="请输入联系电话" type="number" />
<text class="label">货物体积(立方米)</text>
<input class="input" type="number" name="volume" placeholder="请输入货物体积" value="{{volume}}" bindinput="bindVolumeInput" />
</view>
</view>
</view>
<!-- 物流人员信息 -->
<view class="section">
<text class="section-title">物流人员信息</text>
<view class="logistics-intro">
<text class="intro-text">我们拥有专业的物流团队,为您提供高效、安全的运输服务。以下是我们的物流专家,他们具有丰富的行业经验和专业知识,能够为您的货物运输提供专业的解决方案。</text>
</view>
<view class="logistics-personnel">
<view class="personnel-card" wx:for="{{logisticsPersonnel}}" wx:key="item.id">
<view class="personnel-header-section">
<view class="personnel-avatar">
<text class="avatar-text">{{item.name.charAt(0)}}</text>
</view>
<view class="personnel-header-info">
<view class="personnel-name">{{item.name}}</view>
<view class="personnel-position">{{item.position}}</view>
<view class="personnel-tags">
<view class="personnel-tag">{{item.experience}}年物流经验</view>
<view class="personnel-tag">认证物流师</view>
<view class="personnel-tag">专业配送</view>
<!-- 包装类型、车型、车长 -->
<view style="display: flex; gap: 12rpx; margin-bottom: 20rpx;">
<view class="form-item" style="flex: 1;">
<text class="label">包装类型</text>
<picker bindchange="bindPackagingChange" value="{{packagingIndex}}" range="{{packagingTypes}}">
<view class="picker">
{{packagingTypes[packagingIndex]}}
</view>
</view>
</picker>
</view>
<view class="personnel-description">
<view class="description-text">
{{item.description || '拥有丰富的物流行业经验,熟悉各种货物的运输要求和流程,能够为客户提供专业的物流解决方案和优质的服务。'}}
</view>
<view class="form-item" style="flex: 1;">
<text class="label">车型</text>
<picker bindchange="bindVehicleTypeChange" value="{{vehicleTypeIndex}}" range="{{vehicleTypes}}">
<view class="picker">
{{vehicleTypes[vehicleTypeIndex]}}
</view>
</picker>
</view>
<view class="personnel-contact-section">
<view class="personnel-contact-info">
<view class="contact-label">联系电话:</view>
<view class="contact-value">{{item.phone}}</view>
</view>
<button class="contact-btn" bindtap="makePhoneCall" data-phone="{{item.phone}}">
<text>立即联系</text>
</button>
<view class="form-item" style="flex: 1;">
<text class="label">车长</text>
<picker bindchange="bindTruckLengthChange" value="{{truckLengthIndex}}" range="{{truckLengths}}">
<view class="picker">
{{truckLengths[truckLengthIndex]}}
</view>
</picker>
</view>
</view>
<view wx:if="{{logisticsPersonnel.length === 0}}" class="empty-state">
<text>暂无物流人员信息</text>
<!-- 车型详情提示 -->
<view class="form-item">
<text class="label">车型载重/体积参考</text>
<text class="vehicle-info">{{vehicleInfo}}</text>
</view>
</view>
</view>
<!-- 计算按钮 -->
<view class="calculate-section">
<button class="calculate-btn" bindtap="calculateFreight" loading="{{loading}}">
<view class="calculate-section" style="flex-direction: row; justify-content: space-between;">
<button class="calculate-btn" bindtap="calculate" loading="{{loading}}" style="flex: 1; margin-right: 12rpx;">
<text>计算运费</text>
</button>
<button class="clear-btn" bindtap="clearInput">
<button class="clear-btn" bindtap="clearInput" style="flex: 1; margin-left: 12rpx;">
<text>清空输入</text>
</button>
</view>
<!-- 计算结果 -->
<view class="result-section" wx:if="{{calculationResult}}">
<view class="result-section" wx:if="{{calculationResult || showResult}}">
<text class="section-title">计算结果</text>
<view class="result-card">
<view class="result-item">
<text class="result-label">预估运费</text>
<text class="result-value freight">{{calculationResult.freight}} 元</text>
<text class="result-value freight">{{feeRange}}</text>
</view>
<view class="result-item">
<text class="result-label">运输距离</text>
<text class="result-value">{{calculationResult.distance}} km</text>
<text class="result-value">{{calculationResult ? calculationResult.distance + ' km' : ''}}</text>
</view>
<view class="result-item">
<text class="result-label">预计时效</text>
<text class="result-value">{{calculationResult.deliveryTime}} 天</text>
<view class="result-item" wx:if="{{showResult}}">
<text class="result-label">市场参考价</text>
<text class="result-value">{{marketPrice}}</text>
</view>
<view class="result-item" wx:if="{{showResult}}">
<text class="result-label">合规性检查</text>
<text class="result-value" style="color: {{isCompliant ? '#07C160' : '#F56C6C'}}">{{complianceStatus}}</text>
</view>
</view>
<!-- 运费提示信息 -->
<view class="result-note" wx:if="{{showResult}}">
<text class="note-text">注:预估运费可能与实际费用存在误差,仅供参考。如需准确报价,建议联系下方专业物流老师获取详细方案。</text>
</view>
</view>
<!-- 历史记录 -->
@ -222,6 +212,53 @@
<text>暂无历史记录</text>
</view>
</view>
<!-- 物流人员信息 -->
<view class="section">
<text class="section-title">物流人员信息</text>
<view class="logistics-intro">
<text class="intro-text">我们拥有专业的物流团队,为您提供高效、安全的运输服务。以下是我们的物流专家,他们具有丰富的行业经验和专业知识,能够为您的货物运输提供专业的解决方案。</text>
</view>
<view class="logistics-personnel">
<view class="personnel-card" wx:for="{{logisticsPersonnel}}" wx:key="item.id">
<view class="personnel-header-section">
<view class="personnel-avatar">
<image wx:if="{{index === 0}}" src="https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BB%BF%E5%A3%B3/image/855d000d7555af77bb2d46a86deb16d2.jpeg" class="avatar-image"></image>
<image wx:elif="{{index === 1}}" src="https://my-supplier-photos.oss-cn-chengdu.aliyuncs.com/products/%E7%BB%BF%E5%A3%B3/image/855d000d7555af77bb2d46a86deb16d2.jpeg" class="avatar-image"></image>
<text wx:else class="avatar-text">{{item.name.charAt(0)}}</text>
</view>
<view class="personnel-header-info">
<view class="personnel-name" wx:if="{{index === 0}}">物流张经理</view>
<view class="personnel-name" wx:elif="{{index === 1}}">物流刘经理</view>
<view class="personnel-name" wx:else>{{item.name}}</view>
<view class="personnel-position" wx:if="{{index > 1}}">{{item.position}}</view>
<view class="personnel-tags">
<view class="personnel-tag">{{item.experience}}年物流经验</view>
<view class="personnel-tag">认证物流师</view>
<view class="personnel-tag">专业配送</view>
</view>
</view>
</view>
<view class="personnel-description">
<view class="description-text">
{{item.description || '拥有丰富的物流行业经验,熟悉各种货物的运输要求和流程,能够为客户提供专业的物流解决方案和优质的服务。'}}
</view>
</view>
<view class="personnel-contact-section">
<view class="personnel-contact-info">
<view class="contact-label">联系电话:</view>
<view class="contact-value">{{item.phone}}</view>
</view>
<button class="contact-btn" bindtap="makePhoneCall" data-phone="{{item.phone}}">
<text>立即联系</text>
</button>
</view>
</view>
<view wx:if="{{logisticsPersonnel.length === 0}}" class="empty-state">
<text>暂无物流人员信息</text>
</view>
</view>
</view>
</view>
<!-- 地址选择器 -->

121
pages/freight-calculator/index.wxss

@ -103,6 +103,13 @@
text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}
.avatar-image {
width: 100%;
height: 100%;
border-radius: 50%;
object-fit: cover;
}
.personnel-header-info {
flex: 1;
display: flex;
@ -134,11 +141,20 @@
.personnel-tag {
font-size: 18rpx;
color: #1989fa;
background-color: rgba(25, 137, 250, 0.1);
padding: 6rpx 14rpx;
border-radius: 16rpx;
border: 1rpx solid rgba(25, 137, 250, 0.2);
color: #1890ff;
background: linear-gradient(135deg, rgba(25, 137, 250, 0.15), rgba(24, 144, 255, 0.05));
padding: 8rpx 16rpx;
border-radius: 20rpx;
border: 1rpx solid rgba(25, 137, 250, 0.3);
box-shadow: 0 2rpx 6rpx rgba(25, 137, 250, 0.15);
font-weight: 500;
transition: all 0.3s ease;
}
.personnel-tag:hover {
background: linear-gradient(135deg, rgba(25, 137, 250, 0.2), rgba(24, 144, 255, 0.1));
box-shadow: 0 3rpx 8rpx rgba(25, 137, 250, 0.2);
transform: translateY(-1rpx);
}
.personnel-description {
@ -186,16 +202,17 @@
background: linear-gradient(135deg, #1989fa 0%, #1890ff 100%);
color: #fff;
border: none;
border-radius: 8rpx;
padding: 14rpx 28rpx;
font-size: 22rpx;
border-radius: 6rpx;
padding: 10rpx 16rpx;
font-size: 20rpx;
font-weight: 600;
display: flex;
align-items: center;
justify-content: center;
gap: 8rpx;
box-shadow: 0 4rpx 12rpx rgba(25, 137, 250, 0.3);
gap: 6rpx;
box-shadow: 0 2rpx 8rpx rgba(25, 137, 250, 0.3);
transition: all 0.3s ease;
white-space: nowrap;
}
.contact-btn:hover {
@ -254,6 +271,22 @@
width: 100%;
}
/* 地址行样式 */
.address-row {
margin-bottom: 16rpx;
}
.address-inputs {
display: flex;
gap: 12rpx;
width: 100%;
}
.address-input {
flex: 1;
min-width: 0;
}
.label {
font-size: 22rpx;
color: #666;
@ -416,14 +449,16 @@
color: #666;
font-weight: 500;
flex: 1;
min-width: 100rpx;
}
.result-value {
font-size: 24rpx;
font-weight: 600;
color: #333;
flex: 1;
flex: 0 0 auto;
text-align: right;
min-width: 200rpx;
}
.result-value.freight {
@ -431,6 +466,24 @@
font-size: 28rpx;
}
/* 结果提示信息 */
.result-note {
margin-top: 16rpx;
padding: 16rpx;
background-color: #fff7e6;
border-radius: 8rpx;
border-left: 4rpx solid #fa8c16;
width: 100%;
box-sizing: border-box;
}
.note-text {
font-size: 20rpx;
color: #fa8c16;
line-height: 1.5;
font-weight: 500;
}
/* 历史记录 */
.history-list {
margin-top: 12rpx;
@ -642,6 +695,52 @@
color: #ff4d4f;
}
/* 车型信息样式 */
.vehicle-info {
font-size: 20rpx;
color: #999;
margin-top: 4rpx;
line-height: 1.4;
}
/* 详细费用明细样式 */
.detail-section {
margin-top: 16rpx;
background-color: #f8f9fa;
border-radius: 8rpx;
padding: 16rpx;
border-left: 4rpx solid #e3f2fd;
}
.detail-text {
font-size: 20rpx;
color: #666;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-all;
}
/* 切换按钮样式 */
.toggle-btn {
background: none;
border: none;
font-size: 20rpx;
color: #1989fa;
padding: 8rpx 16rpx;
border-radius: 4rpx;
display: flex;
align-items: center;
justify-content: center;
}
.toggle-btn:hover {
background-color: rgba(25, 137, 250, 0.1);
}
.toggle-btn:active {
background-color: rgba(25, 137, 250, 0.2);
}
/* 动画效果 */
@keyframes fadeInUp {
from {

483
pages/goods-detail/goods-detail.js

@ -467,9 +467,24 @@ function processWeightAndQuantityData(weightSpecString, quantityString, specStri
// 组合显示:格式为"净重信息————件数-价格"
let display = '';
if (weightSpecDisplay && quantity) {
// 检查是否为售空状态,如果是售空状态则显示"售空"
// 检查是否为售空状态,如果是售空状态则显示"已售多少件"
if (weightSpecDisplay.includes('售空') || quantity === '售空') {
display = `${weightSpecDisplay}————售空`;
// 尝试从 weightSpecDisplay 或 quantity 中提取库存数量
let soldQuantity = quantity;
if (quantity === '售空') {
// 从 weightSpecDisplay 中提取数字
const quantityMatch = weightSpecDisplay.match(/(\d+)/);
if (quantityMatch) {
soldQuantity = quantityMatch[1];
} else {
soldQuantity = 0;
}
}
display = `${weightSpecDisplay}————已售${soldQuantity}`;
} else if (weightSpecDisplay.includes('剩余售空件') || weightSpecDisplay.includes('已售售空件')) {
// 替换已有的"剩余售空件"或"已售售空件"为"已售多少件"
const soldQuantity = weightSpecDisplay.match(/(\d+)件/)?.[1] || 0;
display = weightSpecDisplay.replace(/(剩余售空|已售售空)件/, `已售${soldQuantity}`);
} else {
if (price) {
display = `${weightSpecDisplay}${quantity}件】¥${price}`;
@ -478,7 +493,18 @@ function processWeightAndQuantityData(weightSpecString, quantityString, specStri
}
}
} else if (weightSpecDisplay) {
display = weightSpecDisplay;
// 处理只包含净重信息的情况
if (weightSpecDisplay.includes('剩余售空件') || weightSpecDisplay.includes('已售售空件')) {
const soldQuantity = weightSpecDisplay.match(/(\d+)件/)?.[1] || 0;
display = weightSpecDisplay.replace(/(剩余售空|已售售空)件/, `已售${soldQuantity}`);
} else if (weightSpecDisplay.includes('售空')) {
// 尝试从 weightSpecDisplay 中提取库存数量
const quantityMatch = weightSpecDisplay.match(/(\d+)/);
const soldQuantity = quantityMatch ? quantityMatch[1] : 0;
display = `${weightSpecDisplay}————已售${soldQuantity}`;
} else {
display = weightSpecDisplay;
}
} else if (quantity) {
display = `${quantity}`;
}
@ -497,9 +523,30 @@ function processWeightAndQuantityData(weightSpecString, quantityString, specStri
}
}
// 处理 quantity 字段,确保售空时也有正确的数量值
let processedQuantity = quantity;
if (quantity === '售空' || weightSpecDisplay.includes('售空') || weightSpecDisplay.includes('已售售空件') || weightSpecDisplay.includes('剩余售空件')) {
// 尝试从 weightSpecDisplay 中提取数字
const quantityMatch = weightSpecDisplay.match(/(\d+)/);
if (quantityMatch) {
processedQuantity = quantityMatch[1];
} else if (quantity !== '售空' && quantity !== '') {
// 如果 quantity 不是 '售空' 且不为空,则保持原值
processedQuantity = quantity;
} else {
// 尝试从 display 字段中提取数字
const displayMatch = display.match(/(\d+)/);
if (displayMatch) {
processedQuantity = displayMatch[1];
} else {
processedQuantity = 0;
}
}
}
result.push({
weightSpec: weightSpecDisplay,
quantity: quantity,
quantity: processedQuantity,
price: price,
specStatus: specStatus,
display: display,
@ -768,6 +815,9 @@ Page({
console.log('===== 显示讲价弹窗开始 =====');
console.log('当前 goodsDetail:', this.data.goodsDetail);
// 记录用户操作历史
API.addUserHistory('还价');
const weightQuantityData = this.data.goodsDetail.weightQuantityData || [];
console.log('weightQuantityData:', weightQuantityData);
@ -941,7 +991,7 @@ Page({
});
if (bargainPrice > minPrice) {
const step = bargainPrice < 20 ? 0.1 : 1;
const step = 0.1;
const newPrice = formatPrice(bargainPrice - step);
console.log('计算新价格:', newPrice);
this.updatePrice(newPrice);
@ -958,7 +1008,7 @@ Page({
});
if (bargainPrice < maxPrice) {
const step = bargainPrice < 20 ? 0.1 : 1;
const step = 0.1;
const newPrice = formatPrice(bargainPrice + step);
console.log('计算新价格:', newPrice);
this.updatePrice(newPrice);
@ -1449,6 +1499,16 @@ Page({
// 导航到运费计算器
navigateToFreightCalculator: function() {
// 权限检查
if (!this.data.isInternalUser) {
wx.showModal({
title: '权限不足',
content: '您没有权限使用此功能',
showCancel: false
});
return;
}
const goodsDetail = this.data.goodsDetail;
if (!goodsDetail) {
wx.showToast({
@ -1458,11 +1518,16 @@ Page({
return;
}
// 记录用户操作历史
API.addUserHistory('运费估算');
// 构建要传递的商品信息
const selectedGoods = {
id: goodsDetail.id || goodsDetail.productId,
name: goodsDetail.name || '未命名商品',
region: goodsDetail.region || '',
// 尝试获取原始的完整地区信息,而不是处理过的省份信息
fullRegion: goodsDetail.originalRegion || goodsDetail.region || '',
specification: goodsDetail.specification || goodsDetail.spec || '',
quantity: goodsDetail.quantity || goodsDetail.minOrder || '',
price: goodsDetail.price || '',
@ -1472,6 +1537,7 @@ Page({
weightQuantityData: goodsDetail.weightQuantityData || [],
imageUrl: (goodsDetail.imageUrls && goodsDetail.imageUrls.length > 0) ? goodsDetail.imageUrls[0] : ''
};
console.log('构建的selectedGoods:', selectedGoods);
// 导航到运费计算器页面
this.navigateLock(() => {
@ -2108,6 +2174,7 @@ Page({
const isSoldOut = product.status === 'sold_out' ||
product.status === 'sold' ||
product.status === 'out_of_stock' ||
product.status === '售空' ||
(product.supplyStatus && product.supplyStatus.includes('售空'));
console.log('===== 售空判断详细分析 =====');
@ -2127,6 +2194,7 @@ Page({
console.log('当前isSoldOut值:', isSoldOut);
console.log('即将执行的条件分支...');
// 处理售空状态和非售空状态
if (isSoldOut) {
// 售空状态的商品,显示规格信息和价格
if (weightSpecString) {
@ -2144,23 +2212,49 @@ Page({
} else if (priceString) {
priceArray = [String(priceString)];
}
// 处理数量数组
let quantityArray = [];
if (quantityString && typeof quantityString === 'string') {
quantityArray = quantityString.split(/[,,、]/).map(item => item.trim()).filter(item => item);
} else if (quantityString) {
quantityArray = [String(quantityString)];
}
weightQuantityData = weightSpecArray.map((spec, index) => {
const price = priceArray[index] || '';
// 使用实际的quantity字段,而不是从spec中提取
const soldQuantity = quantityArray[index] || product.quantity || 0;
// 处理规格显示格式 - 根据内容类型添加相应前缀
let weightSpecDisplay = '';
if (spec) {
if (spec.includes('净重')) {
// 如果已包含"净重"前缀,保持不变
weightSpecDisplay = spec;
} else if (spec.includes('毛重')) {
// 如果已包含"毛重"前缀,保持不变
weightSpecDisplay = spec;
} else {
// 如果都不包含,默认为净重
weightSpecDisplay = `净重${spec}`;
}
}
return {
weightSpec: spec.includes('毛重') ? spec : `毛重${spec}`,
quantity: '售空',
weightSpec: weightSpecDisplay,
quantity: soldQuantity,
price: price,
display: price ?
`${spec.includes('毛重') ? spec : `毛重${spec}`}【售空】¥${price}` :
`${spec.includes('毛重') ? spec : `毛重${spec}`}【售空】`
`${weightSpecDisplay}【已售${soldQuantity}件】¥${price}` :
`${weightSpecDisplay}【已售${soldQuantity}件】`,
isSoldOut: true
};
});
} else {
// 如果没有规格信息,则显示默认的售空信息
const soldQuantity = product.quantity || 0;
weightQuantityData = [{
weightSpec: '规格信息',
quantity: '售空',
display: '规格信息【售空】'
quantity: soldQuantity,
display: `规格信息【已售${soldQuantity}件】`,
isSoldOut: true
}];
}
console.log('✓ 售空分支执行: 显示规格信息和价格');
@ -2183,6 +2277,12 @@ Page({
}
weightQuantityData = processWeightAndQuantityData(weightSpecString, quantityString, '', priceString, specStatusString, specPriceChanges);
// 为非售空状态的商品添加isSoldOut标志
weightQuantityData = weightQuantityData.map(item => ({
...item,
isSoldOut: false
}));
console.log('× 非售空分支结果:', weightQuantityData);
}
@ -2265,6 +2365,9 @@ Page({
}
}
// 保存原始的完整地区信息
const originalRegion = product.region || '';
// 转换商品数据格式
const formattedGoods = {
// 优先设置售空状态标记,放在最前面确保不被覆盖
@ -2304,6 +2407,8 @@ Page({
// 确保imageUrls和mediaItems被正确设置
imageUrls: imageUrls || [],
mediaItems: mediaItems,
// 保存原始的完整地区信息
originalRegion: originalRegion,
// 确保region使用提取后的省份信息,放在最后覆盖所有展开操作
region: region,
// 添加价格波动信息
@ -2352,8 +2457,8 @@ Page({
type: viewer.type,
followupRecords: (viewer.followupRecords || []).map(record => ({
...record,
// 确保时间显示为北京时间
createdAt: record.createdAt ? formatBeijingTime(record.createdAt) : '未知时间'
// 优先使用users表的followup_at字段作为跟进时间,如果没有则使用createdAt
createdAt: record.followup_at ? formatBeijingTime(record.followup_at) : (record.createdAt ? formatBeijingTime(record.createdAt) : '未知时间')
}))
}));
@ -3788,6 +3893,9 @@ Page({
onCompareClick: function () {
console.log('用户点击了对比价格按钮,准备显示对比价格弹窗');
// 记录用户操作历史
API.addUserHistory('对比价格');
// 检查用户登录状态
const openid = wx.getStorageSync('openid');
const userId = wx.getStorageSync('userId');
@ -3828,28 +3936,163 @@ Page({
// 获取当前商品的信息
const currentGoods = this.data.goodsDetail;
const currentCategory = currentGoods.category || '';
const currentSpecifications = currentGoods.weightQuantityData || [];
// 找到当前商品种类在选项中的索引,默认为0(全部)
let defaultCategoryIndex = 0;
if (currentCategory) {
const index = this.data.categoryOptions.indexOf(currentCategory);
if (index !== -1) {
defaultCategoryIndex = index;
}
}
// 品种默认选择当前商品的品种
const selectedCategory = currentGoods.category || '全部';
// 初始化弹窗状态
this.setData({
showCompareModal: true,
compareStep: 1,
selectedCategoryIndex: defaultCategoryIndex,
selectedCategory: this.data.categoryOptions[defaultCategoryIndex],
selectedSpecIndex: 0,
selectedSpec: currentSpecifications.length > 0 ? currentSpecifications[0] : null,
currentSpecifications: currentSpecifications
});
// 找到当前商品品种在选项中的索引
const categoryIndex = this.data.categoryOptions.indexOf(selectedCategory);
const selectedCategoryIndex = categoryIndex !== -1 ? categoryIndex : 0;
// 检查规格数量
if (currentSpecifications.length === 1) {
// 只有一个规格,直接跳转
const selectedSpec = currentSpecifications[0];
// 显示加载提示
wx.showLoading({
title: '正在获取对比数据...',
mask: true
});
// 提取规格信息用于查询
const specification = selectedSpec.weightSpec || selectedSpec.display || '';
console.log('准备通过规格查询商品,规格:', specification);
// 调用API获取相同规格的商品数据
API.getProductsBySpecification(specification)
.then(comparisonProducts => {
wx.hideLoading();
console.log('获取到的对比商品数据:', comparisonProducts);
// 构建要传递的数据
const goodsData = {
id: currentGoods.id || currentGoods.productId,
name: currentGoods.name || '',
price: currentGoods.price || '',
imageUrls: currentGoods.imageUrls || [],
region: currentGoods.region || '',
weightQuantityData: currentGoods.weightQuantityData || [],
category: selectedCategory,
yolk: currentGoods.yolk || '',
sourceType: currentGoods.sourceType || '',
supplyStatus: currentGoods.supplyStatus || '',
mediaItems: currentGoods.mediaItems || [],
frequency: currentGoods.frequency || 0,
status: currentGoods.status || 'published',
totalStock: currentGoods.totalStock || '充足',
selectedSpec: selectedSpec,
comparisonProducts: comparisonProducts // 添加对比商品数据
};
console.log('准备跳转到对比价格页面,传递的数据:', goodsData);
// 跳转到对比价格页面
wx.navigateTo({
url: `/pages/compare_price/index?goodsData=${encodeURIComponent(JSON.stringify(goodsData))}`,
success: function () {
console.log('成功跳转到对比价格页面');
},
fail: function (error) {
console.error('跳转到对比价格页面失败:', error);
wx.showToast({
title: '跳转失败,请稍后重试',
icon: 'none'
});
}
});
})
.catch(error => {
wx.hideLoading();
console.error('获取对比商品数据失败:', error);
// 即使获取对比数据失败,也继续跳转到对比价格页面
const goodsData = {
id: currentGoods.id || currentGoods.productId,
name: currentGoods.name || '',
price: currentGoods.price || '',
imageUrls: currentGoods.imageUrls || [],
region: currentGoods.region || '',
weightQuantityData: currentGoods.weightQuantityData || [],
category: selectedCategory,
yolk: currentGoods.yolk || '',
sourceType: currentGoods.sourceType || '',
supplyStatus: currentGoods.supplyStatus || '',
mediaItems: currentGoods.mediaItems || [],
frequency: currentGoods.frequency || 0,
status: currentGoods.status || 'published',
totalStock: currentGoods.totalStock || '充足',
selectedSpec: selectedSpec,
comparisonProducts: [] // 空数组,表示获取失败
};
console.log('获取对比数据失败,准备跳转到对比价格页面,传递的数据:', goodsData);
// 跳转到对比价格页面
wx.navigateTo({
url: `/pages/compare_price/index?goodsData=${encodeURIComponent(JSON.stringify(goodsData))}`,
success: function () {
console.log('成功跳转到对比价格页面');
},
fail: function (error) {
console.error('跳转到对比价格页面失败:', error);
wx.showToast({
title: '跳转失败,请稍后重试',
icon: 'none'
});
}
});
});
} else if (currentSpecifications.length > 1) {
// 存在多个规格,弹出弹窗让用户选择
this.setData({
showCompareModal: true,
compareStep: 2, // 直接显示规格选择步骤
selectedCategory: selectedCategory,
selectedCategoryIndex: selectedCategoryIndex,
selectedSpecIndex: 0,
selectedSpec: currentSpecifications.length > 0 ? currentSpecifications[0] : null,
currentSpecifications: currentSpecifications
});
} else {
// 没有规格,直接跳转
const goodsData = {
id: currentGoods.id || currentGoods.productId,
name: currentGoods.name || '',
price: currentGoods.price || '',
imageUrls: currentGoods.imageUrls || [],
region: currentGoods.region || '',
weightQuantityData: currentGoods.weightQuantityData || [],
category: selectedCategory,
yolk: currentGoods.yolk || '',
sourceType: currentGoods.sourceType || '',
supplyStatus: currentGoods.supplyStatus || '',
mediaItems: currentGoods.mediaItems || [],
frequency: currentGoods.frequency || 0,
status: currentGoods.status || 'published',
totalStock: currentGoods.totalStock || '充足',
selectedSpec: null,
comparisonProducts: [] // 空数组,因为没有规格
};
console.log('准备跳转到对比价格页面,传递的数据:', goodsData);
// 跳转到对比价格页面
wx.navigateTo({
url: `/pages/compare_price/index?goodsData=${encodeURIComponent(JSON.stringify(goodsData))}`,
success: function () {
console.log('成功跳转到对比价格页面');
},
fail: function (error) {
console.error('跳转到对比价格页面失败:', error);
wx.showToast({
title: '跳转失败,请稍后重试',
icon: 'none'
});
}
});
}
},
// 选择品种
@ -3902,59 +4145,134 @@ Page({
}
const currentGoods = this.data.goodsDetail;
const selectedCategory = this.data.selectedCategory;
// 使用已选择的品种
const selectedCategory = this.data.selectedCategory || currentGoods.category || '全部';
const selectedSpec = this.data.selectedSpec;
// 显示提示信息
wx.showToast({
title: `已选择${selectedCategory} ${selectedSpec.display}`,
icon: 'info',
duration: 1500,
success: () => {
setTimeout(() => {
// 关闭弹窗
this.setData({
showCompareModal: false
});
// 显示加载提示
wx.showLoading({
title: '正在获取对比数据...',
mask: true
});
// 构建要传递的数据
const goodsData = {
id: currentGoods.id || currentGoods.productId,
name: currentGoods.name || '',
price: currentGoods.price || '',
imageUrls: currentGoods.imageUrls || [],
region: currentGoods.region || '',
weightQuantityData: currentGoods.weightQuantityData || [],
category: selectedCategory,
yolk: currentGoods.yolk || '',
sourceType: currentGoods.sourceType || '',
supplyStatus: currentGoods.supplyStatus || '',
mediaItems: currentGoods.mediaItems || [],
frequency: currentGoods.frequency || 0,
status: currentGoods.status || 'published',
totalStock: currentGoods.totalStock || '充足',
selectedSpec: selectedSpec
};
// 提取规格信息用于查询
const specification = selectedSpec.weightSpec || selectedSpec.display || '';
console.log('准备通过规格查询商品,规格:', specification);
console.log('准备跳转到对比价格页面,传递的数据:', goodsData);
// 调用API获取相同规格的商品数据
API.getProductsBySpecification(specification)
.then(comparisonProducts => {
wx.hideLoading();
console.log('获取到的对比商品数据:', comparisonProducts);
// 跳转到对比价格页面
wx.navigateTo({
url: `/pages/compare_price/index?goodsData=${encodeURIComponent(JSON.stringify(goodsData))}`,
success: function () {
console.log('成功跳转到对比价格页面');
},
fail: function (error) {
console.error('跳转到对比价格页面失败:', error);
wx.showToast({
title: '跳转失败,请稍后重试',
icon: 'none'
// 显示提示信息
wx.showToast({
title: `已选择${selectedCategory} ${selectedSpec.display}`,
icon: 'info',
duration: 1500,
success: () => {
setTimeout(() => {
// 关闭弹窗
this.setData({
showCompareModal: false
});
}
});
}, 1500);
}
});
// 构建要传递的数据
const goodsData = {
id: currentGoods.id || currentGoods.productId,
name: currentGoods.name || '',
price: currentGoods.price || '',
imageUrls: currentGoods.imageUrls || [],
region: currentGoods.region || '',
weightQuantityData: currentGoods.weightQuantityData || [],
category: selectedCategory,
yolk: currentGoods.yolk || '',
sourceType: currentGoods.sourceType || '',
supplyStatus: currentGoods.supplyStatus || '',
mediaItems: currentGoods.mediaItems || [],
frequency: currentGoods.frequency || 0,
status: currentGoods.status || 'published',
totalStock: currentGoods.totalStock || '充足',
selectedSpec: selectedSpec,
comparisonProducts: comparisonProducts // 添加对比商品数据
};
console.log('准备跳转到对比价格页面,传递的数据:', goodsData);
// 跳转到对比价格页面
wx.navigateTo({
url: `/pages/compare_price/index?goodsData=${encodeURIComponent(JSON.stringify(goodsData))}`,
success: function () {
console.log('成功跳转到对比价格页面');
},
fail: function (error) {
console.error('跳转到对比价格页面失败:', error);
wx.showToast({
title: '跳转失败,请稍后重试',
icon: 'none'
});
}
});
}, 1500);
}
});
})
.catch(error => {
wx.hideLoading();
console.error('获取对比商品数据失败:', error);
// 即使获取对比数据失败,也继续跳转到对比价格页面
wx.showToast({
title: `已选择${selectedCategory} ${selectedSpec.display}`,
icon: 'info',
duration: 1500,
success: () => {
setTimeout(() => {
// 关闭弹窗
this.setData({
showCompareModal: false
});
// 构建要传递的数据
const goodsData = {
id: currentGoods.id || currentGoods.productId,
name: currentGoods.name || '',
price: currentGoods.price || '',
imageUrls: currentGoods.imageUrls || [],
region: currentGoods.region || '',
weightQuantityData: currentGoods.weightQuantityData || [],
category: selectedCategory,
yolk: currentGoods.yolk || '',
sourceType: currentGoods.sourceType || '',
supplyStatus: currentGoods.supplyStatus || '',
mediaItems: currentGoods.mediaItems || [],
frequency: currentGoods.frequency || 0,
status: currentGoods.status || 'published',
totalStock: currentGoods.totalStock || '充足',
selectedSpec: selectedSpec,
comparisonProducts: [] // 空数组,表示获取失败
};
console.log('获取对比数据失败,准备跳转到对比价格页面,传递的数据:', goodsData);
// 跳转到对比价格页面
wx.navigateTo({
url: `/pages/compare_price/index?goodsData=${encodeURIComponent(JSON.stringify(goodsData))}`,
success: function () {
console.log('成功跳转到对比价格页面');
},
fail: function (error) {
console.error('跳转到对比价格页面失败:', error);
wx.showToast({
title: '跳转失败,请稍后重试',
icon: 'none'
});
}
});
}, 1500);
}
});
});
},
// 关闭对比价格弹窗
@ -4414,5 +4732,10 @@ Page({
// 返回上一页
goBack() {
wx.navigateBack();
},
// 物流按钮点击事件
onLogisticsClick() {
this.navigateToFreightCalculator();
}
});

99
pages/goods-detail/goods-detail.wxml

@ -86,7 +86,7 @@
</view>
</view>
</view>
<view class="source-description" style="background: #f5f5f5; font-size: 28rpx; color: #333; height: 43rpx; display: block; box-sizing: border-box">
<view class="source-description" style="background: #f5f5f5; font-size: 28rpx; color: #333; padding: 12rpx 16rpx; display: block; box-sizing: border-box; word-wrap: break-word; white-space: normal; min-height: 60rpx;">
{{goodsDetail.description || '暂无描述'}}
</view>
</view>
@ -97,14 +97,7 @@
<text wx:if="{{goodsDetail.weightQuantityData && goodsDetail.weightQuantityData[0] && goodsDetail.weightQuantityData[0].priceChangeDirection === 'up'}}" class="price-change-arrow up">↑</text>
<text wx:elif="{{goodsDetail.weightQuantityData && goodsDetail.weightQuantityData[0] && goodsDetail.weightQuantityData[0].priceChangeDirection === 'down'}}" class="price-change-arrow down">↓</text>
</view>
<view
class="compare-button"
bindtap="onCompareClick"
style="display: flex; align-items: left; margin-right: 20rpx; padding: 8rpx 16rpx; border: 2rpx solid #4a90e2; border-radius: 20rpx; position: relative; left: 68rpx; top: 0rpx"
>
<text style="font-size: 32rpx; color: #4a90e2; margin-right: 8rpx;">对比价格</text>
<text style="font-size: 28rpx; color: #4a90e2;">></text>
</view>
<view
class="favorite-button"
bindtap="onFavoriteClick"
@ -122,12 +115,26 @@
<view class="wq-title">规格信息</view>
<view class="wq-list">
<block wx:for="{{goodsDetail.weightQuantityData}}" wx:key="index">
<view class="wq-item">
<!-- 使用display字段显示完整信息,包括已下架标记 -->
<text class="wq-text">{{item.display}}</text>
<text wx:if="{{item.priceChangeDirection === 'up'}}" class="price-change-arrow up">↑</text>
<text wx:elif="{{item.priceChangeDirection === 'down'}}" class="price-change-arrow down">↓</text>
<text wx:if="{{item.isOffShelf}}" style="color: red; margin-left: 20rpx;">已下架</text>
<view class="spec-card">
<!-- 顶部:规格名称 + 价格 -->
<view class="spec-header">
<text class="spec-name">{{item.weightSpec}}</text>
<text class="spec-price">¥{{item.price}}</text>
</view>
<!-- 底部:降价/库存/下架状态 -->
<view class="spec-footer">
<!-- 降价标识(仅当 priceChangeDirection === 'down' 时显示) -->
<view wx:if="{{item.priceChangeDirection === 'down'}}" class="price-down-tag">
<text class="arrow">↓</text>
<text class="label">降价</text>
</view>
<!-- 已下架标识 -->
<text wx:if="{{item.isOffShelf}}" class="off-shelf-tag">已下架</text>
<!-- 库存信息(未下架且有件数且未售空时显示) -->
<text wx:elif="{{!item.isSoldOut && item.quantity && item.quantity !== '售空' && !item.weightSpec.includes('售空') && !item.display.includes('售空') && !item.weightSpec.includes('已售售空件') && !item.display.includes('已售售空件')}}" class="stock-info">剩余{{item.quantity}}件</text>
<!-- 售空标识(未下架且售空时显示) -->
<text wx:else class="stock-info">已售{{item.quantity || 0}}件</text>
</view>
</view>
</block>
</view>
@ -376,48 +383,40 @@
</view>
</view>
<!-- 操作按钮区域 -->
<!-- 操作按钮区域(替换原有底部按钮) -->
<view class="action-buttons" wx:if="{{!fromSeller}}">
<button
class="call-button bottom-button"
bindtap="makePhoneCall"
data-phone="{{goodsDetail.contact_phone}}"
>
拨打电话
<!-- 物流 -->
<button class="bottom-button logistics-btn" bindtap="onLogisticsClick">
<text class="icon">🚚</text>
<text class="text">物流</text>
</button>
<button
class="chat-button bottom-button"
bindtap="showBargainModal"
data-id="{{goodsDetail.id}}"
disabled="{{fromChatDetail}}"
wx:if="{{goodsDetail.bargaining === 0 && goodsDetail.status !== 'sold_out' && goodsDetail.status !== 'sold' && goodsDetail.status !== 'out_of_stock' && !goodsDetail.supplyStatus.includes('售空')}}"
>
还价
<!-- 对比 -->
<button class="bottom-button compare-btn" bindtap="onCompareClick">
<text class="icon">⚖️</text>
<text class="text">比价</text>
</button>
<!-- 联系 -->
<button class="bottom-button chat-btn" bindtap="onChat" data-id="{{goodsDetail.id}}">
<text class="icon">💬</text>
<text class="text">留言</text>
</button>
<button
class="chat-button bottom-button"
bindtap="navigateToFreightCalculator"
data-id="{{goodsDetail.id}}"
>
运费估算
<!-- 还价(保留原有显示条件) -->
<button class="bottom-button bargain-btn"
wx:if="{{goodsDetail.bargaining === 0 && goodsDetail.status !== 'sold_out' && goodsDetail.status !== 'sold' && goodsDetail.status !== 'out_of_stock' && !goodsDetail.supplyStatus.includes('售空')}}"
bindtap="showBargainModal">
<text class="icon">💰</text>
<text class="text">还价</text>
</button>
<button
class="chat-button bottom-button"
bindtap="onChat"
data-id="{{goodsDetail.id}}"
disabled="{{fromChatDetail}}"
>
💬 留言
<!-- 电话 -->
<button class="bottom-button phone-btn" bindtap="makePhoneCall" data-phone="{{goodsDetail.contact_phone}}">
<text class="icon">📞</text>
<text class="text">电话</text>
</button>
</view>
<!-- 返回按钮区域(仅在seller页面查看时显示) -->
<!-- 返回按钮区域(fromSeller 时保留) -->
<view class="action-buttons" wx:if="{{fromSeller}}">
<button
class="back-button bottom-button"
bindtap="goBack"
>
返回
</button>
<button class="back-button bottom-button" bindtap="goBack">返回</button>
</view>
<!-- 讲价弹窗 -->

225
pages/goods-detail/goods-detail.wxss

@ -413,88 +413,95 @@ video.slider-media .wx-video-volume-icon {
box-shadow: 0 2px 8px rgba(82, 196, 26, 0.2);
}
/* 底部按钮区域样式 */
/* 底部操作栏 - 图一样式 */
.action-buttons {
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 12px 16px;
display: flex;
background-color: #ffffff;
border-top: 1px solid #f0f0f0;
box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.06);
border-top: 2rpx solid #f0f0f0;
box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.06);
z-index: 99;
display: flex;
gap: 8px;
flex-wrap: nowrap;
box-sizing: border-box;
align-items: center;
justify-content: space-between;
height: 144rpx; /* 对应 h-18 (72px) */
}
.bottom-button {
flex: 1;
min-width: 0;
height: 48px;
border-radius: 24px;
font-size: 16px;
font-weight: 700;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
justify-content: center;
background: transparent;
border: none;
outline: none;
transition: all 0.3s ease;
border-radius: 0;
padding: 16rpx 0;
margin: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding: 0 12px;
height: 100%;
line-height: 1.2;
transition: background-color 0.2s;
}
.bottom-button:active {
transform: scale(0.98);
opacity: 0.9;
background-color: #f5f5f5; /* 默认点击背景 */
}
.call-button:active {
background-color: #4066ff;
border-color: #4066ff;
box-shadow: 0 4px 12px rgba(47, 84, 235, 0.3);
.bottom-button .icon {
font-size: 44rpx; /* 约22px,略大于原 text-lg */
margin-bottom: 6rpx;
}
.call-button.bottom-button {
background-color: #ffffff;
color: #2f54eb;
border: 2px solid #2f54eb;
box-shadow: none;
.bottom-button .text {
font-size: 26rpx; /* 13px */
font-weight: 400;
}
.call-button.bottom-button:active {
background-color: #f0f4ff;
transform: scale(0.98);
/* 物流、对比、联系默认灰色 */
.logistics-btn .icon,
.logistics-btn .text,
.compare-btn .icon,
.compare-btn .text,
.chat-btn .icon,
.chat-btn .text {
color: #666;
}
.chat-button.bottom-button:active {
background-color: #d6f7e6;
transform: scale(0.98);
/* 还价按钮 - 橙色背景与文字 */
.bargain-btn {
background-color: #fff7e6; /* 对应 bg-orange-50 */
}
.call-button.bottom-button {
background-color: #ffffff;
color: #2f54eb;
border: 2px solid #2f54eb;
box-shadow: none;
.bargain-btn .icon,
.bargain-btn .text {
color: #f97316; /* 对应 text-orange-600 */
}
.bargain-btn:active {
background-color: #ffedd5;
}
.call-button.bottom-button:active {
background-color: #f0f4ff;
transform: scale(0.98);
/* 电话按钮 - 绿色背景与白色文字 */
.phone-btn {
background-color: #10b981; /* 对应 bg-green-500 */
}
.phone-btn .icon,
.phone-btn .text {
color: #ffffff;
}
.phone-btn:active {
background-color: #059669;
}
.chat-button.bottom-button:active {
background-color: #d6f7e6;
transform: scale(0.98);
/* 返回按钮(来自 seller 时) */
.back-button.bottom-button {
background-color: #ffffff;
color: #333;
border: 2rpx solid #d9d9d9;
border-radius: 8rpx;
margin: 12rpx 20rpx;
height: auto;
flex: none;
width: auto;
padding: 16rpx 32rpx;
}
/* 图片预览弹窗 */
@ -721,73 +728,103 @@ video.slider-media .wx-video-volume-icon {
border: none;
}
/* 净重件数对应信息样式 */
/* 规格信息卡片样式(图一风格) */
.weight-quantity-info {
background-color: #ffffff;
margin: 8rpx 16rpx;
padding: 16rpx;
border-radius: 12rpx;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
border: 1rpx solid #f0f0f0;
background-color: transparent; /* 去除背景色,卡片自带白色背景 */
margin: 16rpx 16rpx 24rpx;
}
.wq-title {
font-size: 16px;
font-size: 32rpx;
font-weight: 600;
color: #262626;
margin-bottom: 16rpx;
padding-bottom: 12rpx;
border-bottom: 1rpx solid #f0f0f0;
position: relative;
}
.wq-title::after {
content: '';
position: absolute;
bottom: -1rpx;
left: 0;
width: 60rpx;
height: 4rpx;
background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
border-radius: 2rpx;
padding-left: 8rpx;
}
.wq-list {
display: flex;
flex-direction: column;
gap: 12rpx;
gap: 16rpx;
}
.wq-item {
background-color: #f8f9fa;
padding: 30rpx 20rpx;
border-radius: 8rpx;
border-left: 4rpx solid #1890ff;
transition: all 0.3s ease;
.spec-card {
background-color: #ffffff;
border: 2rpx solid #f0f0f0;
border-radius: 16rpx;
padding: 24rpx 20rpx;
box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
}
.wq-item:active {
background-color: #e6f7ff;
transform: translateX(4rpx);
.spec-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16rpx;
}
.wq-text {
line-height: 1.5;
.spec-name {
font-size: 30rpx;
font-weight: 500;
color: #262626;
line-height: 1.4;
flex: 1;
word-break: break-word;
padding-right: 20rpx;
}
.spec-price {
font-size: 34rpx;
font-weight: 600;
color: #595959;
color: #ff4d4f;
white-space: nowrap;
}
.wq-spec {
font-size: 20px;
color: #333333;
.spec-footer {
display: flex;
align-items: center;
gap: 16rpx;
flex-wrap: wrap;
}
.price-down-tag {
display: inline-flex;
align-items: center;
background-color: #f0fff0;
padding: 4rpx 12rpx;
border-radius: 8rpx;
border: 1rpx solid #b7eb8f;
}
.price-down-tag .arrow {
font-size: 28rpx;
color: #52c41a;
margin-right: 4rpx;
font-weight: bold;
}
.price-down-tag .label {
font-size: 24rpx;
color: #52c41a;
font-weight: 500;
}
.wq-price {
font-size: 18px;
color: #666666;
font-weight: 400;
margin-left: 10rpx;
.off-shelf-tag {
font-size: 24rpx;
color: #ff4d4f;
background-color: #fff1f0;
padding: 4rpx 12rpx;
border-radius: 8rpx;
border: 1rpx solid #ffccc7;
font-weight: 500;
}
.stock-info {
font-size: 24rpx;
color: #8c8c8c;
background-color: #f5f5f5;
padding: 4rpx 12rpx;
border-radius: 8rpx;
}
/* 价格变化箭头样式 */

13
pages/index/index.js

@ -434,6 +434,19 @@ Page({
// 跳转到物流运费估算页面
navigateToFreightCalculator() {
// 权限检查
if (!this.data.isInPersonnel) {
wx.showModal({
title: '权限不足',
content: '您没有权限使用此功能',
showCancel: false
});
return;
}
// 记录用户操作历史
API.addUserHistory('运费估算');
wx.navigateTo({
url: '/pages/freight-calculator/index',
success: function () {

8
pages/index/index.wxml

@ -214,14 +214,14 @@
<text class="function-btn-icon">📣</text>
<text class="function-btn-text">招商</text>
</view>
<view class="function-btn" bindtap="navigateToFreightCalculator" wx:if="{{isInPersonnel}}">
<text class="function-btn-icon">🚚</text>
<text class="function-btn-text">运费估算</text>
</view>
<view class="function-btn" bindtap="navigateToCompany">
<text class="function-btn-icon">📄</text>
<text class="function-btn-text">我们</text>
</view>
<view class="function-btn" bindtap="navigateToFreightCalculator">
<text class="function-btn-icon">🚚</text>
<text class="function-btn-text">运费估算</text>
</view>
</view>
<!-- 添加桌面引导框 -->

8
pages/index/index.wxss

@ -96,16 +96,15 @@ page {
/* 功能按钮样式 */
.function-buttons {
display: flex;
justify-content: space-around;
align-items: center;
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 10rpx;
padding: 10rpx 20rpx;
width: 100%;
max-width: 850rpx;
box-sizing: border-box;
background: #ffffff;
margin: 0 auto 16rpx;
gap: 5rpx;
border-radius: 12rpx;
box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
position: relative;
@ -113,7 +112,6 @@ page {
}
.function-btn {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;

4
pages/profile/index.wxml

@ -106,10 +106,10 @@
<view class="title">系统信息</view>
<view style="padding: 20rpx 0;">
<view style="font-size: 26rpx; color: #333; margin-bottom: 16rpx;">
当前版本:{{versionInfo.version || '2.6.230'}}
当前版本:{{versionInfo.version || '2.6.232'}}
</view>
<view style="font-size: 26rpx; color: #333; margin-bottom: 16rpx;">
上次更新:{{versionInfo.lastUpdate || '2026-02-26'}}
上次更新:{{versionInfo.lastUpdate || '2026-03-03'}}
</view>
</view>
</view>

589
server-example/server-mysql.js

@ -4,6 +4,149 @@ function getCurrentTime() {
return new Date();
}
// 运费计算辅助函数 - 计算运满满运费区间
function calculateYunmanmanFee(distance, weight, volume, vehicleType, truckLength) {
// 车长系数计算
const getTruckLengthFactor = (truckLength) => {
try {
const length = parseFloat(truckLength.replace('米', ''));
if (length <= 3.8) {
return 0.8;
} else if (length <= 4.2) {
return 0.9;
} else if (length <= 5) {
return 1.0;
} else if (length <= 6.8) {
return 1.1;
} else if (length <= 7.7) {
return 1.2;
} else if (length <= 9.6) {
return 1.3;
} else if (length <= 13) {
return 1.4;
} else {
return 1.5;
}
} catch {
return 1.0;
}
};
// 运满满收费标准
const rates = {
'面包车': {
startFee: 80,
startDistance: 10,
unitPriceMin: 1.0,
unitPriceMax: 1.3
},
'依维柯': {
startFee: 160,
startDistance: 10,
unitPriceMin: 1.5,
unitPriceMax: 1.8
},
'平板': {
startFee: 300,
startDistance: 10,
unitPriceMin: 2.5,
unitPriceMax: 2.9
},
'厢式': {
startFee: 220,
startDistance: 10,
unitPriceMin: 2.1,
unitPriceMax: 2.4
},
'高栏车': {
startFee: 200,
startDistance: 10,
unitPriceMin: 2.5,
unitPriceMax: 2.8
},
'集装箱': {
startFee: 300,
startDistance: 10,
unitPriceMin: 2.8,
unitPriceMax: 3.1
},
'自卸': {
startFee: 250,
startDistance: 10,
unitPriceMin: 2.2,
unitPriceMax: 2.5
},
'冷藏': {
startFee: 300,
startDistance: 10,
unitPriceMin: 2.5,
unitPriceMax: 2.8
},
'保温': {
startFee: 280,
startDistance: 10,
unitPriceMin: 2.3,
unitPriceMax: 2.6
},
'棉被车': {
startFee: 260,
startDistance: 10,
unitPriceMin: 2.2,
unitPriceMax: 2.5
},
'爬梯车': {
startFee: 280,
startDistance: 10,
unitPriceMin: 2.3,
unitPriceMax: 2.6
},
'飞翼车': {
startFee: 270,
startDistance: 10,
unitPriceMin: 2.2,
unitPriceMax: 2.5
},
'高低板': {
startFee: 350,
startDistance: 10,
unitPriceMin: 2.8,
unitPriceMax: 3.1
}
};
const rate = rates[vehicleType] || rates['平板'];
// 获取车长系数
const truckLengthFactor = getTruckLengthFactor(truckLength);
// 计算距离费用
let feeMin, feeMax;
if (distance <= rate.startDistance) {
feeMin = rate.startFee;
feeMax = rate.startFee;
} else {
const extraDistance = distance - rate.startDistance;
feeMin = rate.startFee + extraDistance * rate.unitPriceMin;
feeMax = rate.startFee + extraDistance * rate.unitPriceMax;
}
// 应用车长系数
feeMin *= truckLengthFactor;
feeMax *= truckLengthFactor;
// 根据货物重量和体积调整价格
if (weight > 1000 || volume > 10) {
feeMin *= 1.1;
feeMax *= 1.1;
}
// 添加平台佣金(运费的5%左右)
feeMin *= 1.05;
feeMax *= 1.05;
return [Math.floor(feeMin), Math.floor(feeMax)];
}
function getCurrentTimeISOString() {
return getCurrentTime().toISOString();
}
@ -131,7 +274,7 @@ app.post('/api/freight/calculate', (req, res) => {
console.log('===== 运费计算接口被调用 =====');
console.log('1. 收到请求体:', JSON.stringify(req.body, null, 2));
const { origin, destination, goodsInfo: originalGoodsInfo } = req.body;
const { origin, destination, goodsInfo: originalGoodsInfo, productId, userId, phoneNumber, vehicleInfo, transportMode, vehicleType, truckLength, packagingType } = req.body;
let goodsInfo = originalGoodsInfo;
// 验证参数
@ -149,10 +292,6 @@ app.post('/api/freight/calculate', (req, res) => {
goodsInfo = { ...goodsInfo, weight: 1 };
}
// 计算运费(使用默认费率,用户可根据自己的物流标准调整)
const baseRate = 0.5; // 默认基础费率(元/公里/公斤)
const weight = goodsInfo.weight || 1;
// 检查是否有经纬度信息
if (origin.latitude && origin.longitude && destination.latitude && destination.longitude) {
// 直接使用经纬度计算距离
@ -175,51 +314,124 @@ app.post('/api/freight/calculate', (req, res) => {
const response = JSON.parse(data);
console.log('腾讯地图API响应:', response);
if (response.status === 0 && response.result && response.result.elements && response.result.elements.length > 0) {
const distance = response.result.elements[0].distance / 1000; // 转换为公里
const freight = Math.floor(distance * baseRate * weight);
const deliveryTime = Math.ceil(distance / 200); // 公路:200公里/天
console.log('腾讯地图API距离计算成功,距离:', distance, '公里');
res.json({
success: true,
data: {
freight: freight,
let result;
if (response.status === 0 && response.result && response.result.rows && response.result.rows.length > 0) {
// 检查rows[0]是否有elements属性
const row = response.result.rows[0];
if (row.elements && row.elements.length > 0) {
const distance = row.elements[0].distance / 1000; // 转换为公里
// 计算运费区间
const [feeMin, feeMax] = calculateYunmanmanFee(distance, goodsInfo.weight || 1, goodsInfo.volume || 0, vehicleType || '平板', truckLength || '5米');
const deliveryTime = Math.ceil(distance / 80); // 公路:80公里/天
console.log('腾讯地图API距离计算成功,距离:', distance, '公里');
console.log('运费区间:', feeMin, '-', feeMax, '元');
result = {
freight: Math.floor((feeMin + feeMax) / 2), // 中间值
feeMin: feeMin,
feeMax: feeMax,
distance: Math.round(distance * 10) / 10, // 保留一位小数
deliveryTime: deliveryTime
}
});
};
} else {
console.error('腾讯地图API距离计算失败: 响应格式错误', response);
// 如果腾讯地图API调用失败,使用固定距离作为fallback
const distance = 200; // 示例距离:200公里
// 计算运费区间
const [feeMin, feeMax] = calculateYunmanmanFee(distance, goodsInfo.weight || 1, goodsInfo.volume || 0, vehicleType || '平板', truckLength || '5米');
const deliveryTime = Math.ceil(distance / 80); // 公路:80公里/天
result = {
freight: Math.floor((feeMin + feeMax) / 2), // 中间值
feeMin: feeMin,
feeMax: feeMax,
distance: distance,
deliveryTime: deliveryTime
};
}
} else {
console.error('腾讯地图API距离计算失败:', response);
// 如果腾讯地图API调用失败,使用固定距离作为fallback
const distance = 200; // 示例距离:200公里
const freight = Math.floor(distance * baseRate * weight);
const deliveryTime = Math.ceil(distance / 200); // 公路:200公里/天
// 计算运费区间
const [feeMin, feeMax] = calculateYunmanmanFee(distance, goodsInfo.weight || 1, goodsInfo.volume || 0, vehicleType || '平板', truckLength || '5米');
const deliveryTime = Math.ceil(distance / 80); // 公路:80公里/天
result = {
freight: Math.floor((feeMin + feeMax) / 2), // 中间值
feeMin: feeMin,
feeMax: feeMax,
distance: distance,
deliveryTime: deliveryTime
};
}
res.json({
success: true,
data: {
freight: freight,
distance: distance,
deliveryTime: deliveryTime
}
// 保存运费估算历史记录
if (userId && phoneNumber) {
FreightCalculationHistory.create({
productId: productId || '',
userId: userId,
phoneNumber: phoneNumber,
origin: JSON.stringify(origin),
destination: JSON.stringify(destination),
weight: goodsInfo.weight,
volume: goodsInfo.volume,
goodsInfo: JSON.stringify(goodsInfo),
vehicleInfo: vehicleInfo,
transportMode: transportMode,
result: JSON.stringify(result)
}).then(() => {
console.log('运费估算历史记录保存成功');
}).catch((error) => {
console.error('保存运费估算历史记录失败:', error);
});
}
} catch (error) {
console.error('处理腾讯地图API响应时出错:', error);
// 如果处理响应时出错,使用固定距离作为fallback
const distance = 200; // 示例距离:200公里
const freight = Math.floor(distance * baseRate * weight);
const deliveryTime = Math.ceil(distance / 200); // 公路:200公里/天
res.json({
success: true,
data: {
freight: freight,
data: result
});
} catch (error) {
console.error('处理腾讯地图API响应时出错:', error);
// 如果处理响应时出错,使用固定距离作为fallback
const distance = 200; // 示例距离:200公里
// 计算运费区间
const [feeMin, feeMax] = calculateYunmanmanFee(distance, goodsInfo.weight || 1, goodsInfo.volume || 0, vehicleType || '平板', truckLength || '5米');
const deliveryTime = Math.ceil(distance / 80); // 公路:80公里/天
const result = {
freight: Math.floor((feeMin + feeMax) / 2), // 中间值
feeMin: feeMin,
feeMax: feeMax,
distance: distance,
deliveryTime: deliveryTime
}
};
// 保存运费估算历史记录
if (userId && phoneNumber) {
FreightCalculationHistory.create({
productId: productId || '',
userId: userId,
phoneNumber: phoneNumber,
origin: JSON.stringify(origin),
destination: JSON.stringify(destination),
weight: goodsInfo.weight,
volume: goodsInfo.volume,
goodsInfo: JSON.stringify(goodsInfo),
vehicleInfo: vehicleInfo,
transportMode: transportMode,
result: JSON.stringify(result)
}).then(() => {
console.log('运费估算历史记录保存成功');
}).catch((error) => {
console.error('保存运费估算历史记录失败:', error);
});
}
res.json({
success: true,
data: result
});
}
});
@ -227,31 +439,83 @@ app.post('/api/freight/calculate', (req, res) => {
console.error('腾讯地图API调用失败:', error);
// 如果API调用失败,使用固定距离作为fallback
const distance = 200; // 示例距离:200公里
const freight = Math.floor(distance * baseRate * weight);
const deliveryTime = Math.ceil(distance / 200); // 公路:200公里/天
// 计算运费区间
const [feeMin, feeMax] = calculateYunmanmanFee(distance, goodsInfo.weight || 1, goodsInfo.volume || 0, vehicleType || '平板', truckLength || '5米');
const deliveryTime = Math.ceil(distance / 80); // 公路:80公里/天
const result = {
freight: Math.floor((feeMin + feeMax) / 2), // 中间值
feeMin: feeMin,
feeMax: feeMax,
distance: distance,
deliveryTime: deliveryTime
};
// 保存运费估算历史记录
if (userId && phoneNumber) {
FreightCalculationHistory.create({
productId: productId || '',
userId: userId,
phoneNumber: phoneNumber,
origin: JSON.stringify(origin),
destination: JSON.stringify(destination),
weight: goodsInfo.weight,
volume: goodsInfo.volume,
goodsInfo: JSON.stringify(goodsInfo),
vehicleInfo: vehicleInfo,
transportMode: transportMode,
result: JSON.stringify(result)
}).then(() => {
console.log('运费估算历史记录保存成功');
}).catch((error) => {
console.error('保存运费估算历史记录失败:', error);
});
}
res.json({
success: true,
data: {
freight: freight,
distance: distance,
deliveryTime: deliveryTime
}
data: result
});
});
} else {
// 没有经纬度信息,使用固定距离作为fallback
const distance = 200; // 示例距离:200公里
const freight = Math.floor(distance * baseRate * weight);
const deliveryTime = Math.ceil(distance / 200); // 公路:200公里/天
// 计算运费区间
const [feeMin, feeMax] = calculateYunmanmanFee(distance, goodsInfo.weight || 1, goodsInfo.volume || 0, vehicleType || '平板', truckLength || '5米');
const deliveryTime = Math.ceil(distance / 80); // 公路:80公里/天
const result = {
freight: Math.floor((feeMin + feeMax) / 2), // 中间值
feeMin: feeMin,
feeMax: feeMax,
distance: distance,
deliveryTime: deliveryTime
};
// 保存运费估算历史记录
if (userId && phoneNumber) {
FreightCalculationHistory.create({
productId: productId || '',
userId: userId,
phoneNumber: phoneNumber,
origin: JSON.stringify(origin),
destination: JSON.stringify(destination),
weight: goodsInfo.weight,
volume: goodsInfo.volume,
goodsInfo: JSON.stringify(goodsInfo),
vehicleInfo: vehicleInfo,
transportMode: transportMode,
result: JSON.stringify(result)
}).then(() => {
console.log('运费估算历史记录保存成功');
}).catch((error) => {
console.error('保存运费估算历史记录失败:', error);
});
}
res.json({
success: true,
data: {
freight: freight,
distance: distance,
deliveryTime: deliveryTime
}
data: result
});
}
@ -264,6 +528,75 @@ app.post('/api/freight/calculate', (req, res) => {
}
});
// 获取运费估算历史记录接口
app.get('/api/freight/history', async (req, res) => {
try {
console.log('===== 获取运费估算历史记录接口被调用 =====');
console.log('1. 收到查询参数:', req.query);
const { userId, productId, page = 1, pageSize = 10 } = req.query;
// 构建查询条件
const whereCondition = {};
if (userId) {
whereCondition.userId = userId;
}
if (productId) {
whereCondition.productId = productId;
}
// 计算分页偏移量
const offset = (parseInt(page) - 1) * parseInt(pageSize);
// 查询历史记录
const historyRecords = await FreightCalculationHistory.findAll({
where: whereCondition,
order: [['created_at', 'DESC']],
limit: parseInt(pageSize),
offset: offset
});
// 计算总记录数
const totalCount = await FreightCalculationHistory.count({
where: whereCondition
});
// 格式化响应数据
const formattedRecords = historyRecords.map(record => {
const recordData = record.toJSON();
try {
recordData.origin = JSON.parse(recordData.origin);
recordData.destination = JSON.parse(recordData.destination);
recordData.goodsInfo = JSON.parse(recordData.goodsInfo);
recordData.result = JSON.parse(recordData.result);
} catch (error) {
console.error('解析JSON字段失败:', error);
}
return recordData;
});
res.json({
success: true,
data: {
records: formattedRecords,
pagination: {
page: parseInt(page),
pageSize: parseInt(pageSize),
total: totalCount,
totalPages: Math.ceil(totalCount / parseInt(pageSize))
}
}
});
} catch (error) {
console.error('获取运费估算历史记录失败:', error);
res.status(500).json({
success: false,
message: '获取运费估算历史记录失败: ' + error.message
});
}
});
// Eggbar 帖子创建接口
app.post('/api/eggbar/posts', async (req, res) => {
@ -1712,6 +2045,11 @@ User.init({
followup: {
type: DataTypes.TEXT // 临时跟进
},
followup_at: {
type: DataTypes.DATE, // 跟进时间
defaultValue: null,
comment: '跟进时间'
},
notice: {
type: DataTypes.STRING(255) // 通知提醒
},
@ -1779,7 +2117,7 @@ Product.init({
allowNull: false
},
region: {
type: DataTypes.STRING(100),
type: DataTypes.STRING(255),
},
price: {
type: DataTypes.STRING(10),
@ -2770,6 +3108,105 @@ UserFollowupHistory.init({
timestamps: false
});
// 定义运费估算历史记录模型
class FreightCalculationHistory extends Model { }
FreightCalculationHistory.init({
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
productId: {
type: DataTypes.STRING(100),
allowNull: true,
defaultValue: null,
comment: '产品id'
},
userId: {
type: DataTypes.STRING(100),
allowNull: false,
comment: '用户id'
},
phoneNumber: {
type: DataTypes.STRING(20),
allowNull: false,
comment: '电话号码'
},
origin: {
type: DataTypes.STRING(255),
defaultValue: '',
comment: '出发地信息'
},
destination: {
type: DataTypes.STRING(255),
defaultValue: '',
comment: '目的地信息'
},
weight: {
type: DataTypes.DECIMAL(10, 2),
allowNull: true,
comment: '货物重量(kg)'
},
volume: {
type: DataTypes.DECIMAL(10, 2),
allowNull: true,
comment: '货物体积(m³)'
},
goodsInfo: {
type: DataTypes.TEXT,
allowNull: false,
comment: '货物信息'
},
vehicleInfo: {
type: DataTypes.STRING(255),
allowNull: true,
comment: '车型信息'
},
transportMode: {
type: DataTypes.STRING(50),
allowNull: true,
comment: '运输模式'
},
result: {
type: DataTypes.TEXT,
allowNull: false,
comment: '计算结果'
},
created_at: {
type: DataTypes.DATE,
defaultValue: Sequelize.NOW,
comment: '创建时间'
},
updated_at: {
type: DataTypes.DATE,
defaultValue: Sequelize.NOW,
onUpdate: Sequelize.NOW,
comment: '更新时间'
}
}, {
sequelize,
modelName: 'FreightCalculationHistory',
tableName: 'freight_calculation_history',
timestamps: false,
indexes: [
{
fields: ['productId'],
name: 'idx_productId',
comment: '产品ID索引'
},
{
fields: ['created_at'],
name: 'idx_created_at',
comment: '创建时间索引'
},
{
fields: ['productId', 'created_at'],
name: 'idx_productId_created_at',
comment: '产品ID和创建时间联合索引'
}
]
});
// 定义模型之间的关联关系
// 用户和商品的一对多关系 (卖家发布商品)
@ -3909,6 +4346,43 @@ app.post('/api/user/update', async (req, res) => {
}
});
// 记录用户操作历史
app.post('/api/user-history/add', async (req, res) => {
try {
const { phone, operation } = req.body;
if (!phone || !operation) {
return res.status(400).json({
success: false,
code: 400,
message: '缺少必要参数phone或operation'
});
}
// 创建用户操作历史记录
await sequelize.query(
`INSERT INTO use_history (phone, operation, time) VALUES (?, ?, ?)`,
{
replacements: [phone, operation, getCurrentTime()]
}
);
res.json({
success: true,
code: 200,
message: '操作记录添加成功'
});
} catch (error) {
console.error('添加操作记录失败:', error);
res.status(500).json({
success: false,
code: 500,
message: '添加操作记录失败',
error: error.message
});
}
});
// 获取商品分类列表 - 返回不重复的分类
app.get('/api/product/categories', async (req, res) => {
try {
@ -6139,33 +6613,34 @@ app.post('/api/products/detail', async (req, res) => {
attributes: ['user_id', 'created_at']
});
// 提取浏览用户的user_id列表
const userIds = userViews.map(view => view.user_id);
// 提取浏览用户的user_id列表并去重,避免重复处理同一用户
const userIds = [...new Set(userViews.map(view => view.user_id))];
// 查询这些用户的电话号码和跟进记录
let viewerInfo = [];
if (userIds.length > 0) {
// 查询用户信息,包括followup和type字段
// 查询用户信息,包括followup、followup_at和type字段
const users = await User.findAll({
where: {
userId: {
[Sequelize.Op.in]: userIds
}
},
attributes: ['userId', 'phoneNumber', 'nickName', 'followup', 'type']
attributes: ['userId', 'phoneNumber', 'nickName', 'followup', 'followup_at', 'type']
});
// 构建浏览用户信息
userIds.forEach(userId => {
const user = users.find(u => u.userId === userId);
if (user) {
// 构建跟进记录,使用users表中的followup字段
// 构建跟进记录,使用users表中的followup字段和followup_at字段
const followupRecords = [];
if (user.followup) {
followupRecords.push({
content: user.followup,
phoneNumber: user.phoneNumber,
createdAt: new Date() // 使用当前时间
followup_at: user.followup_at, // 传递followup_at字段
createdAt: user.followup_at || new Date() // 优先使用followup_at,否则使用当前时间
});
}

479
utils/api.js

@ -1165,6 +1165,49 @@ module.exports = {
});
},
// 记录用户操作历史
addUserHistory: function (operation) {
console.log('API.addUserHistory - 操作类型:', operation);
// 获取用户手机号
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);
}
if (!userPhone) {
console.warn('用户未登录,无法记录操作历史');
return Promise.resolve({ success: false, message: '用户未登录' });
}
const requestData = {
phone: userPhone,
operation: operation
};
return request('/api/user-history/add', 'POST', requestData).then(res => {
console.log('操作历史记录成功:', res);
return res;
}).catch(err => {
console.error('操作历史记录失败:', err);
// 即使记录失败,也不影响主流程
return { success: false, message: '操作历史记录失败' };
});
},
// 计算物流运费
calculateFreight: function (params) {
console.log('API.calculateFreight - 开始计算运费');
@ -1183,290 +1226,56 @@ module.exports = {
params.goodsInfo.weight = 1;
}
// 直接使用腾讯地图API计算真实距离
return new Promise((resolve, reject) => {
// 定义获取经纬度的函数
function getCoordinates(address) {
return new Promise((resolve, reject) => {
wx.request({
url: 'https://apis.map.qq.com/ws/geocoder/v1/',
data: {
address: address,
key: 'OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77'
},
success: function (response) {
if (response.data.status === 0 && response.data.result && response.data.result.location) {
resolve({
latitude: response.data.result.location.lat,
longitude: response.data.result.location.lng
});
} else {
reject(new Error('地址解析失败'));
}
},
fail: function (err) {
reject(err);
}
});
});
}
// 检查是否有经纬度信息
if (params.origin.latitude && params.origin.longitude && params.destination.latitude && params.destination.longitude) {
// 直接使用经纬度计算距离
const origin = `${params.origin.latitude},${params.origin.longitude}`;
const destination = `${params.destination.latitude},${params.destination.longitude}`;
wx.request({
url: 'https://apis.map.qq.com/ws/distance/v1/matrix',
data: {
mode: 'driving',
from: origin,
to: destination,
key: 'OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77'
},
success: function (response) {
console.log('腾讯地图API距离计算成功:', response);
console.log('腾讯地图API响应状态:', response.data.status);
console.log('腾讯地图API响应结果:', response.data.result);
if (response.data.status === 0 && response.data.result) {
// 检查result结构,适应不同的API响应格式
let distance;
try {
// 优先检查 rows 字段(腾讯地图 API 的标准格式)
if (response.data.result.rows && response.data.result.rows.length > 0) {
const row = response.data.result.rows[0];
if (row.elements && row.elements.length > 0) {
distance = row.elements[0].distance / 1000; // 转换为公里
}
}
// 然后检查 elements 字段
else if (response.data.result.elements && response.data.result.elements.length > 0) {
distance = response.data.result.elements[0].distance / 1000; // 转换为公里
}
// 最后检查 distance 字段
else if (response.data.result.distance) {
distance = response.data.result.distance / 1000; // 转换为公里
}
// 如果都没有,抛出错误
else {
console.error('无法获取距离数据,响应结构:', response.data.result);
throw new Error('无法获取距离数据');
}
const baseRate = 0.5; // 默认基础费率(元/公里/公斤)
const weight = params.goodsInfo.weight || 1;
const freight = Math.floor(distance * baseRate * weight);
const deliveryTime = Math.ceil(distance / 200); // 公路:200公里/天
console.log('腾讯地图API距离计算成功,距离:', distance, '公里');
// 获取用户信息
const userId = wx.getStorageSync('userId');
const userInfo = wx.getStorageSync('userInfo');
const phoneNumber = userInfo?.phoneNumber || wx.getStorageSync('phoneNumber');
resolve({
success: true,
data: {
freight: freight,
distance: Math.round(distance * 10) / 10, // 保留一位小数
deliveryTime: deliveryTime
}
});
} catch (error) {
console.error('处理距离数据时出错:', error);
// 如果处理距离数据时出错,使用随机数据作为fallback
const mockDistance = Math.floor(Math.random() * 1000) + 100; // 100-1100公里
const baseRate = 0.5;
const weight = params.goodsInfo.weight || 1;
const mockFreight = Math.floor(mockDistance * baseRate * weight);
const mockDeliveryTime = Math.ceil(mockDistance / 200);
resolve({
success: true,
data: {
freight: mockFreight,
distance: mockDistance,
deliveryTime: mockDeliveryTime
}
});
}
} else {
console.error('腾讯地图API距离计算失败:', response.data);
// 如果腾讯地图API调用失败,使用随机数据作为fallback
const mockDistance = Math.floor(Math.random() * 1000) + 100; // 100-1100公里
const baseRate = 0.5;
const weight = params.goodsInfo.weight || 1;
const mockFreight = Math.floor(mockDistance * baseRate * weight);
const mockDeliveryTime = Math.ceil(mockDistance / 200);
resolve({
success: true,
data: {
freight: mockFreight,
distance: mockDistance,
deliveryTime: mockDeliveryTime
}
});
}
},
fail: function (err) {
console.error('腾讯地图API调用失败:', err);
// 如果API调用失败,使用随机数据作为fallback
const mockDistance = Math.floor(Math.random() * 1000) + 100; // 100-1100公里
const baseRate = 0.5;
const weight = params.goodsInfo.weight || 1;
const mockFreight = Math.floor(mockDistance * baseRate * weight);
const mockDeliveryTime = Math.ceil(mockDistance / 200);
// 构建请求数据
const requestData = {
...params,
userId: userId,
phoneNumber: phoneNumber
};
resolve({
success: true,
data: {
freight: mockFreight,
distance: mockDistance,
deliveryTime: mockDeliveryTime
}
});
}
});
// 调用后端API计算运费
return request('/api/freight/calculate', 'POST', requestData).then(res => {
console.log('API.calculateFreight - 后端响应:', res);
if (res && res.success) {
return res;
} else {
// 没有经纬度信息,先进行地址解析
const originAddress = `${params.origin.province}${params.origin.city}${params.origin.district}${params.origin.detail}`;
const destinationAddress = `${params.destination.province}${params.destination.city}${params.destination.district}${params.destination.detail}`;
Promise.all([
getCoordinates(originAddress),
getCoordinates(destinationAddress)
]).then(([originCoords, destinationCoords]) => {
// 使用解析得到的经纬度计算距离
const origin = `${originCoords.latitude},${originCoords.longitude}`;
const destination = `${destinationCoords.latitude},${destinationCoords.longitude}`;
wx.request({
url: 'https://apis.map.qq.com/ws/distance/v1/matrix',
data: {
mode: 'driving',
from: origin,
to: destination,
key: 'OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77'
},
success: function (response) {
console.log('腾讯地图API距离计算成功:', response);
console.log('腾讯地图API响应状态:', response.data.status);
console.log('腾讯地图API响应结果:', response.data.result);
if (response.data.status === 0 && response.data.result) {
// 检查result结构,适应不同的API响应格式
let distance;
try {
// 优先检查 rows 字段(腾讯地图 API 的标准格式)
if (response.data.result.rows && response.data.result.rows.length > 0) {
const row = response.data.result.rows[0];
if (row.elements && row.elements.length > 0) {
distance = row.elements[0].distance / 1000; // 转换为公里
}
}
// 然后检查 elements 字段
else if (response.data.result.elements && response.data.result.elements.length > 0) {
distance = response.data.result.elements[0].distance / 1000; // 转换为公里
}
// 最后检查 distance 字段
else if (response.data.result.distance) {
distance = response.data.result.distance / 1000; // 转换为公里
}
// 如果都没有,抛出错误
else {
console.error('无法获取距离数据,响应结构:', response.data.result);
throw new Error('无法获取距离数据');
}
const baseRate = 0.5; // 默认基础费率(元/公里/公斤)
const weight = params.goodsInfo.weight || 1;
const freight = Math.floor(distance * baseRate * weight);
const deliveryTime = Math.ceil(distance / 200); // 公路:200公里/天
console.log('腾讯地图API距离计算成功,距离:', distance, '公里');
throw new Error(res?.message || '运费计算失败');
}
}).catch(err => {
console.error('API.calculateFreight - 计算运费失败:', err);
throw err;
});
},
resolve({
success: true,
data: {
freight: freight,
distance: Math.round(distance * 10) / 10, // 保留一位小数
deliveryTime: deliveryTime
}
});
} catch (error) {
console.error('处理距离数据时出错:', error);
// 如果处理距离数据时出错,使用随机数据作为fallback
const mockDistance = Math.floor(Math.random() * 1000) + 100; // 100-1100公里
const baseRate = 0.5;
const weight = params.goodsInfo.weight || 1;
const mockFreight = Math.floor(mockDistance * baseRate * weight);
const mockDeliveryTime = Math.ceil(mockDistance / 200);
resolve({
success: true,
data: {
freight: mockFreight,
distance: mockDistance,
deliveryTime: mockDeliveryTime
}
});
}
} else {
console.error('腾讯地图API距离计算失败:', response.data);
// 如果腾讯地图API调用失败,使用随机数据作为fallback
const mockDistance = Math.floor(Math.random() * 1000) + 100; // 100-1100公里
const baseRate = 0.5;
const weight = params.goodsInfo.weight || 1;
const mockFreight = Math.floor(mockDistance * baseRate * weight);
const mockDeliveryTime = Math.ceil(mockDistance / 200);
resolve({
success: true,
data: {
freight: mockFreight,
distance: mockDistance,
deliveryTime: mockDeliveryTime
}
});
}
},
fail: function (err) {
console.error('腾讯地图API调用失败:', err);
// 如果API调用失败,使用随机数据作为fallback
const mockDistance = Math.floor(Math.random() * 1000) + 100; // 100-1100公里
const baseRate = 0.5;
const weight = params.goodsInfo.weight || 1;
const mockFreight = Math.floor(mockDistance * baseRate * weight);
const mockDeliveryTime = Math.ceil(mockDistance / 200);
resolve({
success: true,
data: {
freight: mockFreight,
distance: mockDistance,
deliveryTime: mockDeliveryTime
}
});
}
});
}).catch(err => {
console.error('地址解析失败:', err);
// 如果地址解析失败,使用随机数据作为fallback
const mockDistance = Math.floor(Math.random() * 1000) + 100; // 100-1100公里
const baseRate = 0.5;
const weight = params.goodsInfo.weight || 1;
const mockFreight = Math.floor(mockDistance * baseRate * weight);
const mockDeliveryTime = Math.ceil(mockDistance / 200);
// 获取运费估算历史记录
getFreightHistory: function (params) {
console.log('API.getFreightHistory - 获取运费估算历史记录');
console.log('API.getFreightHistory - 参数:', params);
// 构建查询参数
const queryParams = {
userId: params?.userId || wx.getStorageSync('userId'),
productId: params?.productId,
page: params?.page || 1,
pageSize: params?.pageSize || 10
};
resolve({
success: true,
data: {
freight: mockFreight,
distance: mockDistance,
deliveryTime: mockDeliveryTime
}
});
});
// 调用后端API获取历史记录
return request('/api/freight/history', 'GET', queryParams).then(res => {
console.log('API.getFreightHistory - 后端响应:', res);
if (res && res.success) {
return res;
} else {
throw new Error(res?.message || '获取运费估算历史记录失败');
}
}).catch(err => {
console.error('API.getFreightHistory - 获取历史记录失败:', err);
throw err;
});
},
@ -5013,5 +4822,119 @@ module.exports = {
reject(error);
});
});
},
// 通过规格查找不同规格的数据
getProductsBySpecification: function (specification) {
console.log('API.getProductsBySpecification - specification:', specification);
return new Promise((resolve, reject) => {
// 使用getProducts接口获取所有商品,然后在客户端过滤
this.getProducts(1, 100, 'all', '').then(res => {
console.log('获取商品列表成功:', res);
if (res && res.products) {
// 过滤出具有相同规格的商品
const filteredProducts = res.products.filter(item => {
// 检查多个可能存储重量信息的字段
const fieldsToCheck = [
item.specification,
item.grossWeight,
item.weightQuantityData,
item.spec // 检查spec字段
];
let hasMatchingSpec = false;
for (const field of fieldsToCheck) {
if (!field) continue;
if (typeof field === 'string') {
// 处理字符串格式的规格数据
console.log('检查字符串规格:', field, '是否包含', specification);
// 处理逗号分隔的规格字符串
const specs = field.split(/[,,、]/).map(s => s.trim());
if (specs.some(spec => spec.includes(specification))) {
hasMatchingSpec = true;
break;
}
} else if (Array.isArray(field)) {
// 处理数组格式的规格数据
console.log('检查数组规格:', field);
if (field.some(spec => {
if (typeof spec === 'string') {
console.log('检查数组元素(字符串):', spec, '是否包含', specification);
return spec.includes(specification);
} else if (typeof spec === 'object') {
// 检查对象格式的规格数据
const specStr = spec.weightSpec || spec.display || spec.spec || '';
console.log('检查数组元素(对象):', specStr, '是否包含', specification);
return specStr.includes(specification);
}
return false;
})) {
hasMatchingSpec = true;
break;
}
} else if (typeof field === 'object') {
// 处理对象格式的规格数据
console.log('检查对象规格:', field);
const specStr = field.weightSpec || field.display || field.spec || '';
console.log('检查对象规格值:', specStr, '是否包含', specification);
if (specStr.includes(specification)) {
hasMatchingSpec = true;
break;
}
}
}
// 如果没有找到匹配的规格,尝试进行更宽松的匹配
if (!hasMatchingSpec) {
console.log('尝试更宽松的匹配...');
// 提取规格中的数字部分进行匹配
const weightNum = specification.replace(/[^0-9-]/g, '');
console.log('提取的重量数字:', weightNum);
for (const field of fieldsToCheck) {
if (!field) continue;
if (typeof field === 'string') {
console.log('检查字符串字段:', field, '是否包含', weightNum);
if (field.includes(weightNum)) {
hasMatchingSpec = true;
break;
}
} else if (Array.isArray(field)) {
console.log('检查数组字段:', field);
if (field.some(spec => {
const specStr = typeof spec === 'string' ? spec : (spec.weightSpec || spec.display || spec.spec || '');
console.log('检查数组元素:', specStr, '是否包含', weightNum);
return specStr.includes(weightNum);
})) {
hasMatchingSpec = true;
break;
}
} else if (typeof field === 'object') {
console.log('检查对象字段:', field);
const specStr = field.weightSpec || field.display || field.spec || '';
console.log('检查对象字段值:', specStr, '是否包含', weightNum);
if (specStr.includes(weightNum)) {
hasMatchingSpec = true;
break;
}
}
}
}
return hasMatchingSpec;
});
console.log('过滤后的商品数量:', filteredProducts.length);
console.log('过滤后的商品:', filteredProducts);
resolve(filteredProducts);
} else {
reject(new Error('通过规格查找商品失败'));
}
}).catch(error => {
console.error('通过规格查找商品失败:', error);
reject(new Error('通过规格查找商品失败,请稍后重试'));
});
});
}
};
Loading…
Cancel
Save