You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

1680 lines
58 KiB

// pages/goods-detail/goods-detail.js
const API = require('../../utils/api.js')
// 根据sourceType获取对应的颜色
function getSourceTypeColor(sourceType) {
const colorMap = {
'三方认证': '#4d9dff',
'三方未认证': '#ff4d4f',
'平台货源': '#2ad21f'
};
return colorMap[sourceType] || '#4d9dff';
}
// 媒体类型判断函数
function isVideoUrl(url) {
if (!url || typeof url !== 'string') {
return false;
}
// 转换为小写,确保大小写不敏感
const lowerUrl = url.toLowerCase();
// 支持的视频格式
const videoExtensions = ['.mp4', '.mov', '.avi', '.wmv', '.flv', '.webm', '.m4v', '.3gp'];
// 检查URL是否以视频扩展名结尾
for (const ext of videoExtensions) {
if (lowerUrl.endsWith(ext)) {
return true;
}
}
return false;
}
// 预处理媒体URL,返回包含type字段的媒体对象数组
function processMediaUrls(urls) {
if (!urls || !Array.isArray(urls)) {
return [];
}
return urls.map(url => {
return {
url: url,
type: isVideoUrl(url) ? 'video' : 'image'
};
});
}
// 格式化毛重显示的辅助函数
function formatGrossWeight(grossWeight, weight) {
console.log('===== formatGrossWeight 函数调用 =====');
console.log('输入参数:');
console.log('- grossWeight:', grossWeight, '(类型:', typeof grossWeight, ')');
console.log('- weight:', weight, '(类型:', typeof weight, ')');
// 1. 优先使用grossWeight,只要它不是null、不是undefined、不是空字符串
if (grossWeight !== null && grossWeight !== undefined && grossWeight !== '') {
console.log('使用grossWeight参数');
return grossWeight;
}
// 如果grossWeight无效,尝试使用weight字段
if (weight !== null && weight !== undefined && weight !== '') {
console.log('使用weight参数');
return weight;
}
// 3. 新增逻辑:如果grossWeight和weight都无效,返回空字符串以支持文字输入
console.log('两个参数都无效,返回空字符串');
return "";
}
// 提取地区中的省份信息
function extractProvince(region) {
if (!region || typeof region !== 'string') {
return region;
}
// 查找各种省份格式的位置
const provinceEndIndex = region.indexOf('省');
const autonomousRegionEndIndex = region.indexOf('自治区');
const municipalityEndIndex = region.indexOf('市'); // 用于直辖市,如北京市、上海市
const specialRegionEndIndex = region.indexOf('特别行政区'); // 用于香港、澳门
if (provinceEndIndex !== -1) {
// 包含"省"字,提取到"省"字结束
return region.substring(0, provinceEndIndex + 1);
} else if (autonomousRegionEndIndex !== -1) {
// 包含"自治区",提取到"自治区"结束
return region.substring(0, autonomousRegionEndIndex + 3);
} else if (specialRegionEndIndex !== -1) {
// 包含"特别行政区",提取到"特别行政区"结束
return region.substring(0, specialRegionEndIndex + 5);
} else if (municipalityEndIndex === 2) {
// 直辖市(如北京市、上海市),市字在第2个字符位置
return region.substring(0, municipalityEndIndex + 1);
}
// 如果没有找到匹配的格式,返回原字符串
return region;
}
// 检查用户是否已经登录
function checkLoginStatus() {
const openid = wx.getStorageSync('openid');
const userId = wx.getStorageSync('userId');
console.log('检查登录状态:', {
openid: openid ? '已登录' : '未登录',
userId: userId ? '已设置' : '未设置'
});
return !!(openid && userId);
}
// 处理净重、件数和规格数据,将逗号分隔的字符串转换为一一对应的数组
function processWeightAndQuantityData(weightSpecString, quantityString, specString) {
console.log('===== 处理净重、件数和规格数据 =====');
console.log('输入参数:');
console.log('- weightSpecString:', weightSpecString, '(类型:', typeof weightSpecString, ')');
console.log('- quantityString:', quantityString, '(类型:', typeof quantityString, ')');
console.log('- specString:', specString, '(类型:', typeof specString, ')');
// 如果没有数据,返回空数组
if (!weightSpecString && !quantityString && !specString) {
console.log('没有数据,返回空数组');
return [];
}
// 处理净重/规格字符串(它可能包含净重信息)
let weightSpecArray = [];
if (weightSpecString && typeof weightSpecString === 'string') {
// 支持多种逗号分隔符:英文逗号、中文逗号、全角逗号
weightSpecArray = weightSpecString.split(/[,,、]/).map(item => item.trim()).filter(item => item);
console.log('从字符串分割得到净重规格数组:', weightSpecArray);
} else if (weightSpecString) {
weightSpecArray = [String(weightSpecString)];
console.log('将净重规格转换为数组:', weightSpecArray);
}
// 处理件数字符串
let quantityArray = [];
if (quantityString && typeof quantityString === 'string') {
// 支持多种逗号分隔符:英文逗号、中文逗号、全角逗号
quantityArray = quantityString.split(/[,,、]/).map(item => item.trim()).filter(item => item);
console.log('从字符串分割得到数量数组:', quantityArray);
} else if (quantityString) {
quantityArray = [String(quantityString)];
console.log('将数量转换为数组:', quantityArray);
}
// 获取最大长度,确保一一对应
const maxLength = Math.max(weightSpecArray.length, quantityArray.length);
console.log('最大长度:', maxLength);
const result = [];
for (let i = 0; i < maxLength; i++) {
const weightSpec = weightSpecArray[i] || '';
const quantity = quantityArray[i] || '';
console.log(`处理第${i}组数据: weightSpec=${weightSpec}, quantity=${quantity}`);
// 处理净重规格显示格式 - 根据内容类型添加相应前缀
let weightSpecDisplay = '';
if (weightSpec) {
if (weightSpec.includes('净重')) {
// 如果已包含"净重"前缀,保持不变
weightSpecDisplay = weightSpec;
} else if (weightSpec.includes('毛重')) {
// 如果已包含"毛重"前缀,保持不变
weightSpecDisplay = weightSpec;
} else {
// 如果都不包含,默认为净重
weightSpecDisplay = `净重${weightSpec}`;
}
}
// 组合显示:格式为"净重信息————件数"
let display = '';
if (weightSpecDisplay && quantity) {
display = `${weightSpecDisplay}————${quantity}`;
} else if (weightSpecDisplay) {
display = weightSpecDisplay;
} else if (quantity) {
display = `${quantity}`;
}
console.log(`${i}组数据处理结果: weightSpecDisplay=${weightSpecDisplay}, quantity=${quantity}, display=${display}`);
result.push({
weightSpec: weightSpecDisplay,
quantity: quantity,
display: display
});
}
console.log('最终处理结果:', result);
return result;
}
Page({
// 分享给朋友/群聊
onShareAppMessage() {
const goodsDetail = this.data.goodsDetail || {};
const title = goodsDetail.name ? `优质鸡蛋 - ${goodsDetail.name}` : '优质鸡蛋货源';
// 获取联系人、电话号码和地区信息
const contactName = goodsDetail.product_contact || '';
const contactPhone = goodsDetail.contact_phone || '';
const region = goodsDetail.region || '';
// 构建包含联系人信息的分享路径
const contactNameParam = encodeURIComponent(contactName);
const contactPhoneParam = encodeURIComponent(contactPhone);
const regionParam = encodeURIComponent(region);
// 如果有联系人或地区信息,则添加到分享路径
let sharePath = `/pages/goods-detail/goods-detail?productId=${goodsDetail.id || goodsDetail.productId}`;
if (contactName && contactPhone && region) {
sharePath += `&contactName=${contactNameParam}&contactPhone=${contactPhoneParam}&region=${regionParam}`;
} else if (contactName && contactPhone) {
sharePath += `&contactName=${contactNameParam}&contactPhone=${contactPhoneParam}`;
} else if (contactName && region) {
sharePath += `&contactName=${contactNameParam}&region=${regionParam}`;
} else if (contactPhone && region) {
sharePath += `&contactPhone=${contactPhoneParam}&region=${regionParam}`;
} else if (contactName) {
sharePath += `&contactName=${contactNameParam}`;
} else if (contactPhone) {
sharePath += `&contactPhone=${contactPhoneParam}`;
} else if (region) {
sharePath += `&region=${regionParam}`;
}
return {
title: title,
path: sharePath,
imageUrl: goodsDetail.imageUrls && goodsDetail.imageUrls.length > 0 ? goodsDetail.imageUrls[0] : '/images/你有好蛋.png'
}
},
// 分享到朋友圈
onShareTimeline() {
const goodsDetail = this.data.goodsDetail || {};
const title = goodsDetail.name ? `优质鸡蛋 - ${goodsDetail.name}` : '优质鸡蛋货源';
// 获取联系人、电话号码和地区信息
const contactName = goodsDetail.product_contact || '';
const contactPhone = goodsDetail.contact_phone || '';
const region = goodsDetail.region || '';
// 构建分享查询参数
const contactNameParam = encodeURIComponent(contactName);
const contactPhoneParam = encodeURIComponent(contactPhone);
const regionParam = encodeURIComponent(region);
let queryParams = [`productId=${goodsDetail.id || goodsDetail.productId}`];
// 添加联系人信息到查询参数
if (contactName) {
queryParams.push(`contactName=${contactNameParam}`);
}
if (contactPhone) {
queryParams.push(`contactPhone=${contactPhoneParam}`);
}
if (region) {
queryParams.push(`region=${regionParam}`);
}
const contactQuery = queryParams.join('&');
return {
title: title,
query: contactQuery,
imageUrl: goodsDetail.imageUrls && goodsDetail.imageUrls.length > 0 ? goodsDetail.imageUrls[0] : '/images/你有好蛋.png'
}
},
data: {
goodsDetail: {}, // 当前商品详情
showImagePreview: false, // 控制图片预览弹窗显示
previewImageUrls: [], // 预览的图片URL列表
previewImageIndex: 0, // 当前预览图片的索引
fromSeller: false, // 是否来自seller页面
isFavorite: false, // 当前商品是否已收藏
// 登录弹窗状态
showOneKeyLoginModal: false, // 是否显示登录弹窗
// 图片缩放相关状态
scale: 1, // 当前缩放比例
lastScale: 1, // 上一次缩放比例
startDistance: 0, // 双指起始距离
doubleTapTimer: null, // 双击计时器
lastTapTime: 0, // 上一次单击时间
isScaling: false, // 是否正在缩放中
offsetX: 0, // X轴偏移量
offsetY: 0, // Y轴偏移量
initialTouch: null, // 初始触摸点
},
onLoad: function (options) {
console.log('商品详情页面加载,参数:', options);
// 处理登录状态检查 - 优化版:优先检查本地登录状态
console.log('开始检查登录状态...');
// 1. 首先检查用户是否已经登录
const isLoggedIn = checkLoginStatus();
// 2. 检查URL参数中的needLogin
const needLoginFromUrl = (options.needLogin === 'true' || options.needLogin === true);
console.log('登录状态检查结果:', {
isLoggedIn,
needLoginFromUrl
});
// 只有在用户未登录且URL参数明确要求登录时才显示登录弹窗
if (!isLoggedIn && needLoginFromUrl) {
console.log('检测到需要登录且用户未登录,显示登录提示弹窗');
// 延迟显示登录弹窗,确保页面完全加载
setTimeout(() => {
this.setData({
showOneKeyLoginModal: true
});
}, 500);
} else {
console.log('不需要显示登录弹窗:', {
reason: isLoggedIn ? '用户已登录' : 'URL参数未要求登录'
});
}
// 解析传入的商品数据
let goodsData = null;
if (options.goodsData) {
try {
goodsData = JSON.parse(decodeURIComponent(options.goodsData));
console.log('解析后的商品数据:', goodsData);
// 优先使用传入的商品数据中的联系人信息
this.setData({
goodsDetail: goodsData,
fromSeller: options.fromSeller === 'true',
isFavorite: goodsData.isFavorite || false // 初始化收藏状态
});
} catch (error) {
console.error('解析商品数据失败:', error);
}
}
// 优先使用分享URL中的联系人信息
let contactFromShare = null;
if (options.contactName && options.contactPhone) {
contactFromShare = {
product_contact: decodeURIComponent(options.contactName),
contact_phone: decodeURIComponent(options.contactPhone),
};
// 如果有地区信息,也添加到联系人信息中
if (options.region) {
contactFromShare.region = decodeURIComponent(options.region);
}
console.log('从分享URL中获取联系人信息:', contactFromShare);
} else if (options.region) {
// 如果只有地区信息,也需要处理
contactFromShare = {
region: decodeURIComponent(options.region),
};
console.log('从分享URL中获取地区信息:', contactFromShare);
}
// 从商品数据中提取商品ID
let productId;
if (goodsData && (goodsData.id || goodsData.productId)) {
productId = goodsData.id || goodsData.productId;
} else if (options.productId) {
productId = options.productId;
} else {
console.error('未找到商品ID');
wx.showToast({
title: '商品信息有误',
icon: 'none',
duration: 2000
});
// 2秒后返回上一页
setTimeout(() => {
wx.navigateBack();
}, 2000);
return;
}
console.log('最终使用的商品ID:', productId);
// 加载商品详情(即使已有goodsData,也调用API获取最新数据)
this.loadGoodsDetail(productId, goodsData, contactFromShare);
// 添加收藏状态变化事件监听
const app = getApp();
this.favoriteChangedHandler = (data) => {
console.log('收到收藏状态变化通知:', data);
// 如果通知的商品ID与当前页面的商品ID相同,则更新收藏状态
if (data.productId === String(productId) || data.productId === String(this.data.goodsDetail.id)) {
this.setData({
isFavorite: data.isFavorite
});
}
};
app.eventBus.on('favoriteChanged', this.favoriteChangedHandler);
},
onUnload: function () {
// 页面卸载时移除事件监听
const app = getApp();
if (this.favoriteChangedHandler) {
app.eventBus.off('favoriteChanged', this.favoriteChangedHandler);
console.log('移除收藏状态变化事件监听');
}
},
loadGoodsDetail: function (productId, preloadedData = null, contactFromShare = null) {
// 首先显示预加载的数据,确保UI快速响应
if (preloadedData) {
console.log('使用预加载数据显示UI');
}
console.log('调用API获取商品详情,productId:', productId);
API.getProductDetail({ productId: productId })
.then(res => {
console.log('获取商品详情成功:', res);
if (res && res.code === 200 && res.data) {
// 从本地存储获取已预约商品ID列表
const reservedGoodsIds = wx.getStorageSync('reservedGoodsIds') || [];
const product = res.data;
// 详细检查联系人相关字段 - 特别关注数据库字段名
console.log('===== 数据库字段名详细检查 =====');
console.log('- 数据库字段 product_contact:', product.product_contact, '(类型:', typeof product.product_contact, ')');
console.log('- 数据库字段 contact_phone:', product.contact_phone, '(类型:', typeof product.contact_phone, ')');
console.log('- 其他可能的字段:');
console.log(' - contactPhone:', product.contactPhone);
console.log(' - phone:', product.phone);
console.log(' - contact:', product.contact);
console.log(' - name:', product.name);
console.log(' - id:', product.id);
console.log(' - productId:', product.productId);
// 检查完整的API响应字段,确保不错过任何重要信息
console.log('API响应完整字段列表:', Object.keys(product).sort());
// 只过滤hidden状态的商品
if (product.status === 'hidden') {
wx.showToast({
title: '商品已下架',
icon: 'none',
duration: 2000
});
// 2秒后返回上一页
setTimeout(() => {
wx.navigateBack();
}, 2000);
return;
}
// 确保商品ID的一致性
const productIdStr = String(product.productId || product.id);
// 关键修改:直接使用API返回的reservedCount值,这个值已经是从favorites表中统计的收藏数量
// 不再使用selected或reservationCount字段计算,确保收藏人数显示正确
const finalReservationCount = product.reservedCount || 0;
// 调试:打印imageUrls信息
console.log('商品imageUrls:', product.imageUrls);
console.log('imageUrls类型:', typeof product.imageUrls);
console.log('imageUrls是否为数组:', Array.isArray(product.imageUrls));
// 确保imageUrls是数组
let imageUrls = product.imageUrls || [];
if (!Array.isArray(imageUrls)) {
console.error('imageUrls不是数组,转换为数组');
imageUrls = [imageUrls];
}
// 调试:打印处理后的imageUrls
console.log('处理后的imageUrls:', imageUrls);
// 处理grossWeight为null或无效的情况,返回空字符串以支持文字输入
const grossWeightValue = product.grossWeight !== null && product.grossWeight !== undefined ? product.grossWeight : '';
// 处理净重、件数据和规格数据,获取一一对应的显示数组
// 注意:数据库中的规格字段包含净重信息,我们需要与件数数据正确匹配
// 修复:根据用户反馈,数据库中的规格字段内容为:净重46-47,净重44-43,净重47-48
// 我们需要将件数数据正确分割并与净重信息对应
// 首先处理净重和规格数据(它们可能都在spec字段中)
let weightSpecString = '';
let quantityString = '';
// 检查规格字段是否包含净重信息
console.log('=== 数据库字段调试信息 ===');
console.log('product.spec:', product.spec);
console.log('product.specification:', product.specification);
console.log('product.quantity:', product.quantity);
console.log('product.minOrder:', product.minOrder);
console.log('product.grossWeight:', grossWeightValue);
if (product.spec && typeof product.spec === 'string' && (product.spec.includes('净重') || product.spec.includes('毛重'))) {
// 如果规格字段包含净重或毛重信息,则使用该字段作为重量规格数据
weightSpecString = product.spec;
console.log('使用规格字段作为重量规格数据:', weightSpecString);
} else if (product.specification && typeof product.specification === 'string' && (product.specification.includes('净重') || product.specification.includes('毛重'))) {
// 检查specification字段
weightSpecString = product.specification;
console.log('使用specification字段作为重量规格数据:', weightSpecString);
} else if (grossWeightValue) {
// 如果有单独的重量字段,则使用该字段
weightSpecString = grossWeightValue;
console.log('使用重量字段作为重量规格数据:', weightSpecString);
} else {
console.log('未找到重量规格数据');
}
// 处理件数数据
console.log('=== 件数数据调试信息 ===');
console.log('原始件数数据:', product.quantity);
console.log('原始minOrder数据:', product.minOrder);
// 修复:与格式化数据保持一致,优先使用minOrder
if (product.minOrder) {
quantityString = String(product.minOrder);
console.log('使用minOrder作为件数数据:', quantityString);
} else if (product.quantity && typeof product.quantity === 'string') {
quantityString = product.quantity;
console.log('件数数据为字符串:', quantityString);
} else if (product.quantity) {
// 如果件数不是字符串,转换为字符串
quantityString = String(product.quantity);
console.log('件数数据转换为字符串:', quantityString);
} else {
console.log('未找到件数数据');
}
console.log('准备传递给processWeightAndQuantityData的数据:', {
weightSpecString: weightSpecString,
quantityString: quantityString
});
const weightQuantityData = processWeightAndQuantityData(weightSpecString, quantityString, '');
console.log('=== 处理结果调试信息 ===');
console.log('weightSpecString:', weightSpecString);
console.log('quantityString:', quantityString);
console.log('weightQuantityData处理结果:', weightQuantityData);
// 转换supplyStatus字段值
let supplyStatusValue = product.supplyStatus || '';
// 将"平台货源"、"三方认证"、"三方未认证"修改为"预售"、"现货"
if (supplyStatusValue === '平台货源' || supplyStatusValue === '三方认证') {
supplyStatusValue = '现货';
} else if (supplyStatusValue === '三方未认证') {
supplyStatusValue = '预售';
}
// 关键修改:优先使用分享URL中的联系人信息
let contactPhone = '';
let contactName = '';
let region = '';
// 优先级1:分享URL中的联系人信息
if (contactFromShare) {
contactPhone = contactFromShare.contact_phone || '';
contactName = contactFromShare.product_contact || '';
region = contactFromShare.region || '';
console.log('使用分享URL中的联系人信息:', { contactName, contactPhone, region });
}
// 优先级2:预加载数据中的联系人信息
else if (preloadedData) {
contactPhone = preloadedData.contact_phone || preloadedData.contactPhone || preloadedData.phone || '';
contactName = preloadedData.product_contact || preloadedData.contact || preloadedData.contactName || '';
region = preloadedData.region || '';
console.log('使用预加载数据中的联系人信息:', { contactName, contactPhone, region });
}
// 优先级3:API返回的数据
if (!contactPhone && product) {
contactPhone = product.contact_phone || product.contactPhone || product.phone || '';
}
if (!contactName && product) {
contactName = product.product_contact || product.contact || product.contactName || '';
}
if (!region && product && product.region) {
region = product.region || '';
}
// 确保联系人信息不为空
if (!contactPhone) {
contactPhone = product.contact_phone || product.contactPhone || product.phone || '暂无联系电话';
}
if (!contactName) {
contactName = product.product_contact || product.contact || product.contactName || '联系人信息暂不可用';
}
if (!region && product.region) {
region = extractProvince(product.region);
}
// 如果region仍为空,尝试从预加载数据中提取
if (!region && preloadedData && preloadedData.region) {
region = extractProvince(preloadedData.region);
}
if (!region) region = '地区未知';
// 预处理媒体URL,添加类型信息
const mediaItems = processMediaUrls(imageUrls || []);
console.log('预处理后的媒体数据:', mediaItems);
// 转换商品数据格式
const formattedGoods = {
id: productIdStr,
productId: productIdStr,
// 直接使用数据库字段名
name: product.productName || product.name || '商品名称',
price: product.price,
minOrder: product.minOrder || product.quantity,
yolk: product.yolk,
spec: product.spec || product.specification || '暂无规格',
region: region,
// 保留原始字段引用,确保数据完整性
imageUrls: imageUrls || [],
// 添加预处理后的媒体数据,包含类型信息
mediaItems: mediaItems,
displayGrossWeight: formatGrossWeight(grossWeightValue, product.weight),
isReserved: reservedGoodsIds.some(itemId => String(itemId) === productIdStr),
created_at: product.created_at || product.createdAt,
updated_at: product.updated_at || product.updatedAt,
status: product.status,
supplyStatus: supplyStatusValue,
sourceType: product.sourceType || '',
sourceTypeColor: getSourceTypeColor(product.sourceType),
// 复制原始产品对象中的所有字段,确保不丢失任何数据
...product,
// 合并预加载数据中的字段
...(preloadedData || {}),
// 添加产品包装字段(放在product之后,确保不被覆盖)
// 修复:使用正确的数据库字段名producting
producting: product.producting || '',
// 直接使用数据库字段名,确保与表结构完全一致,放在后面覆盖前面的值
product_contact: contactName,
contact_phone: contactPhone,
// 确保reservedCount字段使用我们计算得到的值,放在最后以覆盖其他来源的值
reservedCount: finalReservationCount,
// 添加净重和件数的一一对应数据
weightQuantityData: weightQuantityData
};
// 调试:打印formattedGoods的imageUrls和mediaItems
console.log('formattedGoods.imageUrls:', formattedGoods.imageUrls);
console.log('formattedGoods.mediaItems:', formattedGoods.mediaItems);
console.log('最终格式化后的数据:', {
product_contact: formattedGoods.product_contact,
contact_phone: formattedGoods.contact_phone,
region: formattedGoods.region,
packaging: formattedGoods.packaging
});
// 保存预加载数据中的isFavorite状态,确保是布尔值
const preloadedFavoriteStatus = preloadedData ? (preloadedData.isFavorite || false) : false;
this.setData({
goodsDetail: formattedGoods,
isFavorite: preloadedFavoriteStatus // 优先使用预加载数据中的收藏状态
});
// 只有当没有预加载的收藏状态时,才从服务器加载
if (!preloadedData || preloadedData.isFavorite === undefined) {
this.loadGoodsFavoriteStatus(productIdStr);
}
} else {
wx.showToast({
title: '获取商品详情失败',
icon: 'none',
duration: 2000
});
}
})
.catch(err => {
console.error('获取商品详情失败:', err);
wx.showToast({
title: '获取商品详情失败',
icon: 'none',
duration: 2000
});
})
.finally(() => {
wx.hideLoading();
});
},
// 加载商品的收藏状态
loadGoodsFavoriteStatus: function (productId) {
const openid = wx.getStorageSync('openid');
const userId = wx.getStorageSync('userId');
// 如果用户未登录,不加载收藏状态
if (!openid || !userId) {
return;
}
// 获取用户手机号
let userPhone = '';
try {
const users = wx.getStorageSync('users') || {};
if (userId && users[userId] && users[userId].phoneNumber) {
userPhone = users[userId].phoneNumber;
} else {
const userInfo = wx.getStorageSync('userInfo');
if (userInfo && userInfo.phoneNumber) {
userPhone = userInfo.phoneNumber;
} else {
userPhone = wx.getStorageSync('phoneNumber');
}
}
} catch (e) {
console.error('获取用户手机号失败:', e);
}
if (!userPhone) {
return;
}
// 调用API获取用户收藏列表
API.getFavorites(userPhone)
.then(res => {
if (res && res.code === 200) {
// 检查API返回的数据结构,确保我们获取到正确的收藏列表
let favoritesList = [];
if (Array.isArray(res.data)) {
favoritesList = res.data;
} else if (res.data && Array.isArray(res.data.favorites)) {
favoritesList = res.data.favorites;
} else if (res.data && Array.isArray(res.data.data)) {
favoritesList = res.data.data;
}
console.log('获取收藏列表成功,处理后的数据:', favoritesList);
// 从收藏列表中提取商品ID
const favoriteProductIds = favoritesList.map(item => {
// 尝试从不同的字段名获取商品ID
return String(item.productId || item.id || item.product_id || '');
}).filter(id => id !== ''); // 过滤掉空字符串
console.log('收藏商品ID列表:', favoriteProductIds);
console.log('当前商品ID:', String(productId));
const isFavorite = favoriteProductIds.includes(String(productId));
console.log('计算得到的收藏状态:', isFavorite);
// 只有当从收藏列表中明确获取到结果时,才更新收藏状态
// 避免因为API返回数据结构问题导致收藏状态被错误覆盖
this.setData({
isFavorite: isFavorite
});
}
})
.catch(err => {
console.error('获取收藏状态失败:', err);
// 注意:这里不要更新isFavorite状态,保持之前的状态
});
},
// 添加收藏
addFavorite: function () {
const productId = String(this.data.goodsDetail.id || this.data.goodsDetail.productId);
console.log('用户点击了收藏按钮,商品ID:', productId);
// 检查用户登录状态
const openid = wx.getStorageSync('openid');
const userId = wx.getStorageSync('userId');
if (!openid || !userId) {
console.log('用户未登录,显示一键登录弹窗');
// 显示登录弹窗
this.setData({
showOneKeyLoginModal: true
});
return;
}
wx.showLoading({ title: '正在收藏...' });
// 调用API添加收藏
API.addFavorite(productId)
.then(res => {
wx.hideLoading();
console.log('添加收藏成功:', res);
// 更新商品的收藏状态
this.setData({
isFavorite: true
});
// 触发全局事件,通知其他页面收藏状态已更改
const app = getApp();
app.eventBus.emit('favoriteChanged', {
productId: productId,
isFavorite: true
});
// 显示成功提示
wx.showToast({
title: '收藏成功',
icon: 'success',
duration: 1500
});
})
.catch(err => {
wx.hideLoading();
console.error('添加收藏失败:', err);
// 显示错误提示
wx.showToast({
title: '收藏失败,请稍后重试',
icon: 'none',
duration: 2000
});
});
},
// 取消收藏
cancelFavorite: function () {
const productId = String(this.data.goodsDetail.id || this.data.goodsDetail.productId);
console.log('用户点击了取消收藏按钮,商品ID:', productId);
// 检查用户登录状态
const openid = wx.getStorageSync('openid');
const userId = wx.getStorageSync('userId');
if (!openid || !userId) {
console.log('用户未登录,显示一键登录弹窗');
// 由于商品详情页可能没有登录弹窗,这里直接提示用户登录
wx.showToast({
title: '请先登录',
icon: 'none',
duration: 2000
});
return;
}
wx.showLoading({ title: '正在取消收藏...' });
// 调用API取消收藏
API.cancelFavorite(productId)
.then(res => {
wx.hideLoading();
console.log('取消收藏成功:', res);
// 更新商品的收藏状态
this.setData({
isFavorite: false
});
// 触发全局事件,通知其他页面收藏状态已更改
const app = getApp();
app.eventBus.emit('favoriteChanged', {
productId: productId,
isFavorite: false
});
// 显示成功提示
wx.showToast({
title: '取消收藏成功',
icon: 'success',
duration: 1500
});
})
.catch(err => {
wx.hideLoading();
console.error('取消收藏失败:', err);
// 显示错误提示
wx.showToast({
title: '取消收藏失败,请稍后重试',
icon: 'none',
duration: 2000
});
});
},
// 处理收藏按钮点击事件
onFavoriteClick: function () {
if (this.data.isFavorite) {
this.cancelFavorite();
} else {
this.addFavorite();
}
},
// 预览媒体(只对图片执行预览操作)
previewImage(e) {
const { urls, index } = e.currentTarget.dataset;
if (!urls || urls.length === 0) {
wx.showToast({
title: '没有内容可预览',
icon: 'none'
});
return;
}
// 检查当前点击的是否为图片
const currentUrl = urls[index];
const isVideo = currentUrl.includes('.mp4') || currentUrl.includes('.mov') || currentUrl.includes('.avi') || currentUrl.includes('.wmv') || currentUrl.includes('.flv') || currentUrl.includes('.webm');
if (isVideo) {
// 视频不执行预览,直接播放
console.log('当前是视频,不执行预览操作');
return;
}
// 只对图片执行预览操作
this.setData({
showImagePreview: true,
previewImageUrls: urls.filter(url => !url.includes('.mp4') && !url.includes('.mov') && !url.includes('.avi') && !url.includes('.wmv') && !url.includes('.flv') && !url.includes('.webm')),
previewImageIndex: parseInt(index || 0)
});
this.resetZoom();
},
// 关闭图片预览
closeImagePreview() {
this.setData({
showImagePreview: false
});
this.resetZoom();
},
// 重置缩放状态
resetZoom() {
this.setData({
scale: 1,
lastScale: 1,
offsetX: 0,
offsetY: 0,
initialTouch: null
});
},
// 图片预览切换
onPreviewImageChange(e) {
this.setData({
previewImageIndex: e.detail.current
});
// 切换图片时重置缩放状态
this.resetZoom();
},
// 处理图片点击事件(单击/双击判断)
handleImageTap(e) {
const currentTime = Date.now();
const lastTapTime = this.data.lastTapTime || 0;
// 判断是否为双击(300ms内连续点击)
if (currentTime - lastTapTime < 300) {
// 双击事件
if (this.data.doubleTapTimer) {
clearTimeout(this.data.doubleTapTimer);
}
// 切换放大/缩小状态
const newScale = this.data.scale === 1 ? 2 : 1;
this.setData({
scale: newScale,
lastScale: newScale,
offsetX: 0,
offsetY: 0,
lastTapTime: 0 // 重置双击状态
});
} else {
// 单击事件,设置延迟来检测是否会成为双击
if (this.data.doubleTapTimer) {
clearTimeout(this.data.doubleTapTimer);
}
this.setData({
lastTapTime: currentTime,
doubleTapTimer: setTimeout(() => {
// 确认是单击,关闭图片预览
this.closeImagePreview();
}, 300)
});
}
},
// 计算两点之间的距离
calculateDistance(touch1, touch2) {
const dx = touch2.clientX - touch1.clientX;
const dy = touch2.clientY - touch1.clientY;
return Math.sqrt(dx * dx + dy * dy);
},
// 处理触摸开始事件
handleTouchStart(e) {
console.log('触摸开始事件:', e);
const touches = e.touches;
if (touches.length === 1) {
// 单指:准备拖动
this.setData({
initialTouch: {
x: touches[0].clientX,
y: touches[0].clientY
}
});
} else if (touches.length === 2) {
// 双指:记录起始距离,准备缩放
const distance = this.calculateDistance(touches[0], touches[1]);
this.setData({
startDistance: distance,
isScaling: true,
lastScale: this.data.scale
});
}
},
// 处理触摸移动事件
handleTouchMove(e) {
const touches = e.touches;
if (touches.length === 1 && this.data.initialTouch && this.data.scale !== 1) {
// 单指拖动(只有在缩放状态下才允许拖动)
const deltaX = touches[0].clientX - this.data.initialTouch.x;
const deltaY = touches[0].clientY - this.data.initialTouch.y;
// 计算新的偏移量
let newOffsetX = this.data.offsetX + deltaX;
let newOffsetY = this.data.offsetY + deltaY;
// 边界限制
const windowWidth = wx.getSystemInfoSync().windowWidth;
const windowHeight = wx.getSystemInfoSync().windowHeight;
const maxOffsetX = (windowWidth * (this.data.scale - 1)) / 2;
const maxOffsetY = (windowHeight * (this.data.scale - 1)) / 2;
newOffsetX = Math.max(-maxOffsetX, Math.min(maxOffsetX, newOffsetX));
newOffsetY = Math.max(-maxOffsetY, Math.min(maxOffsetY, newOffsetY));
this.setData({
offsetX: newOffsetX,
offsetY: newOffsetY,
initialTouch: {
x: touches[0].clientX,
y: touches[0].clientY
}
});
} else if (touches.length === 2) {
// 双指缩放
const currentDistance = this.calculateDistance(touches[0], touches[1]);
const scale = (currentDistance / this.data.startDistance) * this.data.lastScale;
// 限制缩放范围在0.5倍到3倍之间
const newScale = Math.max(0.5, Math.min(3, scale));
this.setData({
scale: newScale,
isScaling: true
});
}
},
// 处理触摸结束事件
handleTouchEnd(e) {
this.setData({
isScaling: false,
lastScale: this.data.scale,
initialTouch: null
});
},
// 拨打电话
makePhoneCall(e) {
console.log('拨打电话事件:', e);
const phoneNumber = e.currentTarget.dataset.phone;
if (phoneNumber) {
wx.showModal({
title: '联系人电话',
content: phoneNumber,
showCancel: true,
cancelText: '取消',
confirmText: '拨打',
success: (res) => {
if (res.confirm) {
wx.makePhoneCall({
phoneNumber: phoneNumber,
success: () => {
console.log('拨打电话成功');
},
fail: (err) => {
console.error('拨打电话失败', err);
wx.showToast({
title: '拨打电话失败',
icon: 'none'
});
}
});
}
}
});
}
},
// 在线聊天
onChat(e) {
console.log('在线咨询事件:', e);
const { id } = e.currentTarget.dataset;
if (!id) return;
// 获取商品联系人信息
const contactName = this.data.goodsDetail.product_contact;
const contactPhone = this.data.goodsDetail.contact_phone;
// 检查是否有联系电话
if (!contactPhone) {
wx.showToast({
title: '未找到联系电话',
icon: 'none'
});
return;
}
// 检查用户登录状态
const openid = wx.getStorageSync('openid');
const userId = wx.getStorageSync('userId');
if (!openid || !userId) {
console.log('用户未登录,显示登录弹窗');
this.setData({
showOneKeyLoginModal: true
});
return;
}
// 跳转到聊天界面或打开客服窗口
wx.showModal({
title: '在线咨询',
content: `将为您连接到 ${contactName || '客服人员'}`,
showCancel: true,
cancelText: '取消',
confirmText: '立即咨询',
success: (res) => {
if (res.confirm) {
// 获取当前用户的手机号
let userPhone = '';
try {
// 尝试从不同的存储位置获取手机号
const userInfo = wx.getStorageSync('userInfo');
if (userInfo && userInfo.phoneNumber) {
userPhone = userInfo.phoneNumber;
} else {
// 尝试从其他可能的存储位置获取
const users = wx.getStorageSync('users') || {};
const userId = wx.getStorageSync('userId');
if (userId && users[userId] && users[userId].phoneNumber) {
userPhone = users[userId].phoneNumber;
} else {
userPhone = wx.getStorageSync('phoneNumber');
}
}
} catch (e) {
console.error('获取用户手机号失败:', e);
}
console.log('当前用户手机号:', userPhone);
console.log('联系人信息:', { contactName, contactPhone });
// 验证手机号
if (!userPhone) {
wx.showToast({
title: '请先登录获取手机号',
icon: 'none'
});
return;
}
// 验证联系人手机号
if (!contactPhone) {
console.error('联系人手机号不存在');
wx.showToast({
title: '联系人信息不完整,请稍后重试',
icon: 'none'
});
return;
}
console.log('联系人手机号:', contactPhone);
// 显示加载提示
wx.showLoading({
title: '正在建立聊天...',
});
// 调用API创建聊天记录,确保用户和联系人之间的聊天记录是双向的
API.fixChatRecordsPair(userPhone, contactPhone).then(res => {
console.log('聊天建立成功:', JSON.stringify(res, null, 2));
// 隐藏加载提示
wx.hideLoading();
// 使用联系人手机号作为聊天会话ID
const chatSessionId = contactPhone;
// 跳转到聊天页面,确保正确传递联系人手机号和用户名
wx.navigateTo({
url: `/pages/chat-detail/index?userId=${chatSessionId}&userName=${encodeURIComponent(contactName || '联系人')}&phone=${contactPhone}&isManager=true`,
success: function () {
console.log('成功跳转到聊天详情页');
},
fail: function (error) {
console.error('跳转到聊天详情页失败:', error);
wx.showToast({
title: '聊天功能开发中',
icon: 'none'
});
}
});
}).catch(err => {
console.error('建立聊天失败:', err);
// 隐藏加载提示
wx.hideLoading();
wx.showToast({
title: '建立聊天失败,请重试',
icon: 'none'
});
});
}
}
});
},
/* 已移除:我想要(预约)功能
onClickWantInDetail(e) {
console.log('我想要事件:', e);
const { id } = e.currentTarget.dataset;
if (!id) return;
// 从本地存储获取openid
const openid = wx.getStorageSync('openid');
console.log('openid:', openid);
// 检查是否已登录
if (!openid) {
// 如果未登录,显示授权登录弹窗
this.setData({ showAuthModal: true });
return;
}
// 获取已预约商品ID列表
let reservedGoodsIds = wx.getStorageSync('reservedGoodsIds') || [];
// 检查是否已经预约过
if (reservedGoodsIds.some(itemId => String(itemId) === String(id))) {
wx.showToast({
title: '您已经预约过该商品',
icon: 'none',
duration: 1500
});
return;
}
// 添加到已预约列表
reservedGoodsIds.push(id);
wx.setStorageSync('reservedGoodsIds', reservedGoodsIds);
// 更新页面状态
this.setData({
'goodsDetail.isReserved': true
});
// 调用API记录预约
API.reserveProduct({ id: id })
.then(res => {
console.log('预约成功:', res);
wx.showToast({
title: '预约成功',
icon: 'success',
duration: 1500
});
})
.catch(err => {
console.error('预约失败:', err);
// 如果API调用失败,从本地列表中移除
reservedGoodsIds = reservedGoodsIds.filter(itemId => String(itemId) !== String(id));
wx.setStorageSync('reservedGoodsIds', reservedGoodsIds);
// 更新页面状态
this.setData({
'goodsDetail.isReserved': false
});
wx.showToast({
title: '预约失败,请重试',
icon: 'none',
duration: 1500
});
});
},
*/
// 关闭登录弹窗
closeOneKeyLoginModal() {
this.setData({
showOneKeyLoginModal: false
});
},
// 处理手机号授权结果
onPhoneNumberResult(e) {
console.log('getPhoneNumber响应:', e.detail);
// 关闭登录弹窗
this.setData({
showOneKeyLoginModal: false
});
// 用户点击拒绝授权
if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
wx.showToast({
title: '需要授权手机号才能使用',
icon: 'none',
duration: 2000
});
return;
}
// 处理没有权限的情况
if (e.detail.errMsg === 'getPhoneNumber:fail no permission') {
wx.showToast({
title: '当前环境无法获取手机号权限',
icon: 'none',
duration: 3000
});
return;
}
// 这里可以添加完整的登录处理逻辑
// 参考首页的 onGetPhoneNumber 函数
console.log('手机号授权成功,需要完整的登录流程处理');
// 由于详情页的登录处理比较复杂,建议跳转到首页处理
// 或者可以触发一个全局事件,让其他页面处理登录逻辑
const app = getApp();
if (app && app.globalData) {
app.globalData.pendingPhoneAuth = e.detail;
// 可以跳转到首页处理登录
wx.switchTab({
url: '/pages/index/index',
success: () => {
// 可以发送事件通知首页处理登录
wx.showToast({
title: '请在首页完成登录',
icon: 'none',
duration: 2000
});
}
});
}
},
// 处理登录授权
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 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://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
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('用户点击了我知道了');
}
}
});
}
// 显示登录成功提示
wx.showToast({
title: '登录成功',
icon: 'success',
duration: 1500
})
// 登录成功后,重新加载商品详情以刷新收藏状态
const productId = String(this.data.goodsDetail.id || this.data.goodsDetail.productId);
this.loadGoodsFavoriteStatus(productId);
// 触发全局事件,通知其他页面登录状态已更改
const app = getApp();
if (app && app.eventBus) {
app.eventBus.emit('userLoginStatusChanged', {
isLoggedIn: true,
userId: storedUserId,
phoneNumber: finalPhoneNumber
});
}
} else {
// 用户拒绝授权或其他情况
console.log('手机号授权失败:', e.detail.errMsg)
// 不再抛出错误,而是显示友好的提示
wx.hideLoading()
wx.showToast({
title: '需要授权手机号才能使用',
icon: 'none',
duration: 2000
})
return
}
} catch (error) {
wx.hideLoading()
console.error('登录过程中发生错误:', error)
// 更具体的错误提示
let errorMsg = '登录失败,请重试'
if (error.message.includes('网络')) {
errorMsg = '网络连接失败,请检查网络后重试'
} else if (error.message.includes('服务器')) {
errorMsg = '服务器连接失败,请稍后重试'
}
wx.showToast({
title: errorMsg,
icon: 'none',
duration: 3000
})
// 清除可能已经保存的不完整信息
try {
wx.removeStorageSync('openid')
wx.removeStorageSync('sessionKey')
wx.removeStorageSync('userId')
} catch (e) {
console.error('清除临时登录信息失败:', e)
}
}
},
// 保存用户信息的方法
async saveUserInfo(userInfo, userType) {
return new Promise((resolve, reject) => {
// 1. 保存到本地users对象
const users = wx.getStorageSync('users') || {};
const userId = wx.getStorageSync('userId');
if (!userId) {
reject(new Error('用户ID不存在'));
return;
}
// 合并用户信息
users[userId] = {
...users[userId],
...userInfo,
type: userType || 'buyer',
updatedAt: new Date().toISOString()
};
wx.setStorageSync('users', users);
// 2. 保存到全局userInfo对象
wx.setStorageSync('userInfo', {
...userInfo,
userType: userType || 'buyer'
});
// 3. 上传到服务器
const API = require('../../utils/api.js');
API.uploadUserInfo({
userId: userId,
...userInfo,
type: userType || 'buyer'
}).then(res => {
console.log('用户信息上传成功:', res);
resolve(res);
}).catch(err => {
console.error('用户信息上传失败:', err);
// 即使服务器上传失败,也继续流程,只在本地保存
resolve({ success: false, message: '本地保存成功,服务器同步失败' });
});
});
},
// 返回上一页
goBack() {
wx.navigateBack();
}
});