1 |
- "use strict";const i=require("../../common/vendor.js");require("../../api/list.js");const d=require("../../api/live.js");require("../../api/order.js");const C=require("../../api/home.js"),c=require("../../common/assets.js");var _="wss://live.test.ylrztop.com/ws/live-api/app/webSocket";const k={data(){return{liveItem:{liveId:null,shopping:!1,inputInfo:"",goodsList:[],goodsTotal:0,goodsPageNum:1,goodsPageSize:10,goodsLoading:!1,goodsNoMoreData:!1,goodsScrollHeight:0,goodsScrollTimer:null,goodsCurrentIndex:0,goodsCurrentPage:1,talkList:[],showWelcomeMessage:!1,redInfo:null,scrollIntoView:null},timer:null,isShowRed:!1,lastSwiperChangeTime:0,swiperChangeThrottle:300,lastClickTime:0,clickDelay:300,connectingLiveId:null,swiperDuration:0,videoRetryCounts:{},liveUserTotal:null,viewPageSize:10,viewPageNum:1,viewLoading:!1,viewNoMoreData:!1,scrollHeight:0,scrollTimer:null,socketInstance:null,reconnectCount:0,maxReconnectAttempts:3,isManualClose:!1,showRed:!0,searchTimer:null,reconnectTimer:null,isCollect:!1,showPurchasePrompt:!1,purchasePromptTimer:null,prevOrderCount:0,videoUrl:null,showType:1,boxHeight:300,liveViewers:[],likeName:0,hlsPlayer:null,livingUrl:"",products:{},store:{},orderUser:{},userType:0,timestamp:"",liveId:null,userinfo:"",talkdisabled:!1,autoplay:!1,showadd:!1,scrollIntoView:"",videoContext:"",livedata:{}}},onLoad(e){if(this.initTime(),console.log(e),e.liveId&&(this.liveId=e.liveId),this.userinfo=JSON.parse(i.index.getStorageSync("userInfo")),this.liveId==null){i.index.showToast({title:"未知错误,请联系管理员!",icon:"none"});return}console.log(this.liveId),this.getliving(this.liveId),this.initSocket(this.liveId);const t=i.index.getWindowInfo().platform;["mp-weixin","mp-alipay","mp-baidu","mp-toutiao"].includes(t)&&(i.index.showShareMenu?i.index.showShareMenu({withShareTicket:!0,success:()=>{console.log("分享菜单显示成功")},fail:o=>{console.error("分享菜单显示失败:",o)}}):console.warn("当前平台不支持 uni.showShareMenu"))},onReady(){},onShareAppMessage(){return{title:this.livedata.liveName,path:"/pages/home/living",imageUrl:this.products.image,success(e){console.log("分享成功",e)},fail(e){console.error("分享失败",e)}}},computed:{filteredViewers(){return Array.isArray(this.liveViewers)?this.liveViewers.slice(0,3):[]}},onHide(){const e=this.liveItem;e&&(this.pauseVideo(e),this.clearTimeTimer(e)),this.closeAllWebSockets()},onUnload(){this.closeWebSocket(),this.socketInstances={},this.removeAllEventListeners(),this.clearAllTimers(),this.hlsPlayer&&(this.hlsPlayer.destroy(),this.hlsPlayer=null),this.list.forEach(e=>{const t=`myVideo_${e.liveId}`,o=i.index.createVideoContext(t,this);o&&o.pause()})},watch:{"orderUser.count":{handler(e,t){e!==this.prevOrderCount&&(this.prevOrderCount=e,this.showPurchaseMessage())},immediate:!0}},methods:{openShop(){this.queryCollect(),this.liveItem.shopping=!0},onLiveStateChange(e,t){e.detail.code},onLiveError(e,t){this.videoError(e,t)},getCurrentActivities(e){e.liveId&&d.currentActivities(e.liveId).then(t=>{t.code==200?(this.$set(e,"goodsCard",t.goods),this.$set(e,"redInfo",t.red[0]),this.isShowRed=!0,this.$set(e,"lottery",t.lottery)):i.index.showToast({title:t.msg,icon:"none"})},t=>{})},calculateTimeDiff(e){if(!e.startTime){e.totalTime="00小时00分钟00秒";return}const t=e.startTime.replace(/-/g,"/").replace(" "," "),o=new Date(e.startTime),n=new Date;if(isNaN(o.getTime())){console.warn(`iOS 时间解析失败,原始时间:${e.startTime},转换后:${t}`),e.totalTime="00小时00分钟00秒";return}const s=Math.max(0,n-o),l=Math.floor(s/1e3),u=this.padZero(Math.floor(l/3600)),v=this.padZero(Math.floor(l%3600/60)),m=this.padZero(l%60);this.$set(e,"totalTime",`${u}:${v}:${m}`)},padZero(e){return e<10?`0${e}`:e},startTimeTimer(e){e.timeTimer&&clearInterval(e.timeTimer),this.calculateTimeDiff(e),e.timeTimer=setInterval(()=>{this.calculateTimeDiff(e)},1e3)},clearTimeTimer(e){e.timeTimer&&(clearInterval(e.timeTimer),e.timeTimer=null)},toggleViewerList(){const e=Date.now();e-this.lastClickTime>this.clickDelay&&(this.showadd=!this.showadd,this.lastClickTime=e)},closeAllWebSockets(){this.isManualClose=!0,Object.keys(this.socketInstances).forEach(e=>{try{this.socketInstances[e]&&this.socketInstances[e].instance&&(this.socketInstances[e].instance.close({code:1e3,reason:"页面关闭"}),console.log(`直播间 ${e} WebSocket 已关闭`))}catch(t){console.error(`关闭直播间 ${e} WebSocket 时出错:`,t)}}),this.socketInstances={}},removeAllEventListeners(){i.index.$off("initSocket"),i.index.$off("sendMsg"),i.index.$off("closeWebSocket"),i.index.$off("refreshOrder")},clearAllTimers(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.pingpangTimes&&(clearInterval(this.pingpangTimes),this.pingpangTimes=null),this.reconnectTimer&&(clearInterval(this.reconnectTimer),this.reconnectTimer=null),this.scrollTimer&&(clearTimeout(this.scrollTimer),this.scrollTimer=null),this.searchTimer&&(clearTimeout(this.searchTimer),this.searchTimer=null),this.purchasePromptTimer&&(clearTimeout(this.purchasePromptTimer),this.purchasePromptTimer=null)},playVideo(e){if(e)try{if(e.liveType===1&&e.livingUrl){const t=`myLivePlayer_${e.liveId}`,o=i.index.createLivePlayerContext(t,this);o&&o.play()}else if(e.liveType===2&&e.videoUrl){const t=`myVideo_${e.liveId}`,o=i.index.createVideoContext(t,this);o&&o.pause(()=>{o.play()})}}catch(t){console.error("播放视频失败:",t)}},pauseVideo(e){if(e)try{if(e.liveType===1){const t=`myLivePlayer_${e.liveId}`,o=i.index.createLivePlayerContext(t,this);o&&o.pause()}else if(e.liveType===2){const t=`myVideo_${e.liveId}`,o=i.index.createVideoContext(t,this);o&&o.pause()}}catch(t){console.error("暂停视频失败:",t)}},openViews(){this.$nextTick(()=>{i.index.createSelectorQuery().in(this).select(".view-box").boundingClientRect(t=>{t&&(this.scrollHeight=t.height-80-120)}).exec()})},resetLiveData(){const e={userinfo:this.userinfo,list:this.list,currentSwiperIndex:this.currentSwiperIndex};this.liveUserTotal=null,this.liveViewers=[],this.livingUrl="",this.videoUrl=null,this.products={},this.store={},this.orderUser={},this.talklist=[],this.livedata={},this.shopping=!1,this.inputInfo="",Object.assign(this,e)},async getliveUser(e=!1){const t=this.liveId;if(t){this.viewLoading=!0;try{const o=await d.watchUserList(t,this.viewPageSize,this.viewPageNum,!1);if(o.code===200){if(this.liveId!==t)return;if(this.liveUserTotal=o.total,o.rows.length===0){this.viewNoMoreData=!0;return}this.liveViewers=e?[...this.liveViewers,...o.rows]:o.rows,this.viewPageNum++}}catch(o){console.error("获取观众列表失败:",o)}finally{this.viewLoading=!1}}},handleScrollToLower(){this.scrollTimer&&clearTimeout(this.scrollTimer),this.scrollTimer=setTimeout(()=>{},1e3)},async getLiveMsg(e){if(!e||!e.liveId){console.error("getLiveMsg 错误:无效的 liveItem",{liveItem:e,currentIndex:this.currentSwiperIndex,listLength:this.list.length});return}try{const t=await d.liveMsg(e.liveId,30,1);if(t.code==200){const n=[...Array.isArray(t.rows)?t.rows:[]].reverse();this.$set(e,"talklist",n),this.$nextTick(()=>{this.$set(e,"scrollIntoView",`list_${n.length-1}`)})}}catch(t){console.error("获取聊天记录失败:",t)}},onRed(e){var o;if(!e.liveId||!((o=e.redInfo)!=null&&o.redId))return;let t={liveId:e.liveId,userId:this.userinfo.userId,redId:e.redInfo.redId};d.liveRed(t).then(n=>{this.isShowRed=!1,n.code==200?(console.log(this.isShowRed),console.log("点了this.liveId",liveItem.redInfo),i.index.showToast({title:n.msg,icon:"none"})):i.index.showToast({title:n.msg,icon:"none"})},n=>{})},handleSearchInput(){clearTimeout(this.searchTimer),this.searchTimer=setTimeout(()=>{this.queryCollect()},500)},showPurchaseMessage(){this.purchasePromptTimer&&clearTimeout(this.purchasePromptTimer),this.showPurchasePrompt=!0,this.purchasePromptTimer=setTimeout(()=>{this.showPurchasePrompt=!1},2e3)},truncateString(e,t){return e.length>t?e.slice(0,t)+"...":e},goOrderList(){i.index.navigateTo({url:"/pages_shop/order"})},initHlsPlayer(){if(i.Hls.isSupported()&&this.livingUrl){const e=document.getElementById("myVideo");e&&(this.hlsPlayer=new i.Hls,this.hlsPlayer.loadSource(this.livingUrl),this.hlsPlayer.attachMedia(e),this.hlsPlayer.on(i.Hls.Events.MANIFEST_PARSED,()=>{e.play()}))}},videoError(e,t){if(!(!t||t.liveId!==this.liveId)){if(this.videoRetryCounts[t.liveId]===void 0&&(this.videoRetryCounts[t.liveId]=0),this.videoRetryCounts[t.liveId]>=3){console.error(`直播间 ${t.liveId} 视频加载失败,停止重试`),i.index.showToast({title:"视频加载失败,请检查网络",icon:"none",duration:2e3});return}this.videoRetryCounts[t.liveId]++,setTimeout(()=>{t.liveId===this.liveId&&(console.log(`第${this.videoRetryCounts[t.liveId]}次重试播放视频`),this.playVideo(t))},2e3)}},async getliving(e){const t={id:e};try{const o=await C.getlive(t);if(o.code!==200){i.index.showToast({title:o.msg,icon:"none"});return}this.liveItem=o.data,this.liveItem.talklist=[],o.data.liveType===2?(this.$set(this.liveItem,"videoUrl",o.data.videoUrl),this.$set(this.liveItem,"livingUrl",""),this.$set(this.liveItem,"placeholderText","说点什么...")):o.data.liveType===1?(this.$set(this.liveItem,"livingUrl",o.data.flvHlsUrl),this.$set(this.liveItem,"videoUrl",""),this.$set(this.liveItem,"placeholderText","说点什么...")):(this.$set(this.liveItem,"livingUrl",""),this.$set(this.liveItem,"videoUrl","")),await this.getLiveMsg(this.liveItem),await this.getliveViewData(this.liveItem),this.getCurrentActivities(this.liveItem),this.$set(this.liveItem,"autoplay",o.data.liveType!==0),this.$set(this.liveItem,"showType",o.data.showType),this.$set(this.liveItem,"storeId",o.storeId)}catch(o){console.error("获取直播信息失败:",o),i.index.showToast({title:"获取直播信息失败",icon:"none"})}},maskString(e,t="*"){return e?String(e).split("").map((n,s)=>s===0?n:t).join(""):""},getPureDecimal(e,t=6){const o=Math.abs(e).toFixed(t).split(".")[1];return(o==null?void 0:o.replace(/0+$/,""))||""},goBack(){const e=this.liveItem;e&&this.pauseVideo(e),this.closeWebSocket(),getCurrentPages().length>1?i.index.navigateBack():i.index.reLaunch({url:"/pages/list/index"})},async onLike(e){if(!(!e||!e.liveId))try{const t=await d.liveDataLike(e.liveId);t!=null&&t.like?e.liveViewData.like++:i.index.showToast({title:t.msg,icon:"none"})}catch(t){console.error("点赞失败:",t)}},async getliveViewData(e){if(!(!e||!e.liveId))try{const t=await d.getLiveViewData(e.liveId);t.code==200&&this.$set(e,"liveViewData",t)}catch(t){console.error("获取直播间数据失败:",t),this.$set(e,"liveViewData",{like:0,watchCount:0})}},goShop(e,t){const o=this.liveItem;!o||!o.liveId||i.index.navigateTo({url:"/pages_shop/goods?productId="+e+"&liveId="+o.liveId+"&goodsId="+t+"&storeId="+o.storeId})},async queryCollect(){const e=this.liveItem;if(!e||!e.liveId)return;const{storeId:t}=e;if(t){e.inputInfo==null&&(e.inputInfo="");try{const o=await d.liveStore(e.liveId,e.inputInfo);o.code===200&&(this.$set(e,"products",o.data),this.products=o.data)}catch(o){console.error("获取小黄车商品失败:",o)}}},initTime(){const e=new Date;this.timestamp=e.getTime()},openCart(e){if(!e.storeId){i.index.showToast({title:"当前直播间暂未开通店铺",icon:"none"});return}e.shopping=!0},close(){this.showadd=!1},closeShop(){const e=this.liveItem;e&&this.$set(e,"shopping",!1)},getEWechatSdk(){},closeWebSocket(){var e;(e=this.socket)==null||e.close()},initSocket(e){if(e==null)return;this.connectingLiveId=e;const t=i.CryptoJS.HmacSHA256(`${e}${this.userinfo.userId}${this.userType}${this.timestamp}`,this.timestamp.toString()).toString(i.CryptoJS.enc.Hex);try{const o=i.index.connectSocket({url:`${_}?userId=${this.userinfo.userId}&liveId=${e}&userType=${this.userType}×tamp=${this.timestamp}&signature=${t}`,success:()=>{},fail:n=>{}});o.onOpen(n=>{this.socket=o}),o.onMessage(n=>{const s=this.liveItem;s&&this.handleSocketMessage(n,s)}),o.onError(n=>{console.log(n)}),o.onClose(()=>{console.log(`WebSocket 连接已关闭: ${e}`),this.connectingLiveId=null})}catch(o){console.error("创建 WebSocket 异常:",o),this.connectingLiveId=null,this.scheduleReconnect(e)}},handleSocketMessage(e,t){let o=JSON.parse(e.data);const n=o.data;if(o.code==200){const s={...n,cmd:n.cmd||"",ts:Date.now()};if(n.cmd=="sendMsg")this.$set(t,"talklist",[...t.talklist||[],s]),this.$nextTick(()=>{const l=t.talklist.length-1;this.$set(t,"scrollIntoView",`list_${l}`)});else if(n.cmd=="red")this.$set(t,"redInfo",JSON.parse(n.data)),this.isShowRed=!0,this.timer=setInterval(()=>{this.isShowRed=!0},t.redInfo.duration*1e3);else if(n.cmd=="entry"||n.cmd=="out")this.$set(t,"talklist",[...t.talklist,s]),this.$set(t,"showWelcomeMessage",!1),this.$set(t,"showWelcomeMessage",!0),this.getliveUser(!1),t.welcomeTimer&&clearTimeout(t.welcomeTimer),t.welcomeTimer=setTimeout(()=>{this.$set(t,"showWelcomeMessage",!1)},1e3);else if(n.cmd=="Integral"){let l={msg:n.msg,status:!0};this.$set(t,"integral",l)}else n.cmd=="blockUser"?i.index.removeStorage({key:"AppToken",success:()=>{i.index.reLaunch({url:"/pages/auth/login"})}}):n.cmd=="goods"&&this.$set(t,"goodsCard",JSON.parse(n.data))}else i.index.showToast({title:o.msg,icon:"none"})},sendMsg(e){if(!e||!e.liveId||e.isSending)return;e.isSending=!0,setTimeout(()=>{e.isSending=!1},800);const t=(e.value||"").trim();if(!t){i.index.showToast({title:"不能发送空消息",icon:"none"});return}const o=e.liveId;this.socket,this.$set(e,"value","");const n={liveId:o,userId:this.userinfo.userId,userType:0,cmd:"sendMsg",msg:t,nickName:this.userinfo.nickName,avatar:this.userinfo.avatar};try{this.socket.send({data:JSON.stringify(n),success:()=>{},fail:s=>{i.index.showToast({title:s,icon:"none"}),this.$set(e,"value",t)}})}catch{}}}};if(!Array){const e=i.resolveComponent("u-avatar"),t=i.resolveComponent("u-input"),o=i.resolveComponent("u-popup");(e+t+o)()}const x=()=>"../../uni_modules/uview-plus/components/u-avatar/u-avatar.js",L=()=>"../../uni_modules/uview-plus/components/u-input/u-input.js",P=()=>"../../uni_modules/uview-plus/components/u-popup/u-popup.js";Math||(x+L+P)();function V(e,t,o,n,s,l){var u,v,m,g,p,f,w,I,T,y;return i.e({a:i.o((...r)=>l.goBack&&l.goBack(...r)),b:c._imports_0$2,c:i.p({src:s.liveItem.liveImgUrl||e.$img.logo,size:"32"}),d:i.t(s.liveItem.liveName?l.truncateString(s.liveItem.liveName,8):"未命名"),e:Array.isArray(l.filteredViewers)},Array.isArray(l.filteredViewers)?{f:i.f(l.filteredViewers,(r,a,h)=>({a,b:r.avatar||e.$img.logo}))}:{},{g:i.t(s.liveUserTotal||0),h:i.o((...r)=>l.toggleViewerList&&l.toggleViewerList(...r)),i:i.o(r=>l.onLike(s.liveItem)),j:c._imports_1$3,k:i.t(((u=s.liveItem.liveViewData)==null?void 0:u.like)||0),l:c._imports_2,m:i.n(s.liveItem.showType==1?"siderow-group":"side-group"),n:((v=s.liveItem.redInfo)==null?void 0:v.redStatus)==1&&s.isShowRed},((m=s.liveItem.redInfo)==null?void 0:m.redStatus)==1&&s.isShowRed?{o:i.o(r=>l.onRed(s.liveItem)),p:c._imports_3}:{},{q:s.liveItem.livingUrl&&s.liveItem.liveType===1},s.liveItem.livingUrl&&s.liveItem.liveType===1?{r:"myLivePlayer_"+s.liveItem.liveId,s:i.n(s.liveItem.showType==1?"video_row":"videotop"),t:s.liveItem.livingUrl,v:s.liveItem.showType==1?"horizontal":"vertical",w:i.o(r=>l.onLiveStateChange(r,s.liveItem)),x:i.o(r=>l.onLiveError(r,s.liveItem))}:{},{y:s.liveItem.videoUrl},s.liveItem.videoUrl?{z:i.n(s.liveItem.showType==1?"video_row":"videotop"),A:s.liveItem.videoUrl,B:i.o((...r)=>l.videoError&&l.videoError(...r))}:{},{C:s.liveItem.videoUrl},s.liveItem.videoUrl?{D:i.t(s.liveItem.totalTime)}:{},{E:i.f(s.liveItem.talklist,(r,a,h)=>({a:i.t(r.msg),b:a,c:r.cmd=="announcement"})),F:i.t(s.liveItem.messageContent),G:i.f(s.liveItem.talklist,(r,a,h)=>({a:i.t(r.nickName),b:i.t(r.msg),c:a,d:`list_${a}`,e:r.cmd!="red"&&r.cmd!="out"&&r.cmd!="entry"})),H:s.liveItem.showWelcomeMessage},s.liveItem.showWelcomeMessage?{I:i.f(s.liveItem.talklist,(r,a,h)=>({a:i.t(r.nickName),b:i.t(r.msg),c:a,d:r.cmd=="entry"||r.cmd=="out"})),J:i.t(s.liveItem.messageContent)}:{},{K:s.liveItem.scrollIntoView,L:i.o(r=>s.liveItem.value=r),M:i.p({placeholder:s.liveItem.placeholderText,border:"none",customStyle:"font-size:24rpx;",shape:"circle",color:"#fff",placeholderStyle:"color:#e7e7e7",modelValue:s.liveItem.value}),N:i.o(r=>l.sendMsg(s.liveItem)),O:c._imports_4,P:i.o(r=>l.openCart(s.liveItem)),Q:c._imports_5,R:c._imports_6,S:i.o(r=>s.liveItem.goodsCard.isShow=!1),T:(g=s.liveItem.goodsCard)==null?void 0:g.imgUrl,U:i.t((p=s.liveItem.goodsCard)==null?void 0:p.price),V:i.t((f=s.liveItem.goodsCard)==null?void 0:f.otPrice),W:i.t((w=s.liveItem.goodsCard)==null?void 0:w.productName),X:i.o(r=>{var a,h;return l.goShop((a=s.liveItem.goodsCard)==null?void 0:a.productId,(h=s.liveItem.goodsCard)==null?void 0:h.goodsId)}),Y:i.o(r=>{var a;return!((a=s.liveItem.goodsCard)!=null&&a.isShow)}),Z:i.p({show:(I=s.liveItem.goodsCard)==null?void 0:I.isShow,round:"20rpx",mode:"center",bgColor:"#ffffff"}),aa:c._imports_7,ab:i.t((T=s.liveItem.integral)==null?void 0:T.msg),ac:i.o(r=>s.liveItem.integral.status=e.flase),ad:i.o(r=>{var a;return!((a=s.liveItem.integral)!=null&&a.status)}),ae:i.p({show:(y=s.liveItem.integral)==null?void 0:y.status,round:"20rpx",mode:"center",bgColor:"#ffffff"}),af:i.f(s.liveViewers,(r,a,h)=>({a:i.t(a+1),b:a===0?"#FF3B30":a===1?"#FF9500":a===2?"#FFCC00":"#8E8E93",c:a<3?"bold":"normal",d:"471975a0-5-"+h+",471975a0-4",e:i.p({src:r.avatar||e.$img.logo,size:"32"}),f:i.t(r.nickName||"未命名"),g:a})),ag:s.viewNoMoreData&&s.liveViewers.length>0},s.viewNoMoreData&&s.liveViewers.length>0?{}:{},{ah:s.scrollHeight+"px",ai:i.o((...r)=>l.handleScrollToLower&&l.handleScrollToLower(...r)),aj:i.o(l.close),ak:i.o(l.openViews),al:i.p({show:s.showadd,round:"20rpx",bgColor:"#ffffff"}),am:i.p({src:s.store.logoUrl,size:"36"}),an:c._imports_1$2,ao:i.o([r=>s.liveItem.inputInfo=r.detail.value,(...r)=>l.handleSearchInput&&l.handleSearchInput(...r)]),ap:s.liveItem.inputInfo,aq:c._imports_9,ar:i.o(r=>l.goOrderList(s.liveItem)),as:i.f(s.products,(r,a,h)=>i.e({a:r.imgUrl,b:i.t(a+1),c:i.t(r.productName),d:i.t(r.sales),e:i.t(Math.trunc(r.price)),f:i.t(l.getPureDecimal(r.price)?l.getPureDecimal(r.price):"00"),g:r.isFavorite},r.isFavorite?{h:i.o(S=>e.onGoodsCollect(r),a),i:c._imports_10}:{j:i.o(S=>e.onGoodsCollect(r),a),k:c._imports_11},{l:r.status==1},r.status==1?{m:i.o(S=>l.goShop(r.productId,r.goodsId),a)}:r.status==0?{}:{},{n:r.status==0,o:a})),at:s.boxHeight+"px",av:i.o(l.closeShop),aw:i.o(l.openShop),ax:i.p({show:s.liveItem.shopping,round:"20rpx",bgColor:"f3f5f9"})})}const M=i._export_sfc(k,[["render",V],["__scopeId","data-v-471975a0"]]);k.__runtimeHooks=2;wx.createPage(M);
|