From fc957feb72aa2733bdff2c929246ac06aaf8fe2d Mon Sep 17 00:00:00 2001 From: wwz <1144797966@qq.com> Date: Sat, 15 Mar 2025 12:03:34 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BC=9A=E5=91=98=EF=BC=8C?= =?UTF-8?q?=E5=95=86=E5=93=81=EF=BC=8C=E4=B8=8B=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- App.vue | 49 ++ common/api/request.js | 30 +- common/js/websocket.js | 121 ++-- pages/index/index.vue | 57 +- pages/index/indexs.vue | 6 +- pages/order/components/IntegralInput.vue | 6 +- pages/order/components/orderInfoAfter.vue | 3 +- pages/order/components/orderInfoBefore.vue | 557 ------------------ pages/order/coupon.vue | 6 +- pages/order/detail.vue | 87 ++- pages/product/choosetable.vue | 4 +- pages/product/components/confirmorder.vue | 2 - pages/product/components/shoppingCartes.vue | 17 +- pages/product/index.vue | 443 +++++++------- .../user/member/components/registermember.vue | 30 +- pages/user/member/index.vue | 11 +- pages/user/member/memberdetails.vue | 23 +- pages/user/user.vue | 2 +- stores/user.js | 8 +- 19 files changed, 484 insertions(+), 978 deletions(-) delete mode 100644 pages/order/components/orderInfoBefore.vue diff --git a/App.vue b/App.vue index 0f606f6..028ad90 100644 --- a/App.vue +++ b/App.vue @@ -32,6 +32,55 @@ console.log(error) } // #endif + try { + uni.getLocation({ + type: 'wgs84', + success: async (res) => { + let successres = await APIgeocodelocation({ + lng: res.longitude, + lat: res.latitude, + }) + if (successres) { + let datastorage = { + country: successres.addressComponent.country, // "中国" + province: successres.addressComponent + .province, //province: "陕西省" + address: successres.addressComponent.city, //district: "西安市" + district: successres.addressComponent.district, //district: "未央区" + lng: res.longitude, + lat: res.latitude, + } + uni.cache.set('getLocationstorage', datastorage); + // 登录 + proxy.$isResolve() + } + }, + + }); + } catch (error) { + try { + let successres = await APIgeocodelocation({ + lng: '', + lat: '', + }) + if (successres) { + let datastorage = { + country: successres.addressComponent.country, // "中国" + province: successres.addressComponent + .province, //province: "陕西省" + address: successres.addressComponent.city, //district: "西安市" + district: successres.addressComponent.district, //district: "未央区" + lng: res.longitude, + lat: res.latitude, + } + uni.cache.set('getLocationstorage', datastorage); + proxy.$isResolve() + } + } catch (error) { + + } + } + proxy.$isResolve() }); // export default { diff --git a/common/api/request.js b/common/api/request.js index 6051965..d057677 100644 --- a/common/api/request.js +++ b/common/api/request.js @@ -31,11 +31,13 @@ export default (params) => { }) } return new Promise((resolve, reject) => { + const timeoutDuration = params.timeout || 10000; // 可以通过 params 传入超时时间,默认 10 秒 uni.request({ url: uni.conf.baseUrl + url, method: method, header: header, data: data, + timeout: timeoutDuration, success(response) { const res = response.data // 根据返回的状态码做出对应的操作 @@ -43,7 +45,7 @@ export default (params) => { if (res.code == 200) { uni.hideLoading(); uni.hideToast(); - resolve(res.data); + resolve(res.data ?res.data: true); } else { switch (res.code) { case '501': @@ -68,15 +70,14 @@ export default (params) => { break; default: // 是否提示 - console.log(res) if (toast) { uni.showToast({ title: res.message || res.msg || res.error, icon: "none", success: () => { setTimeout(res => { - - }, 2000) + reject(false); + }, 1000) } }) } @@ -85,21 +86,18 @@ export default (params) => { } }, fail(err) { - console.log(err) if (err.errMsg.indexOf('request:fail') !== -1) { - uni.showToast({ - title: '网络异常', - icon: "error", - duration: 2000 - }) - } else { - uni.showToast({ - title: '未知异常', - duration: 2000 - }) + if (err.errMsg.indexOf('timeout') !== -1) { + if (toast) { + uni.showToast({ + title: `请求超时,请稍后重试`, + icon: "error", + duration: 2000 + }); + } + } } reject(err); - }, complete() { // 不管成功还是失败都会执行 diff --git a/common/js/websocket.js b/common/js/websocket.js index 95c5676..074f6e5 100644 --- a/common/js/websocket.js +++ b/common/js/websocket.js @@ -24,10 +24,10 @@ const useWebSocket = (options = {}) => { const reconnectAttempts = ref(0); //重连的尝试次数 const isNetworkConnected = ref(true); //监听当前网络连接状态 const isManuallyClosed = ref(false); //是否是被手动关闭的 - const receivedMessages = ref([]); //储从 WebSocket 服务器接收到的消息 + const receivedMessages = ref(); //储从 WebSocket 服务器接收到的消息 const initMessageSendAttempts = ref(0); //初始化连接多少次 const reconnectStartTime = ref(0); //新增:记录重连开始时间 - + const isPongReceived = ref(false) // 关闭现有连接并清理资源 const closeExistingConnection = () => { if (socketTask.value) { @@ -75,9 +75,8 @@ const useWebSocket = (options = {}) => { url: uni.conf.baseUrlwws, success: (res) => { isConnected.value = true; - reconnectAttempts.value = 0; // 监听初始化成功在开启心跳 - // startHeartbeat(); + startHeartbeat(); }, fail: () => { console.error('WebSocket 连接失败,尝试重连'); @@ -91,12 +90,12 @@ const useWebSocket = (options = {}) => { socketTask.value.onOpen(() => { // 初始化 初始购物车 sendMessage(initMessage) + uni.hideLoading(); }); socketTask.value.onMessage((res) => { - let list = JSON.parse(res.data) - console.log(list, 'receivedMessages.value') - receivedMessages.value.push(list); - if (res.msg == 'ok') { + receivedMessages.value = JSON.parse(res.data) + // receivedMessages.value.push(list); + if (receivedMessages.value == 'ok') { console.log('心跳响应正常'); // 心跳正常,重置重连尝试次数 reconnectAttempts.value = 0; @@ -110,8 +109,15 @@ const useWebSocket = (options = {}) => { clearInterval(heartbeatTimer.value); // 停止心跳定时器 clearTimeout(reconnectTimer.value); // 清除重连定时器 if (res.code == '1006') { + uni.showToast({ + title: '操作异常,请重新扫码', + icon: 'none' + }); console.log('服务器正常关闭,停止重连'); autoReconnect.value = false; + setTimeout(() => { + uni.pro.switchTab('index/index'); + }, 1000) return false; } if (autoReconnect.value && !isManuallyClosed.value) { @@ -139,14 +145,16 @@ const useWebSocket = (options = {}) => { uni.showToast({ title: '网络未连接...', icon: 'none' - }) + }); setTimeout(() => { - uni.pro.switchTab('index/index') - }, 1000) + uni.pro.switchTab('index/index'); + }, 1000); return; } heartbeatTimer.value = setInterval(() => { if (isConnected.value) { + console.log('发送心跳消息'); + isPongReceived.value = false; // 每次发送心跳消息前重置标记 socketTask.value.send({ data: JSON.stringify({ type: 'ping_interval' @@ -154,24 +162,47 @@ const useWebSocket = (options = {}) => { success: () => { console.log('心跳消息发送成功'); const pongTimer = setTimeout(() => { - console.error('心跳超时,未收到响应,尝试重连'); - clearInterval(heartbeatTimer.value); - if (autoReconnect) { - handleReconnect(); + if (!isPongReceived.value) { + console.error('心跳超时,未收到响应,尝试重连'); + clearInterval(heartbeatTimer.value); + if (autoReconnect.value && reconnectAttempts.value < + maxReconnectAttempts) { + handleReconnect(); + } else { + console.error('重连次数达到上限,停止重连和心跳'); + clearInterval(heartbeatTimer.value); + autoReconnect.value = false; + uni.pro.switchTab('index/index'); + } } }, heartbeatInterval * 1.2); - socketTask.value.onMessage((res) => { - if (res.msg == 'ok') { - clearTimeout(pongTimer); + const handlePong = (res) => { + try { + let data = JSON.parse(res.data); + if (data.msg === 'ok' && data.msg_id == + 'ping_interval') { + isPongReceived.value = true; + console.log('收到心跳响应,清除超时定时器'); + clearTimeout(pongTimer); + } + } catch (error) { + console.error('解析心跳响应数据时出错:', error); } - }); + }; + socketTask.value.onMessage(handlePong); }, fail: () => { console.error('心跳消息发送失败,尝试重连'); clearInterval(heartbeatTimer.value); - if (autoReconnect) { + if (autoReconnect.value && reconnectAttempts.value < + maxReconnectAttempts) { handleReconnect(); + } else { + console.error('重连次数达到上限,停止重连和心跳'); + clearInterval(heartbeatTimer.value); + autoReconnect.value = false; + uni.pro.switchTab('index/index'); } } }); @@ -179,6 +210,7 @@ const useWebSocket = (options = {}) => { }, heartbeatInterval); }; + // 手动关闭连接 const closeSocket = () => { isManuallyClosed.value = true; @@ -217,6 +249,10 @@ const useWebSocket = (options = {}) => { reconnectAttempts.value++; const reconnectInterval = initialReconnectInterval * Math.pow(2, reconnectAttempts.value - 1); const randomizedInterval = reconnectInterval + Math.floor(Math.random() * 1000); + uni.showLoading({ + title: `尝试第 ${reconnectAttempts.value} 次重连`, + mask: true + }) console.log(`尝试第 ${reconnectAttempts.value} 次重连,重连间隔: ${randomizedInterval}ms...`); reconnectTimer.value = setTimeout(() => { connect(); @@ -227,36 +263,14 @@ const useWebSocket = (options = {}) => { title: '重连次数达到上限,停止重连', icon: 'none' }); - } - }; - - // 发送初始化消息 - const sendInitMessage = async () => { - if (initMessageSendAttempts.value < initMessageRetryCount) { - initMessageSendAttempts.value++; - await socketTask.value.send({ - data: JSON.stringify(initMessage), - success: () => { - console.log('初始化消息发送成功'); - initMessageSendAttempts.value = 0; // 重置尝试次数 - }, - fail: () => { - console.log( - `初始化消息发送失败,第 ${initMessageSendAttempts.value} 次尝试,将在 ${initMessageRetryInterval} 后重试` - ); - setTimeout(() => { - sendInitMessage(); - }, initMessageRetryInterval); - } - }); - } else { - console.error('初始化消息发送失败,已达到最大重试次数'); - // initMessageSendAttempts.value = 0; // 重置尝试次数 + clearInterval(heartbeatTimer.value); + autoReconnect.value = false; + uni.pro.switchTab('index/index'); } }; - // 网络状态监听 + // / 网络状态监听 const initNetworkListener = () => { uni.getSystemInfo({ success: (res) => { @@ -295,10 +309,12 @@ const useWebSocket = (options = {}) => { }); }; - onMounted(() => { - initNetworkListener(); - connect(); - }); + // 页面显示,尝试连接 WebSocket + const onShowconnect = () => { + if (autoReconnect.value) { + connect(); + } + } onBeforeUnmount(() => { closeSocket(); @@ -308,7 +324,10 @@ const useWebSocket = (options = {}) => { isConnected, sendMessage, closeSocket, - receivedMessages + receivedMessages, + closeExistingConnection, + onShowconnect, + initNetworkListener }; }; diff --git a/pages/index/index.vue b/pages/index/index.vue index f4df936..0877120 100644 --- a/pages/index/index.vue +++ b/pages/index/index.vue @@ -74,7 +74,7 @@ :style="{'background':c.backColor,'color':c.backColor}"> - {{c.name}} + {{c.name || ''}} @@ -338,66 +338,19 @@ uni.$u.debounce(store.scrollTop = res.scrollTop, 500) }); onShow(async () => { + + }) + onMounted(async () => { await proxy.$onLaunched; if (uni.cache.get('shopId')) { showindex.value = 'shopIndex' await storeuser.actionsAPIuser() } else { + showindex.value = 'index' hometop() init_fn() - showindex.value = 'index' // 获取初始定位高度 } - }) - onMounted(async () => { - try { - uni.getLocation({ - type: 'wgs84', - success: async (res) => { - let successres = await APIgeocodelocation({ - lng: res.longitude, - lat: res.latitude, - }) - if (successres) { - let datastorage = { - country: successres.addressComponent.country, // "中国" - province: successres.addressComponent - .province, //province: "陕西省" - address: successres.addressComponent.city, //district: "西安市" - district: successres.addressComponent.district, //district: "未央区" - lng: res.longitude, - lat: res.latitude, - } - uni.cache.set('getLocationstorage', datastorage); - // 登录 - proxy.$isResolve() - } - }, - - }); - } catch (error) { - try { - let successres = await APIgeocodelocation({ - lng: '', - lat: '', - }) - if (successres) { - let datastorage = { - country: successres.addressComponent.country, // "中国" - province: successres.addressComponent - .province, //province: "陕西省" - address: successres.addressComponent.city, //district: "西安市" - district: successres.addressComponent.district, //district: "未央区" - lng: res.longitude, - lat: res.latitude, - } - uni.cache.set('getLocationstorage', datastorage); - proxy.$isResolve() - } - } catch (error) { - proxy.$isResolve() - } - } }); onReachBottom(() => { diff --git a/pages/index/indexs.vue b/pages/index/indexs.vue index 38fcda3..d9d7cf4 100644 --- a/pages/index/indexs.vue +++ b/pages/index/indexs.vue @@ -42,9 +42,8 @@ import { productStore } from '@/stores/user.js'; - const shopExtend = uni.cache.get('shopUserInfo')? uni.cache.get('shopUserInfo').shopExtendList[0] : '' + const shopExtend = uni.cache.get('shopUserInfo') ? uni.cache.get('shopUserInfo').shopExtendList[0] : '' const scanCodehandle = async (i) => { - console.log(11) const store = productStore(); await store.scanCodeactions() } @@ -64,8 +63,7 @@ } return null; } - onMounted(() => { - }) + onMounted(() => {}) \ No newline at end of file diff --git a/pages/order/coupon.vue b/pages/order/coupon.vue index 881dc3d..36cd50b 100644 --- a/pages/order/coupon.vue +++ b/pages/order/coupon.vue @@ -251,11 +251,13 @@ }; }); } - if (!res) { + console.log(res) + if (res.length > 0) { + fromInfo.list = res + } else { fromInfo.list = [] return false } - fromInfo.list = res console.log(res) } diff --git a/pages/order/detail.vue b/pages/order/detail.vue index 2ee1370..d3e027c 100644 --- a/pages/order/detail.vue +++ b/pages/order/detail.vue @@ -39,8 +39,6 @@ @clickPointsamount='clickPointsamount' @learcoupons="learcoupons"> - - @@ -33,7 +33,7 @@ ref } from 'vue' - const otherNum = ref('其他') + const otherNum = ref('') const numIndex = ref(0) diff --git a/pages/product/components/confirmorder.vue b/pages/product/components/confirmorder.vue index 25dc0aa..974b777 100644 --- a/pages/product/components/confirmorder.vue +++ b/pages/product/components/confirmorder.vue @@ -281,8 +281,6 @@ paymentmethod.payType = e.payType; } - - // 提交订单 const orderdetail = async () => { let res = await storeMemberpay.actionscreateOrder({ diff --git a/pages/product/components/shoppingCartes.vue b/pages/product/components/shoppingCartes.vue index 4e720b0..19554c1 100644 --- a/pages/product/components/shoppingCartes.vue +++ b/pages/product/components/shoppingCartes.vue @@ -19,9 +19,15 @@ {{ item.name }} - + - {{item.id == i.productId && item.skuId == i.id ? i.specInfo :""}} + {{item.cartListinfo.sku_id == i.id? i.name:"" }} + + + + {{dataprocessing(item.cartListinfo).title}} + + {{i.proName }} @@ -93,6 +99,7 @@ type: Boolean }, }); + const shopInfo = uni.cache.get('shopInfo') // 定义 ifcartNumber 计算属性方法 @@ -138,6 +145,12 @@ }) } + const dataprocessing = computed(() => { + return (item) => { + return JSON.parse(item.pro_group_info); + }; + }) + // 封装加法函数 const calculateValue = (cartNumber, i, step = 1) => { if (i == '+') { diff --git a/pages/product/index.vue b/pages/product/index.vue index 46c56d0..5473432 100644 --- a/pages/product/index.vue +++ b/pages/product/index.vue @@ -98,7 +98,8 @@ - + {{ ifcartNumber(item) }} @@ -106,7 +107,8 @@ v-if="item.suitNum>1">{{item.suitNum<99?item.suitNum:'99+'}} - + @@ -161,15 +163,9 @@ - {{ item1.memberPrice }} - + + {{shopInfo.isVip ==1 && shopInfo.isMemberPrice==1?item1.memberPrice:item1.salePrice}} + /{{item1.unitName}} @@ -182,18 +178,11 @@ - {{ item1.memberPrice }} - + + {{shopInfo.isVip ==1 && shopInfo.isMemberPrice==1?item1.memberPrice:item1.salePrice}} + /{{item1.unitName}} - {{ ifcartNumber(item1) <99?ifcartNumber(item1):'99+'}} - - + {{ ifcartNumber(item1) }} - + - + @@ -232,10 +222,12 @@ + + @@ -244,7 +236,7 @@ - + @@ -294,6 +286,7 @@ + @@ -362,6 +355,7 @@ onLoad, onReady, onShow, + onHide, onPageScroll } from '@dcloudio/uni-app' @@ -579,9 +573,7 @@ type: '', product_id: '', sku_id: '', - groupSnap: { - goods: [] - } + groupSnap: {} }) // 用于判断接口数据是否加载完成 const isDataLoaded = ref(false); @@ -621,10 +613,11 @@ }); specifications.sku_id = result.id specifications.product_id = result.productId - specifications.item = Object.assign({}, result, specifications.item); + // 添加多规格分组 + specifications.item.result = result if (result.isPauseSale == 0) { canSubmit.value = true; - skuBtnText.value = '添加到购物车' + // skuBtnText.value = '添加到购物车' } } catch (error) { canSubmit.value = false; @@ -682,55 +675,78 @@ } } - // 使用 find 方法查找购物车是否有匹配的数组 + // 根据购物车的数据匹配选中的商品查找是否有匹配的数组 const matchingProduct = async (data) => { - return matchedProducts.value.find(product => { - if (data.type === 'single') { - return product.skuId == data.skuId && product.id == data.id + console.log(specifications, matchedProducts.value, selectedOptions.value, '11111') + return matchedProducts.value.find((product, index) => { + if (data.type == 'package') { + // 套餐 + let result = []; + if (product.type == "package") { + JSON.parse(product.cartListinfo.pro_group_info).goods.forEach(item1 => { + selectedOptions.value.forEach(item2 => { + if (item1.proId === item2.proId && item1.skuId === item2 + .skuId) { + result.push(item1); + } + }); + }); + } + + return result.length > 0 ? result : false; + } else if (specifications.item.type == 'sku') { + // 多规格 + return product.skuId == data.id && product.id == data.productId } else { - return product.skuId == data.sku_id && product.id == data.product_id + // 其他 + return product.skuId == data.skuId && product.id == data.id } }); } // 提交选择并执行下一步操作的方法 const submitSelection = async () => { - if (!canSubmit.value) { - return false; + if (shopCartNumber.value > 0 && canSubmit.value) { + // 是否是套餐package + let res = await matchingProduct(specifications.item.type == "package" ? specifications.item : + specifications.item.result) + console.log(res) + if (res) { + await calculateValue(res.cartNumber, '+', shopCartNumber.value) + } + // 是否是套餐 有就传 + if (specifications.item.type == "package") { + specifications.groupSnap.goods = selectedOptions.value + } else { + specifications.groupSnap = null + } + console.log(specifications.groupSnap, 'specifications.groupSnap.goods') + websocketsendMessage({ + id: res ? res.cartListId : '', + type: 'shopping', + table_code: uni.cache.get('tableCode'), + shop_id: uni.cache.get('shopId'), + operate_type: res ? 'edit' : 'add', + product_id: specifications.product_id, + sku_id: specifications.sku_id, + number: res ? await calculateValue(res.cartNumber, '+', shopCartNumber.value) : + shopCartNumber.value, + pro_group_info: specifications.groupSnap, + goods_type: specifications.item.type == "package" ? 'package' : '' + }) + // 清空有无无清空套餐 + showShopsku.value = false } - let res = await matchingProduct(specifications) - if (res) { - await calculateValue(res.cartNumber, '+', shopCartNumber.value) - } - // 是否是套餐 有就传 - if (selectedOptions.value) { - specifications.groupSnap.goods = selectedOptions.value - } - websocketsendMessage({ - type: 'shopping', - table_code: uni.cache.get('tableCode'), - shop_id: uni.cache.get('shopId'), - operate_type: res ? 'edit' : 'add', - product_id: specifications.product_id, - sku_id: specifications.sku_id, - number: res ? await calculateValue(res.cartNumber, '+', shopCartNumber - .value) : shopCartNumber.value, - pro_group_info: specifications.groupSnap - }) - showShopsku.value = false - // 这里可以添加更多的业务逻辑,例如发送请求到后端等 + } //获取多规格数据 const clickspecifications = async (item, index, indexs, type) => { - // console.log(item, index, indexs, type) // 数量清零 shopCartNumber.value = 0 // 初始化 let data = { item: item, - index: '', - inedxs: '', type: '', product_id: '', sku_id: '' @@ -739,21 +755,18 @@ // 初始化 多规格选中 selectedSpecs.value = {} canSubmit.value = false - skuBtnText.value = '请选择规格' + // skuBtnText.value = '请选择规格' // single-单规格商品 sku-多规格商品 package-套餐商品 weight-称重商品 coupon-团购券 let res = await APIminiAppinfo(item.id) specifications.item = res if (specifications.item.type == "package") { selectedOptions.value = [] - specifications.product_id = item.id + specifications.product_id = res.id specifications.sku_id = item.skuId specifications.groupSnap = res.groupSnap[0] } // 购物车是否有商品 - specifications.item.cartListId = await matchingProduct(specifications.item) ? item.cartListId : '' - specifications.index = index - specifications.indexs = indexs - specifications.type = type + specifications.type = res.type specifications.item.selectSpecInfo = Object.fromEntries( Object.entries(specifications.item.selectSpecInfo).filter(([_, value]) => value.length > 0) ); @@ -764,11 +777,15 @@ // 单规格 const singleclick = async (item, i) => { - if (selectedOptions.value.length > 0) { - specifications.groupSnap.goods = selectedOptions.value - } // 判断购物车是否有该选中商品 let res = await matchingProduct(item) + // 是否是套餐 有就传 + console.log(specifications, '单规格') + if (specifications.item.type == "package") { + specifications.groupSnap.goods = selectedOptions.value + } else { + specifications.groupSnap = null + } websocketsendMessage({ id: res ? item.cartListId : '', type: 'shopping', @@ -777,19 +794,21 @@ operate_type: await calculateValue(item.cartNumber, i) == 'del' ? 'del' : res ? 'edit' : 'add', product_id: item.id, sku_id: item.skuId, - number: await calculateValue(item.cartNumber, i), - pro_group_info: specifications.groupSnap, + number: await calculateValue(item.cartNumber, i) + // pro_group_info: specifications.groupSnap, + // goods_type: specifications.item.type == "package" ? 'package' : '' + // pro_group_info: specifications.groupSnap }) } - // 封装加法函数 + const calculateValue = (cartNumber, i, step = 1) => { if (i == '+') { - const result = parseFloat(cartNumber) + step; + const result = parseFloat(cartNumber) + parseFloat(step); return result.toFixed(2); } else { // 当减到0返回del - const result = parseFloat(cartNumber) - step; + const result = parseFloat(cartNumber) - parseFloat(step); return result == 0 ? 'del' : result.toFixed(2); } } @@ -808,7 +827,10 @@ isConnected, sendMessage, closeSocket: manualClose, - receivedMessages + receivedMessages, + closeExistingConnection, + onShowconnect, + initNetworkListener } = useWebSocket(options); @@ -823,68 +845,70 @@ // 更新商品数量的方法 const updateProductQuantities = () => { - // 遍历购物车数组 - if (cartListFilter.value.length > 0) { - cartListFilter.value.forEach((cartItem) => { - shopProductList.productInfo.forEach((group) => { - group.productList.forEach((product) => { - if (product.id == cartItem.product_id && product.skuId == cartItem - .sku_id) { - product.cartNumber = cartItem.number - product.cartListId = cartItem.id - } - }); - }); + // 先将所有商品的 cartNumber 初始化为 0 + shopProductList.hots.forEach((i) => { + i.cartNumber = 0 + }) + // 遍历商品列表二维数组 + shopProductList.productInfo.forEach((group) => { + group.productList.forEach((product) => { + product.cartNumber = 0 }); - // 遍历购物车数组 - cartListFilter.value.forEach((cartItem) => { - // 遍历商品列表二维数组 - shopProductList.hots.forEach((group) => { - // 商品 id 匹配 - if (group.id == cartItem.product_id) { - // 更新商品的数量 - group.cartListId = cartItem.id - group.cartNumber = cartItem.number + }); + + // 再去更新数组的值 + cartListFilter.value.forEach((cartItem) => { + shopProductList.productInfo.forEach((group) => { + group.productList.forEach((product) => { + if (product.id == cartItem.product_id && product.skuId == cartItem + .sku_id) { + product.cartNumber = cartItem.number + product.cartListId = cartItem.id } }); }); - } else { - shopProductList.hots.forEach((i) => { - i.cartNumber = 0 - }) + }); + // 遍历购物车数组 + cartListFilter.value.forEach((cartItem) => { // 遍历商品列表二维数组 - shopProductList.productInfo.forEach((group) => { - group.productList.forEach((product) => { - product.cartNumber = 0 - }); + shopProductList.hots.forEach((group) => { + // 商品 id 匹配 + if (group.id == cartItem.product_id) { + // 更新商品的数量 + group.cartListId = cartItem.id + group.cartNumber = cartItem.number + } }); - } + }); } //websocket产值 const websocketsendMessage = (data) => { - sendMessage(data) + uni.$u.debounce(sendMessage(data), 500) } + // 用于记录已经处理过的消息的 msg_id + const processedMessageIds = new Set(); + // 监听接收到的消息变化 watchEffect(async () => { - if (isDataLoaded.value && receivedMessages.value.length > 0) { - const Message = receivedMessages.value[receivedMessages.value.length - 1]; + if (isDataLoaded.value && receivedMessages.value) { + const Message = receivedMessages.value if (Message) { // 心跳返回 过滤 if (Message.type == "ping_interval" || Message.msg_id == "ping_interval") { return false } + // 初始化 if (Message.operate_type == "shopping_init") { cartList.value = Message.data } - // 购物车数据更新从新请求 - if (Message.type == 'product') { - isDataLoaded.value = false; - uni.$u.debounce(productqueryProduct(), 500) - // 数据可以更新 + // 清空购物车 + if (Message.operate_type == 'shopping_cleanup') { + cartList.value = [] + showCart.value = false } // 初始化购物车数据 @@ -893,8 +917,8 @@ } // 删除除购物车 - if (Message.operate_type == 'shopping_del') { - cartList.value = cartList.value.filter(item => item.id !== Message.data.id); + if (Message.operate_type == 'shopping_del' && Message.status == 1) { + cartList.value = cartList.value.filter(item => item.id != Message.data.id); } // 添加或者减少购物后返回 @@ -910,10 +934,11 @@ }); } - // 清空购物车 - if (Message.operate_type == 'shopping_cleanup') { + // 购物车数据更新从新请求 + if (Message.type == 'product') { cartList.value = [] - showCart.value = false + isDataLoaded.value = false; + productqueryProduct() } //除去p 每次返回都回执消息 @@ -922,11 +947,11 @@ msg_id: Message.msg_id }) - // if(Message.status != 1){ - // uni.showToast({ - // title:'操作失败请稍后重试~' - // }) - // } + // 检查消息是否已经处理过 + if (processedMessageIds.has(Message.msg_id)) { + return; + } + processedMessageIds.add(Message.msg_id); // 初始化商品数量 await updateProductQuantities() @@ -937,78 +962,78 @@ // 更新购物车数据shopProductList.hots const matchedProducts = computed(() => { - if (!cartList.value) { - return false; - } - let Specialstop = null + if (cartList.value.length > 0) { + let Specialstop = null + + try { + Specialstop = [...[{ + id: "", + name: "", + productList: shopProductList.hots + }], ...shopProductList.productInfo] + } catch (error) { + Specialstop = shopProductList.productInfo + //TODO handle the exception + } + return cartList.value.map((cartItem) => { + for (const group of Specialstop) { + for (const product of group.productList) { + if (product.id == cartItem.product_id) { + return { + ...product, + cartListinfo: cartItem, + cartListId: cartItem.id, //购物车id + cartNumber: cartItem.number //增加一个数量算法 + // cartNumberToAdd: cartItem.number //增加一个数量算法 + }; - try { - Specialstop = [...[{ - id: "", - name: "", - productList: shopProductList.hots - }], ...shopProductList.productInfo] - } catch (error) { - Specialstop = shopProductList.productInfo - //TODO handle the exception - } - return cartList.value.map((cartItem) => { - for (const group of Specialstop) { - for (const product of group.productList) { - if (product.id == cartItem.product_id) { - // 多规格 - if (product.type == 'sku') { - product.skuList.forEach((item) => { - if (item.id == product.id && item.productId == product.id) { - product.salePrice = item.salePrice - product.memberPrice = item.memberPrice - product.originPrice = item.originPrice - } - }) } - // 单规格 - return { - ...product, - // cartListinfo:cartItem - cartListId: cartItem.id, - // cartNumberToAdd: product.type == 'weight' ? 1 : cartItem.number //增加一个数量算法 - cartNumberToAdd: cartItem.number //增加一个数量算法 - }; - } } - } - // 如果没找到匹配的商品,返回 null 或者其他默认值,这里返回 null - return null; - }).filter(item => item !== null); + // 如果没找到匹配的商品,返回 null 或者其他默认值,这里返回 null + return null; + }).filter(item => item !== null); + } else { + return [] + } + }) // 计算购物车商品总数量 const cartLists_count = computed(() => { - return matchedProducts.value.reduce((sum, item) => { - // 将 cartNumberToAdd 转换为数字 - const num = typeof item.cartNumberToAdd === 'string' ? parseFloat(item - .cartNumberToAdd) : item - .cartNumberToAdd; - return sum + num; - }, 0); + if (matchedProducts.value.length > 0) { + return matchedProducts.value.reduce((sum, item) => { + // 将 cartNumberToAdd 转换为数字 + // const num = typeof item.cartNumberToAdd === 'string' ? parseFloat(item.cartNumberToAdd) : item.cartNumberToAdd; + const num = typeof item.cartNumber === 'string' ? parseFloat(item.cartNumber) : item + .cartNumber; + return sum + num; + }, 0); + } else { + return 0; + } }); // 计算购物车商品总价格 const totalPrices = computed(() => { - // 购物车总数价格 - let cart = matchedProducts.value.reduce((total, item) => { - // 是否启用会员价 0否1是 - if (shopInfo.isVip == 1 && shopInfo.isMemberPrice == 1) { - // memberPrice会员价 - return total + parseFloat(item.memberPrice) * parseFloat(item.cartNumber); - } else { - // salePrice销售价 - return total + parseFloat(item.salePrice) * parseFloat(item.cartNumber); - } - }, 0); - // 向上取整并保留两位小数 - return cart = Math.ceil(cart * 100) / 100; + if (matchedProducts.value.length > 0) { + // 购物车总数价格 + let cart = matchedProducts.value.reduce((total, item) => { + // 是否启用会员价 0否1是 + if (shopInfo.isVip == 1 && shopInfo.isMemberPrice == 1) { + // memberPrice会员价 + return total + parseFloat(item.memberPrice) * parseFloat(item.cartNumber); + } else { + // salePrice销售价 + return total + parseFloat(item.salePrice) * parseFloat(item.cartNumber); + } + }, 0); + // 向上取整并保留两位小数 + return cart = Math.ceil(cart * 100) / 100; + } else { + return 0 + } + }); // 储存是否存在多次下单 @@ -1085,30 +1110,44 @@ try { shopProductList.hots = await productminiApphotsquery() shopProductList.productInfo = await APIgroupquery() - //第一步:将所有商品的 cartNumber 初始化为 0 - shopProductList.productInfo.forEach((group) => { - group.productList.forEach((product) => { - product.cartNumber = 0; - }); - }); - shopProductList.hots.forEach((i) => { - i.cartNumber = 0 - }) - scrollTopSize.value = 0 - topArr.value = [] - userStore.actionsAPIuser() - // 数据可以更新 - isDataLoaded.value = true; - } catch (error) { + } catch (error) {} + + // 如果商品报错就返回上一页 + if (!shopProductList.productInfo || !shopProductList.hots) { uni.navigateBack() - //TODO handle the exception + return false; } + //TODO handle the exception + //第一步:将所有商品的 cartNumber 初始化为 0 + shopProductList.productInfo.forEach((group) => { + group.productList.forEach((product) => { + product.cartNumber = 0; + }); + }); + shopProductList.hots.forEach((i) => { + i.cartNumber = 0 + }) + scrollTopSize.value = 0 + topArr.value = [] + // userStore.actionsAPIuser() + // 数据可以更新 + isDataLoaded.value = true; + } onLoad(async (e) => { await proxy.$onLaunched; }) + onShow(() => { + // 监听页面显示和隐藏 + onShowconnect() + }) + + onHide(() => { + closeExistingConnection() + }) + onMounted(async () => { await proxy.$onLaunched; // 获取当前页面栈 @@ -1133,6 +1172,8 @@ await productqueryProduct() setTimeout(() => { + // 启动网络监听 + initNetworkListener() getElementTop() }, 500) }) diff --git a/pages/user/member/components/registermember.vue b/pages/user/member/components/registermember.vue index cecc085..c0d1460 100644 --- a/pages/user/member/components/registermember.vue +++ b/pages/user/member/components/registermember.vue @@ -90,7 +90,8 @@ } from 'vue'; import { - APIshopUser + APIshopUser, + APIshopUserInfo } from '@/common/api/member.js' import { @@ -112,6 +113,8 @@ }, }); + // 定义要触发的事件 + const formInfo = reactive({ nickName: "", telephone: "", @@ -302,13 +305,7 @@ const registerMember = async () => { - // if ( userHeadImg.value == "" || userHeadImg.value == null ) { - // uni.showToast({ - // title: '请选择会员头像', - // icon: 'none' - // }); - // return; - // } + if (formInfo.nickName == "" || formInfo.nickName == null) { uni.showToast({ title: '请输入会员昵称', @@ -316,13 +313,7 @@ }); return; } - // if ( this.birthDay == "" || this.birthDay == null ) { - // uni.showToast({ - // title: '请选择日期', - // icon: 'none' - // }); - // return; - // } + if (formInfo.telephone == "" || formInfo.telephone == null) { uni.showToast({ title: '请获取手机号', @@ -337,7 +328,7 @@ }); return; } - let res = await APIshopUser({ + await APIshopUser({ // id: uni.cache.get('userInfo').id, // shopId: uni.cache.get('shopId'), nickName: formInfo.nickName, @@ -345,7 +336,6 @@ phone: formInfo.telephone, birthDay: formInfo.birthDay }) - // 定义自定义事件 let APIshopUserInfores = await APIshopUserInfo({ shopId: uni.cache.get('shopId') }) @@ -355,11 +345,11 @@ title: '会员加入成功', icon: 'none' }) + // 定义自定义事件 setTimeout(() => { - if (props.detailtype == 'detail') { - uni.navigateBack() - } + uni.navigateBack() }, 1500) + } diff --git a/pages/user/member/index.vue b/pages/user/member/index.vue index 5f44e0f..e26ce45 100644 --- a/pages/user/member/index.vue +++ b/pages/user/member/index.vue @@ -320,7 +320,6 @@ }); return false; } - console.log(infoForn, 111) console.log({ shopId: infoForn.shopId, activateId: infoForn.id, @@ -340,6 +339,7 @@ console.log(res) } + // 会员总信息 const asyncshopUserInfo = async () => { let res = await APIshopUserInfo({ @@ -349,6 +349,7 @@ uni.cache.set('ordershopUserInfo', res.shopInfo) infoForn.show = res.isVip == 1 ? false : true infoForn.userInfo = res + infoForn.shopUserInfo = res.shopInfo } const detailtype = ref('') @@ -377,10 +378,10 @@ infoForn.shopId = options.shopId ? options.shopId : uni.cache.get('shopId') } - let resone = await APIusershopInfodetail({ - shopId: infoForn.shopId - }) - infoForn.shopUserInfo = resone.shopInfo + // let resone = await APIusershopInfodetail({ + // shopId: infoForn.shopId + // }) + // infoForn.shopUserInfo = resone.shopInfo asyncshopUserInfo() if (options.type == 'detail') { detailtype.value = 'detail' diff --git a/pages/user/member/memberdetails.vue b/pages/user/member/memberdetails.vue index 02d4b4e..b76c4e1 100644 --- a/pages/user/member/memberdetails.vue +++ b/pages/user/member/memberdetails.vue @@ -115,7 +115,7 @@ }) const form = reactive({ - memberOpen: false, + memberOpen: true, shopName: "", amount: '', lucky: { @@ -153,11 +153,6 @@ }) } - // * 注册会员卡 - const getRegisterMember = () => { - this.memberOpen = e; - this.init() - } // 会员总信息 const asyncshopUserInfo = async () => { @@ -167,6 +162,7 @@ uni.cache.set('orderVIP', res) uni.cache.set('ordershopUserInfo', res.shopInfo) form.memberOpen = res.isVip == 1 ? false : true + shopUserInfo.shopExtend = res.shopExtendList[2] } @@ -184,14 +180,15 @@ // 获取页面参数 const pageParams = currentPage.options; if (pageParams.shopId) { - asyncshopUserInfo() - uni.cache.set('shopId', pageParams.shopId, 30) - let res = await APIusershopInfodetail({ - shopId: pageParams.shopId - }) - // 根据传的shopInfo来返回上面的值 - shopUserInfo.shopExtend = res.shopExtend.member_bg shopUserInfo.shopId = pageParams.shopId + uni.cache.set('shopId', pageParams.shopId, 30) + // let res = await APIusershopInfodetail({ + // shopId: pageParams.shopId + // }) + // 根据传的shopInfo来返回上面的值 + // shopUserInfo.shopExtend = res.shopExtend.member_bg + asyncshopUserInfo() + console.log(shopUserInfo.shopId) } }) diff --git a/pages/user/user.vue b/pages/user/user.vue index ed93c9e..9726047 100644 --- a/pages/user/user.vue +++ b/pages/user/user.vue @@ -107,7 +107,7 @@ const teblist = ref([]) const shopExtend = ref(null) const userInfo = reactive({}) - + const ShopId = ref(uni.cache.get('shopId')) const clickEvent = () => { diff --git a/stores/user.js b/stores/user.js index 27a68a4..473dc8a 100644 --- a/stores/user.js +++ b/stores/user.js @@ -229,6 +229,8 @@ export const productStore = defineStore('product', { try { let res = await APIshopUserInfo() uni.cache.set('shopUserInfo', res); + uni.cache.set('orderVIP', res) + uni.cache.set('ordershopUserInfo', res.shopInfo) resolve(true) } catch (e) { reject(false) @@ -244,10 +246,10 @@ export const productStore = defineStore('product', { // 获取店铺用户会员信息 if (uni.cache.get('shopId')) { this.actionsproductqueryProduct() + } else { + let res = await APIuser() + uni.cache.set('userInfo', res); } - let res = await APIuser() - uni.cache.set('userInfo', res); - // } resolve(true) } catch (e) { reject(false)