living.vue 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540
  1. <template>
  2. <view class="swiper-wrapper">
  3. <swiper class="swiper-container" :current="currentSwiperIndex" :circular="false" vertical
  4. @change="onSwiperChange" :style="{height: '100vh'}" :duration="swiperDuration">
  5. <swiper-item v-for="(liveItem, index) in list" :key="liveItem.liveId">
  6. <view class="container" :class="{active: currentSwiperIndex === index}">
  7. <view class="blackbg"></view>
  8. <view class="content">
  9. <!-- 页面内容 -->
  10. <view style="position: fixed;top: 0;z-index: 5;" class="content-top">
  11. <view class="u-flex-y-center">
  12. <image @click="goBack" style="width: 60rpx;height: 64rpx;margin-right: 26rpx;"
  13. src="/static/images/live/return.png"></image>
  14. <view class="align-center"
  15. style="padding: 6rpx 4rpx;height: 64rpx;background: rgba(0,0,0,0.5);border-radius: 32rpx;">
  16. <u-avatar :src="liveItem.liveImgUrl||$img.logo" size="32"></u-avatar>
  17. <view class="colorf ml10 mr6">
  18. <view>{{liveItem.liveName?truncateString(liveItem.liveName,5):"未命名"}}</view>
  19. </view>
  20. </view>
  21. </view>
  22. <view class="u-flex-end align-center" @click="toggleViewerList" style="margin-top: 100rpx;">
  23. <image class="w52 h52 mr4" v-for="(item,viewerIndex) in filteredViewers"
  24. :key="viewerIndex" style="border-radius: 26rpx;" :src="item.avatar||$img.logo">
  25. </image>
  26. <view class="sum">{{liveUserTotal||0}}</view>
  27. </view>
  28. </view>
  29. <!-- 右边的 -->
  30. <view :class=" liveItem.showType==1 ? 'siderow-group' : 'side-group'">
  31. <view class="side-item">
  32. <image class="image" @click="onLike(liveItem)" src="/static/images/live/like.png"></image>
  33. <view>{{liveItem.liveViewData?.like||0}}</view>
  34. </view>
  35. <!-- <view class="side-item">
  36. <image @click="goStore(liveItem)" src="/static/images/live/shop.png"></image>
  37. <view>店铺</view>
  38. </view> -->
  39. <view class="side-item">
  40. <button open-type="share" class="button">
  41. <image class="image" src="/static/images/live/share.png" mode="widthFix"></image>
  42. </button>
  43. <view>分享</view>
  44. </view>
  45. </view>
  46. <!-- 红包内容 -->
  47. <view style="position: fixed;top:120rpx;left: 0rpx; z-index: 5;" class="content-top">
  48. <view class="u-flex-y-center">
  49. <image @click="onRed(liveItem)" v-if="liveItem.redInfo?.redStatus==1"
  50. style="width: 70rpx;height: 70rpx;" src="/static/images/hongbao.png"></image>
  51. </view>
  52. </view>
  53. <view class="shop-prompt u-flex-y-center" v-if="showPurchasePrompt&&orderUser?.count">
  54. <image class="w32 h32 mr8" src="/static/images/live/shopping.png"></image>
  55. <text> {{orderUser.userName ? maskString(orderUser.userName) : ''}} 等
  56. {{orderUser.count || 0}}
  57. 人正在去购买</text>
  58. </view>
  59. <view class="videolist" style="margin: auto 0">
  60. <view class="video" style="height:100vh">
  61. <!-- 视频组件 -->
  62. <video v-if="currentSwiperIndex === index && liveItem.livingUrl" :id="'myVideo_' + liveItem.liveId"
  63. :class="liveItem.showType == 1 ? 'video_row' : 'videotop'" :src="liveItem.livingUrl"
  64. :autoplay="currentSwiperIndex === index" :controls='false' object-fit='contain'
  65. :custom-cache="false" :enable-progress-gesture="false"
  66. vslide-gesture-in-fullscreen='true' :show-center-play-btn="false"
  67. :http-cache="false" @error="videoError">
  68. </video>
  69. <video v-if="currentSwiperIndex === index && liveItem.videoUrl"
  70. :class="liveItem.showType == 1 ? 'video_row' : 'videotop'" :src="liveItem.videoUrl"
  71. :autoplay="currentSwiperIndex === index" :controls='false' object-fit='contain'
  72. :custom-cache="false" :enable-progress-gesture="false"
  73. vslide-gesture-in-fullscreen='true' :show-center-play-btn="false"
  74. :http-cache="false" loop @error="videoError">
  75. </video>
  76. <view v-if="liveItem.videoUrl" class="time">{{liveItem.totalTime}}</view>
  77. <!-- 加载提示 -->
  78. <!-- <view v-if="liveItem.loading" class="loading-tip">
  79. <u-loading mode="circle" color="#ffffff" size="36"></u-loading>
  80. <text class="loading-text">加载中...</text>
  81. </view> -->
  82. </view>
  83. </view>
  84. <!-- 底部聊天区域 -->
  85. <view class="pb40 mt90" style="position: fixed;bottom: 0;width: 100%;">
  86. <view class="w100 h300 mt20">
  87. <scroll-view enable-flex scroll-y="true" class="talk p20 scrolly flex-1 column"
  88. style="width: calc(100% - 40rpx);height: calc(100% - 40rpx);"
  89. :scroll-into-view="liveItem.scrollIntoView">
  90. <view>
  91. <view class="list justify-start" v-for="(item,talkIndex) in liveItem.talklist"
  92. :key="talkIndex" v-show="item.cmd=='announcement'">
  93. <view class="talk-list ml16 justify-start">
  94. <view class="fs24">
  95. <text class='fs24 colorf'>
  96. {{item.msg}}直播间{{liveItem.messageContent}}</text>
  97. </view>
  98. </view>
  99. </view>
  100. </view>
  101. <view class="list justify-start" v-for="(item,talkIndex) in liveItem.talklist"
  102. :key="talkIndex" :id="`list_${talkIndex}`"
  103. v-show="item.cmd!='red'&&item.cmd!='out'&&item.cmd!='entry'">
  104. <view class="talk-list ml16 justify-start">
  105. <view class="fs24">
  106. <text style="color: #FFDA73;">{{item.nickName}}:</text>
  107. <text class='fs24 colorf'>{{item.msg}}</text>
  108. </view>
  109. </view>
  110. </view>
  111. <view v-if="liveItem.showWelcomeMessage" class="welcome-message">
  112. <view class="list justify-start" v-for="(item,talkIndex) in liveItem.talklist"
  113. :key="talkIndex" v-show="item.cmd=='entry'||item.cmd=='out'">
  114. <view class="talk-list ml16 justify-start">
  115. <view class="fs24">
  116. <text style="color: #ff89d6;">{{item.nickName}} </text>
  117. <text class='fs24 colorf'>
  118. {{item.msg}}直播间{{liveItem.messageContent}}</text>
  119. </view>
  120. </view>
  121. </view>
  122. </view>
  123. </scroll-view>
  124. </view>
  125. <!-- 底部输入框和操作按钮 -->
  126. <view class="justify-between p24">
  127. <view class="u-flex-y-center"
  128. style="background:rgba(57, 57, 57, 0.8);padding:10rpx 14rpx 10rpx 32rpx;width: 580rpx;box-sizing:border-box;border-radius:36rpx;">
  129. <u-input :placeholder="liveItem.placeholderText" border="none"
  130. customStyle='font-size:24rpx;' v-model="liveItem.value" shape='circle'
  131. color='#fff' placeholderStyle='color:#e7e7e7' class="ml20">
  132. </u-input>
  133. <view class="send" @click="sendMsg(liveItem)">发送</view>
  134. </view>
  135. <view class="justify-between mr15 align-center">
  136. <!-- <view class="icon ml20" @click="onLike(liveItem)">
  137. <image src="/static/images/live/like.png" class="w56 h56"></image>
  138. <view>{{liveItem.liveViewData?.like||0}}</view>
  139. </view>
  140. <view class="icon ml20">
  141. <button open-type="share" class="button">
  142. <image src="/static/images/live/share.png" class="w56 h56"></image>
  143. </button>
  144. <view>分享</view>
  145. </view> -->
  146. <view class="icon-bg ml20" @click="openCart(liveItem)">
  147. <image src="/static/images/shopping.png" class="w48 h48"></image>
  148. </view>
  149. </view>
  150. </view>
  151. </view>
  152. <!-- 弹出商品 -->
  153. <!-- v-if="liveItem.goodsCard.isShow" -->
  154. <!-- <view class="goods">
  155. <view class="top">
  156. <view class="left">
  157. <image class="w30 h30 mr8" src="/static/images/signal.png"></image>讲解中
  158. </view>
  159. <image class="w30 h30" src="/static/images/close.png"
  160. @click="liveItem.goodsCard.isShow=false"></image>
  161. </view>
  162. <image class="photo" :src="liveItem.goodsCard.imgUrl"></image>
  163. <view class="item">
  164. <view class="price"><text class="red">¥{{liveItem.goodsCard.price}} </text><text
  165. class="del">¥{{liveItem.goodsCard.otPrice}}</text></view>
  166. <view class="title oneline-hide">{{liveItem.goodsCard.productName}}</view>
  167. <view class="button">立即抢购</view>
  168. </view>
  169. </view> -->
  170. </view>
  171. <u-popup :show="liveItem.goodsCard.isShow" @close="!liveItem.goodsCard.isShow" round='20rpx'
  172. mode="center" bgColor='#ffffff'>
  173. <view class="goods">
  174. <view class="top">
  175. <view class="left">
  176. <image class="w30 h30 mr8" src="/static/images/signal.png"></image>讲解中
  177. </view>
  178. <image class="w30 h30" src="/static/images/close.png"
  179. @click="liveItem.goodsCard.isShow=false"></image>
  180. </view>
  181. <image class="photo" :src="liveItem.goodsCard.imgUrl"></image>
  182. <view class="item">
  183. <view class="price"><text class="red">¥{{liveItem.goodsCard.price}} </text><text
  184. class="del">¥{{liveItem.goodsCard.otPrice}}</text></view>
  185. <view class="title oneline-hide">{{liveItem.goodsCard.productName}}</view>
  186. <view class="button"
  187. @click="goShop(liveItem.goodsCard.productId,liveItem.goodsCard.goodsId)">立即抢购</view>
  188. </view>
  189. </view>
  190. </u-popup>
  191. <!-- 观众列表弹窗 -->
  192. <u-popup :show="showadd" @close="close" @open="openViews" round='20rpx' bgColor='#ffffff'>
  193. <view class="view-box">
  194. <view class="t-c fs30">在线观众</view>
  195. <scroll-view scroll-y class="scroll-content" :style="{height: scrollHeight + 'px'}"
  196. @scrolltolower="handleScrollToLower">
  197. <view class="fs24 u-flex-y-center mb20" v-for="(item,index) in liveViewers"
  198. :key="index">
  199. <view
  200. :style="{color: index === 0 ? '#FF3B30' : index === 1 ? '#FF9500' : index === 2 ? '#FFCC00' : '#8E8E93',fontWeight: index < 3 ? 'bold' : 'normal',width: '50rpx'}"
  201. class="mr10">{{index+1}}</view>
  202. <u-avatar :src="item.avatar||$img.logo" size="32"></u-avatar>
  203. <text class="ml16">{{item.nickName||"未命名"}}</text>
  204. </view>
  205. <view class="no-more" v-if="viewNoMoreData && liveViewers.length > 0">
  206. <text>没有更多了</text>
  207. </view>
  208. </scroll-view>
  209. </view>
  210. </u-popup>
  211. <!-- 商品弹窗 -->
  212. <u-popup :show="liveItem.shopping" @close="closeShop" @open="openShop" round='20rpx'
  213. bgColor='f3f5f9'>
  214. <view class="shoppop">
  215. <view class="shoppop-top">
  216. <u-avatar :src="store.logoUrl" size="36" class="ml16"></u-avatar>
  217. <view class="search-input u-flex-y-center">
  218. <image style="width: 24rpx;margin-right: 16rpx;" src="/static/images/search.png"
  219. mode="widthFix">
  220. </image>
  221. <input placeholder="请搜索商品" v-model="liveItem.inputInfo"
  222. @input="handleSearchInput" />
  223. </view>
  224. <view class="t-c search-top" style="margin-right: 48rpx;">
  225. <image @click="onStoreCollect(liveItem)" v-if="store.isFavorite"
  226. style="width:40rpx;height: 40rpx;" src="/static/images/collect_select.png">
  227. </image>
  228. <image v-else @click="onStoreCollect(liveItem)" style="width: 32rpx;height: 32rpx;"
  229. src="/static/images/collect.png"></image>
  230. <view>收藏</view>
  231. </view>
  232. <view class="t-c search-top" @click="goOrderList(liveItem)">
  233. <image style="width: 40rpx;height: 40rpx;" src="/static/images/order.png"></image>
  234. <view>订单</view>
  235. </view>
  236. </view>
  237. <scroll-view enable-flex scroll-y class="shop-list" :style="{ height: boxHeight + 'px' }">
  238. <view class="list-item" v-for="(item,index) in products" :key="index">
  239. <view class="goods-img">
  240. <image :src="item.imgUrl" mode="widthFix"></image>
  241. <view class="goods-label">{{index+1}}</view>
  242. </view>
  243. <view class="goods-right">
  244. <view class="goods-title">{{item.productName}}</view>
  245. <view class="goods-people">{{item.sales}} 人已购</view>
  246. <view class="goods-shop">
  247. <text class="nummber"><text
  248. style="font-size: 20rpx;font-weight: 600;">¥</text><text
  249. style="font-size: 36rpx;font-weight: bold;">{{Math.trunc(item.price)}}</text>.{{getPureDecimal(item.price)?getPureDecimal(item.price):'00'}}/日</text>
  250. <view class="btn-group u-flex-y-center">
  251. <view class="collect-btn">
  252. <image v-if="item.isFavorite" @click="onGoodsCollect(item)"
  253. style="width: 32rpx;height: 32rpx;"
  254. src="/static/images/collect_select.png">
  255. </image>
  256. <image v-else @click="onGoodsCollect(item)"
  257. style="width: 32rpx;height: 32rpx;"
  258. src="/static/images/collect.png">
  259. </image>
  260. </view>
  261. <view v-if="item.status==1" class="shop-btn"
  262. @click="goShop(item.productId,item.goodsId)">去购买 </view>
  263. <view v-else-if="item.status==0" class="shop-btn">
  264. 已下架</view>
  265. </view>
  266. </view>
  267. </view>
  268. </view>
  269. </scroll-view>
  270. </view>
  271. </u-popup>
  272. </view>
  273. </swiper-item>
  274. </swiper>
  275. </view>
  276. </template>
  277. <script>
  278. import Hls from 'hls.js';
  279. import CryptoJS from 'crypto-js'
  280. import {
  281. liveList
  282. } from '@/api/list'
  283. import {
  284. liveRed, // 点击领红包
  285. liveDataLike, // 点赞
  286. collectStore, // 店铺收藏/取消收藏
  287. collectGoods, // 商品收藏/取消收藏
  288. store, // 查询店铺
  289. showGoods, //弹出商品卡片
  290. // follow, // 关注/取消关注
  291. watchUserList, //获取直播间用户(展示在线用户)
  292. liveMsg, //获取最近聊天记录
  293. // 小黄车
  294. liveStore, //店铺展示,
  295. // liveGoodsDetail, //商品详情,
  296. liveOrderUser, //正在购买
  297. getLiveInfo, //获取直播间信息接口
  298. getLiveViewData //直播间点赞、关注、在线人数数据
  299. } from '@/api/live'
  300. import {
  301. liveOrderList, // 订单列表
  302. } from '@/api/order'
  303. import parse from '/uni_modules/uview-plus/libs/config/props/parse';
  304. import {
  305. LiveWS
  306. } from '@/utils/liveWS.js'
  307. import {
  308. getlive,
  309. // gettextlist,
  310. getAnswerlist,
  311. submitAnswer
  312. } from '@/api/home'
  313. var wsUrl = "wss://live.test.ylrztop.com/ws/live-api/app/webSocket"; //余红奇
  314. // var wsUrl = "ws://192.168.10.166:7114/app/webSocket"; //余红奇
  315. // var wsUrl = "ws://192.168.10.125:7114/app/webSocket"; //涂小龙
  316. // var wsUrl = "ws://live.test.ylrztop.com/prod-api/app/webSocket"; //余红奇
  317. // var wsUrl = "ws://nd383294.natappfree.cc/app/webSocket"; //余红奇
  318. // var wsUrl = "ws://v56c9b8e.natappfree.cc/app/webSocket"; //余红奇
  319. // var wsUrl = "ws://192.168.10.170:7114/app/webSocket"; //陈果
  320. // var wsUrl = "ws://live.ylrzcloud.com/socket/app/webSocket";
  321. var pingpangTimes = null;
  322. var initTimes = null;
  323. var isSocketOpen = false;
  324. var socket = null;
  325. export default {
  326. data() {
  327. return {
  328. // 新增:滑动节流相关变量
  329. lastSwiperChangeTime: 0, // 上次切换时间戳
  330. swiperChangeThrottle: 300, // 切换节流阈值(毫秒)
  331. lastClickTime: 0,
  332. clickDelay: 300, // 300ms内只响应一次点击
  333. connectingLiveId: null, // 记录正在连接的直播间ID
  334. swiperDuration: 0, // 初始化为0,首次加载无动画
  335. videoRetryCounts: {}, // 记录每个直播间的视频重试次数,格式: { liveId: 次数 }
  336. socketInstances: {}, // 改为对象存储多个socket实例
  337. currentSwiperIndex: 0, // 当前swiper索引
  338. list: [], // 直播间列表
  339. preloading: false, // 预加载状态
  340. liveUserTotal: null,
  341. viewPageSize: 10, // 每页数量
  342. viewPageNum: 1, // 当前页码
  343. viewLoading: false, // 是否正在加载
  344. viewNoMoreData: false, // 是否没有更多数据
  345. scrollHeight: 0,
  346. scrollTimer: null, // 滚动防抖定时器
  347. socketInstance: null, // 统一管理 socket 实例
  348. reconnectCount: 0,
  349. maxReconnectAttempts: 3,
  350. isManualClose: false, // 标记是否手动关闭
  351. showRed: true,
  352. // redInfo: {},
  353. // inputInfo: '',
  354. searchTimer: null,
  355. // storeId: null,
  356. reconnectTimer: null,
  357. isCollect: false,
  358. showPurchasePrompt: false,
  359. purchasePromptTimer: null,
  360. prevOrderCount: 0, // 用于记录上一次的购买人数
  361. videoUrl: null,
  362. showType: 1, //横屏1 竖屏2
  363. boxHeight: 300, //小黄车高度
  364. // isFollow: false,
  365. // liveViewData: {},
  366. liveViewers: [], //观众
  367. likeName: 0,
  368. hlsPlayer: null, // HLS播放器实例,
  369. livingUrl: "",
  370. products: {},
  371. store: {},
  372. orderUser: {}, //正在购买
  373. userType: 0,
  374. timestamp: '',
  375. liveId: null,
  376. // userId: uni.getStorageSync("userInfo.userId"),
  377. // isZoom: false, //点赞按钮控制是否放大
  378. userinfo: '', //用户信息
  379. // path: 'http://192.168.10.166/dev-api', //余红奇
  380. // path: 'http://v56c9b8e.natappfree.cc', //余红奇
  381. // path: 'live.test.ylrztop.com/prod-api', //余红奇
  382. // path: 'http://192.168.10.170/dev-api', //陈果
  383. // value: '',
  384. talkdisabled: false, //输入框是否禁用
  385. autoplay: false, //视频自动播放
  386. showadd: false,
  387. // talklist: [],
  388. scrollIntoView: '',
  389. videoContext: '',
  390. // thistime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
  391. // showWelcomeMessage: false,
  392. // isSubmit: false,
  393. // messageContent: "",
  394. // showziliao: false,
  395. // isScreen: true,
  396. // shopping: false, //小黄车弹窗
  397. // scrollTop: 0, //弹幕
  398. // old: {
  399. // scrollTop: 0
  400. // },
  401. livedata: {}, //直播间点赞、关注、在线人数数据
  402. };
  403. },
  404. onLoad(options) {
  405. this.initTime();
  406. if (options.liveId) {
  407. this.liveId = options.liveId; // 仅当 liveId 变化时更新
  408. }
  409. this.userinfo = JSON.parse(uni.getStorageSync("userInfo"))
  410. // 初始化直播间列表
  411. this.initLiveList(options);
  412. this.getliveUser(false); // 调用获取在线用户接口
  413. const platform = uni.getWindowInfo().platform;
  414. // 初始化直播间列表
  415. if (['mp-weixin', 'mp-alipay', 'mp-baidu', 'mp-toutiao'].includes(platform)) {
  416. // 确保 API 存在再调用
  417. if (uni.showShareMenu) {
  418. uni.showShareMenu({
  419. withShareTicket: true, // 可选参数,根据需求配置
  420. success: () => {
  421. console.log('分享菜单显示成功');
  422. },
  423. fail: (err) => {
  424. console.error('分享菜单显示失败:', err);
  425. }
  426. });
  427. } else {
  428. console.warn('当前平台不支持 uni.showShareMenu');
  429. }
  430. } else {
  431. // console.log('当前平台无需显示分享菜单');
  432. }
  433. },
  434. onReady() {},
  435. onShareAppMessage() {
  436. return {
  437. // title: this.product.title,
  438. title: this.livedata.liveName,
  439. path: '/pages/home/living',
  440. imageUrl: this.products.image,
  441. success(res) {
  442. console.log("分享成功", res);
  443. },
  444. fail(err) {
  445. console.error("分享失败", err);
  446. }
  447. };
  448. },
  449. computed: {
  450. filteredViewers() {
  451. if (!this.liveViewers) {
  452. return
  453. } else {
  454. return this.liveViewers.slice(0, 3);
  455. }
  456. }
  457. },
  458. onHide() {
  459. const currentLive = this.list[this.currentSwiperIndex];
  460. if (currentLive) {
  461. this.pauseVideo(currentLive);
  462. this.clearTimeTimer(currentLive); // 隐藏时清除当前直播间定时器
  463. } // 隐藏时关闭所有连接
  464. this.closeAllWebSockets();
  465. },
  466. onUnload() {
  467. // 清除所有直播间的时间定时器
  468. this.list.forEach(liveItem => {
  469. this.clearTimeTimer(liveItem);
  470. });
  471. // 关闭所有WebSocket连接
  472. this.closeAllWebSockets();
  473. this.socketInstances = {}; // 强制清空实例对象
  474. // 移除所有全局事件监听
  475. this.removeAllEventListeners();
  476. // 清理定时器
  477. this.clearAllTimers();
  478. // 销毁HLS播放器(如果使用了hls.js)
  479. if (this.hlsPlayer) {
  480. this.hlsPlayer.destroy();
  481. this.hlsPlayer = null;
  482. }
  483. this.list.forEach(liveItem => {
  484. const videoId = `myVideo_${liveItem.liveId}`;
  485. const videoContext = uni.createVideoContext(videoId, this);
  486. if (videoContext) {
  487. videoContext.pause(); // 仅暂停视频即可
  488. }
  489. });
  490. },
  491. watch: {
  492. // 监听orderUser.count的变化
  493. 'orderUser.count': {
  494. handler(newVal, oldVal) {
  495. if (newVal !== this.prevOrderCount) {
  496. this.prevOrderCount = newVal;
  497. this.showPurchaseMessage();
  498. }
  499. },
  500. immediate: true
  501. }
  502. },
  503. methods: { // 计算当前时间与 liveItem.startTime 的差值,并更新 totalTime
  504. calculateTimeDiff(liveItem) {
  505. // 1. 校验 startTime 格式(防止无效时间)
  506. if (!liveItem.startTime) {
  507. liveItem.totalTime = '00小时00分钟00秒';
  508. return;
  509. }
  510. const iosCompatibleTime = liveItem.startTime
  511. .replace(/-/g, '/') // 把所有 "-" 替换为 "/"
  512. .replace(' ', ' '); // 保留空格(也可替换为 "T",即 "yyyy-MM-ddTHH:mm:ss")
  513. // 2. 转换时间格式(字符串转 Date 对象)
  514. const startTime = new Date(liveItem.startTime);
  515. const now = new Date();
  516. // 4. 容错处理:防止时间解析失败(极端情况)
  517. if (isNaN(startTime.getTime())) {
  518. console.warn(`iOS 时间解析失败,原始时间:${liveItem.startTime},转换后:${iosCompatibleTime}`);
  519. liveItem.totalTime = '00小时00分钟00秒';
  520. return;
  521. }
  522. // 3. 计算毫秒级差值(确保差值非负,避免未来时间出现负数)
  523. const diffMs = Math.max(0, now - startTime);
  524. // 4. 转换为 小时:分钟:秒(补零确保两位数)
  525. const totalSeconds = Math.floor(diffMs / 1000);
  526. const hours = this.padZero(Math.floor(totalSeconds / 3600));
  527. const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
  528. const seconds = this.padZero(totalSeconds % 60);
  529. // 5. 更新当前直播间的 totalTime(响应式更新)
  530. this.$set(liveItem, 'totalTime', `${hours}:${minutes}:${seconds}`);
  531. },
  532. // 辅助方法:数字补零(如 9 → 09)
  533. padZero(num) {
  534. return num < 10 ? `0${num}` : num;
  535. },
  536. // 启动当前直播间的时间差值定时器
  537. startTimeTimer(liveItem) {
  538. // 先清除当前直播间的旧定时器(避免重复)
  539. if (liveItem.timeTimer) {
  540. clearInterval(liveItem.timeTimer);
  541. }
  542. // 1. 立即计算一次(避免等待1秒才显示)
  543. this.calculateTimeDiff(liveItem);
  544. // 2. 每秒更新一次(实时刷新)
  545. liveItem.timeTimer = setInterval(() => {
  546. this.calculateTimeDiff(liveItem);
  547. }, 1000);
  548. },
  549. // 清除指定直播间的时间定时器
  550. clearTimeTimer(liveItem) {
  551. if (liveItem.timeTimer) {
  552. clearInterval(liveItem.timeTimer);
  553. liveItem.timeTimer = null; // 清空定时器标识
  554. }
  555. },
  556. toggleViewerList() {
  557. const now = Date.now()
  558. if (now - this.lastClickTime > this.clickDelay) {
  559. this.showadd = !this.showadd
  560. this.lastClickTime = now
  561. }
  562. },
  563. // 重置在线用户列表的分页参数
  564. resetUserListParams() {
  565. this.viewPageNum = 1; // 重置页码为第一页
  566. this.viewNoMoreData = false; // 重置“没有更多数据”状态
  567. this.liveViewers = []; // 清空现有列表
  568. },
  569. closeAllWebSockets() {
  570. this.isManualClose = true;
  571. // 关闭所有连接
  572. Object.keys(this.socketInstances).forEach(liveId => {
  573. try {
  574. if (this.socketInstances[liveId] && this.socketInstances[liveId].instance) {
  575. this.socketInstances[liveId].instance.close({
  576. code: 1000,
  577. reason: '页面关闭'
  578. });
  579. console.log(`直播间 ${liveId} WebSocket 已关闭`);
  580. }
  581. } catch (e) {
  582. console.error(`关闭直播间 ${liveId} WebSocket 时出错:`, e);
  583. }
  584. });
  585. this.socketInstances = {};
  586. isSocketOpen = false;
  587. }, // 移除所有全局事件监听器
  588. removeAllEventListeners() {
  589. uni.$off('initSocket');
  590. uni.$off('sendMsg');
  591. uni.$off('closeWebSocket');
  592. uni.$off('refreshOrder');
  593. // 可以根据实际情况添加其他需要移除的事件
  594. }, // 清理所有定时器
  595. clearAllTimers() {
  596. if (this.intervalId) {
  597. clearInterval(this.intervalId);
  598. this.intervalId = null;
  599. }
  600. if (this.pingpangTimes) {
  601. clearInterval(this.pingpangTimes);
  602. this.pingpangTimes = null;
  603. }
  604. if (this.reconnectTimer) {
  605. clearInterval(this.reconnectTimer);
  606. this.reconnectTimer = null;
  607. }
  608. if (this.scrollTimer) {
  609. clearTimeout(this.scrollTimer);
  610. this.scrollTimer = null;
  611. }
  612. if (this.searchTimer) {
  613. clearTimeout(this.searchTimer);
  614. this.searchTimer = null;
  615. }
  616. if (this.purchasePromptTimer) {
  617. clearTimeout(this.purchasePromptTimer);
  618. this.purchasePromptTimer = null;
  619. }
  620. },
  621. // 初始化当前直播间数据
  622. async initCurrentLiveData() {
  623. const currentLive = this.list[this.currentSwiperIndex];
  624. if (!currentLive) return;
  625. // 设置加载状态
  626. currentLive.loading = true;
  627. try {
  628. // 先初始化WebSocket连接
  629. await this.initSocket(currentLive);
  630. // 然后并行加载其他数据
  631. await Promise.allSettled([
  632. this.getLiveMsg(currentLive),
  633. this.getliveViewData(currentLive),
  634. this.getShowGoods(currentLive),
  635. this.getliving(currentLive)
  636. ]);
  637. currentLive.loaded = true;
  638. // 初始化完成后,启动当前直播间的时间差值定时器
  639. this.startTimeTimer(currentLive);
  640. } catch (error) {
  641. console.error("初始化直播间数据失败:", error);
  642. } finally {
  643. currentLive.loading = false;
  644. }
  645. },
  646. // 初始化直播间列表
  647. async initLiveList(options) {
  648. try {
  649. await this.getList(); // 先加载直播间列表
  650. if (this.list.length === 0) {
  651. console.error("直播间列表为空,无法初始化");
  652. return;
  653. }
  654. // 设置初始直播间索引(原逻辑保留)
  655. if (options.liveId) {
  656. const index = this.list.findIndex(item => item.liveId == options.liveId);
  657. this.currentSwiperIndex = index !== -1 ? index : 0;
  658. } else {
  659. this.currentSwiperIndex = 0;
  660. }
  661. // 延迟设置动画时间(原逻辑保留)
  662. setTimeout(() => {
  663. this.swiperDuration = 300;
  664. }, 100);
  665. // 获取当前直播间的liveItem
  666. const currentLive = this.list[this.currentSwiperIndex];
  667. if (currentLive) {
  668. this.liveId = currentLive.liveId;
  669. // 重置用户列表参数
  670. this.resetUserListParams();
  671. // 预加载相邻直播间(不初始化WebSocket)
  672. this.preloadNearbyLives(false);
  673. // 初始化当前直播间数据(包含WebSocket连接)
  674. await this.initCurrentLiveData();
  675. // 获取在线用户
  676. this.getliveUser(false);
  677. // 延迟播放视频
  678. setTimeout(() => {
  679. this.playVideo(currentLive);
  680. }, 500);
  681. }
  682. } catch (error) {
  683. console.error("初始化失败:", error);
  684. }
  685. },
  686. // Swiper切换事件
  687. async onSwiperChange(e) {
  688. const now = Date.now();
  689. const newIndex = e.detail.current;
  690. const oldIndex = this.currentSwiperIndex;
  691. // 相同索引或节流期间,不处理
  692. if (newIndex === oldIndex) return;
  693. if (now - this.lastSwiperChangeTime < this.swiperChangeThrottle) {
  694. console.log('Swiper切换过快,已节流');
  695. return;
  696. }
  697. // 更新最后切换时间
  698. this.lastSwiperChangeTime = now;
  699. // 1. 立即关闭旧直播间的WebSocket(同步操作)
  700. const oldLive = this.list[oldIndex];
  701. if (oldLive) {
  702. this.pauseVideo(oldLive);
  703. this.clearTimeTimer(oldLive); // 清除旧直播间的时间定时器
  704. console.log("oldLive",oldLive)
  705. // 强制关闭并删除实例,确保连接被释放
  706. if (this.socketInstances[oldLive.liveId]) {
  707. try {
  708. this.socketInstances[oldLive.liveId].instance.close({
  709. code: 1000,
  710. reason: '切换直播间'
  711. });
  712. console.log(`关闭旧直播间 ${oldLive.liveId} WebSocket`);
  713. } catch (e) {
  714. console.error('关闭旧连接失败:', e);
  715. }
  716. delete this.socketInstances[oldLive.liveId]; // 彻底删除实例
  717. }
  718. }
  719. // 2. 处理新直播间(后续逻辑不变)
  720. this.currentSwiperIndex = newIndex;
  721. const newLive = this.list[newIndex];
  722. if (!newLive) return;
  723. this.liveId = newLive.liveId;
  724. this.resetUserListParams();
  725. await this.initCurrentLiveData(); // 内部会启动新直播间的定时器
  726. this.getliveUser(false);
  727. setTimeout(() => {
  728. this.playVideo(newLive);
  729. }, 100);
  730. },
  731. // 获取直播间列表
  732. async getList() {
  733. const data = {
  734. page: 1,
  735. page_size: 20
  736. };
  737. try {
  738. const res = await liveList(data);
  739. if (res.code === 200) {
  740. this.list = res.rows.map(item => ({
  741. ...item,
  742. talklist: [],
  743. loading: false,
  744. loaded: false,
  745. shopping: false,
  746. inputInfo: '',
  747. showWelcomeMessage: false,
  748. redInfo: {},
  749. goodsCard: {},
  750. totalTime: '00小时00分钟00秒', // 初始化差值为0
  751. timeTimer: null, // 存储当前直播间的定时器,用于后续清理
  752. // 预处理:统一将 startTime 转换为 iOS 兼容格式(避免重复转换)
  753. startTime: item.startTime ? item.startTime.replace(/-/g, '/') : ''
  754. // 其他初始化字段...
  755. }));
  756. console.log("直播间列表加载成功,数量:", this.list.length); // 确认数量是否 > 0
  757. } else {
  758. uni.showToast({
  759. title: res.msg,
  760. icon: "none"
  761. });
  762. this.list = []; // 接口失败时清空列表,避免后续错误
  763. }
  764. } catch (error) {
  765. console.error("获取直播间列表失败:", error);
  766. this.list = []; // 异常时清空列表
  767. }
  768. },
  769. // 播放视频
  770. playVideo(liveItem) {
  771. if (!liveItem) return;
  772. try {
  773. const videoId = `myVideo_${liveItem.liveId}`;
  774. const videoContext = uni.createVideoContext(videoId, this);
  775. if (videoContext) {
  776. videoContext.pause(() => {
  777. // 暂停完成后再播放
  778. videoContext.play();
  779. });
  780. }
  781. } catch (error) {
  782. console.error("播放视频失败:", error);
  783. }
  784. },
  785. pauseVideo(liveItem) {
  786. if (!liveItem) return;
  787. try {
  788. const videoId = `myVideo_${liveItem.liveId}`;
  789. const videoContext = uni.createVideoContext(videoId, this);
  790. if (videoContext) {
  791. videoContext.pause();
  792. }
  793. } catch (error) {
  794. console.error("暂停视频失败:", error);
  795. }
  796. },
  797. // 预加载相邻直播间
  798. async preloadNearbyLives(includeWebSocket = false) {
  799. this.preloading = true;
  800. const currentIndex = this.currentSwiperIndex;
  801. const preloadIndexes = [];
  802. // 只预加载数据,不初始化WebSocket(强制关闭WebSocket预加载)
  803. includeWebSocket = false; // 关键:强制不预加载WebSocket
  804. if (currentIndex > 0) preloadIndexes.push(currentIndex - 1);
  805. if (currentIndex < this.list.length - 1) preloadIndexes.push(currentIndex + 1);
  806. for (const index of preloadIndexes) {
  807. const liveItem = this.list[index];
  808. if (!liveItem || liveItem.loaded || liveItem.loading) continue;
  809. liveItem.loading = true;
  810. try {
  811. // 只加载基础数据,不初始化WebSocket
  812. await Promise.all([
  813. this.getliving(liveItem),
  814. this.getLiveMsg(liveItem),
  815. this.getliveViewData(liveItem),
  816. this.getShowGoods(liveItem)
  817. ]);
  818. liveItem.loaded = true;
  819. } catch (error) {
  820. console.error(`预加载直播间 ${index} 失败:`, error);
  821. liveItem.loaded = false;
  822. } finally {
  823. liveItem.loading = false;
  824. }
  825. }
  826. this.preloading = false;
  827. },
  828. openViews() {
  829. // 计算scroll-view高度
  830. this.$nextTick(() => {
  831. const query = uni.createSelectorQuery().in(this);
  832. query.select('.view-box').boundingClientRect(data => {
  833. if (data) {
  834. // 减去标题和底部固定区域的高度
  835. this.scrollHeight = data.height - 80 - 120; // 80是标题高度,120是底部高度
  836. }
  837. }).exec();
  838. });
  839. },
  840. // 重置直播间数据
  841. resetLiveData() {
  842. // 保留不需要重置的数据(如用户信息等)
  843. const keepData = {
  844. userinfo: this.userinfo,
  845. list: this.list,
  846. currentSwiperIndex: this.currentSwiperIndex
  847. };
  848. // 重置其他直播间特定数据
  849. this.liveUserTotal = null;
  850. // this.liveViewData = {};
  851. this.liveViewers = [];
  852. this.livingUrl = "";
  853. this.videoUrl = null;
  854. this.products = {};
  855. this.store = {};
  856. this.orderUser = {};
  857. this.talklist = [];
  858. this.livedata = {};
  859. // this.isFollow = false;
  860. this.shopping = false;
  861. this.inputInfo = ''
  862. // 恢复需要保留的数据
  863. Object.assign(this, keepData);
  864. },
  865. // 获取直播间用户
  866. async getliveUser(isLoadMore = false) {
  867. // 强制使用当前 liveId,避免使用旧值
  868. const currentLiveId = this.liveId;
  869. if (!currentLiveId) return;
  870. // if (this.viewLoading || this.viewNoMoreData) return;
  871. this.viewLoading = true;
  872. try {
  873. const res = await watchUserList(currentLiveId, this.viewPageSize, this.viewPageNum, false);
  874. if (res.code === 200) {
  875. // 若请求期间已切换直播间,忽略旧数据
  876. if (this.liveId !== currentLiveId) return;
  877. this.liveUserTotal = res.total;
  878. if (res.rows.length === 0) {
  879. this.viewNoMoreData = true;
  880. return;
  881. }
  882. this.liveViewers = isLoadMore ? [...this.liveViewers, ...res.rows] : res
  883. .rows; // 首次加载/切换直播间时重置数据
  884. this.viewPageNum++;
  885. // console.log("在线观众", this.liveViewers)
  886. }
  887. } catch (error) {
  888. console.error('获取观众列表失败:', error);
  889. } finally {
  890. this.viewLoading = false;
  891. }
  892. },
  893. // 滚动到底部触发
  894. handleScrollToLower() {
  895. // 清除上一次未执行的定时器,避免重复请求
  896. if (this.scrollTimer) {
  897. clearTimeout(this.scrollTimer);
  898. }
  899. // 延迟0.5秒(500毫秒)执行接口请求
  900. this.scrollTimer = setTimeout(() => {
  901. this.getliveUser(true); // 加载更多数据
  902. }, 1000); // 延迟时间:500毫秒
  903. },
  904. async getLiveMsg(liveItem) {
  905. // 强化校验:确保 liveItem 存在且包含 liveId
  906. if (!liveItem || !liveItem.liveId) {
  907. console.error('getLiveMsg 错误:无效的 liveItem', {
  908. liveItem: liveItem,
  909. currentIndex: this.currentSwiperIndex,
  910. listLength: this.list.length
  911. });
  912. return; // 直接返回,不执行后续逻辑
  913. }
  914. try {
  915. const res = await liveMsg(liveItem.liveId, 30, 1);
  916. if (res.code == 200) {
  917. // 确保使用响应式更新
  918. this.$set(liveItem, 'talklist', [...res.rows]);
  919. this.$nextTick(() => {
  920. this.$set(liveItem, 'scrollIntoView', `list_${liveItem.talklist.length-1}`);
  921. });
  922. }
  923. } catch (error) {
  924. console.error("获取聊天记录失败:", error);
  925. }
  926. },
  927. // 点击红包
  928. onRed(item) {
  929. // console.log("点了this.liveId", item)
  930. if (!item.liveId) return;
  931. // console.log("点了this.liveId", this.liveId)
  932. if (!item.redInfo?.redId) return;
  933. // console.log("点了this.redInfo?.redId", this.redInfo.redId)
  934. // console.log("点了this.userinfo.userId", this.userinfo.userId)
  935. let data = {
  936. liveId: item.liveId,
  937. userId: this.userinfo.userId,
  938. redId: item.redInfo.redId,
  939. }
  940. console.log("点了this.liveId", data)
  941. liveRed(data).then(res => {
  942. if (res.code == 200) {
  943. uni.showToast({
  944. title: res.msg,
  945. icon: 'none'
  946. });
  947. } else {
  948. uni.showToast({
  949. title: res.msg,
  950. icon: 'none'
  951. });
  952. }
  953. },
  954. rej => {}
  955. );
  956. },
  957. handleSearchInput() {
  958. // 使用防抖优化性能,避免频繁请求
  959. clearTimeout(this.searchTimer);
  960. this.searchTimer = setTimeout(() => {
  961. this.queryCollect();
  962. }, 500); // 500毫秒延迟
  963. },
  964. // 显示购买提示信息
  965. showPurchaseMessage() {
  966. // 清除之前的定时器
  967. if (this.purchasePromptTimer) {
  968. clearTimeout(this.purchasePromptTimer);
  969. }
  970. // 显示提示
  971. this.showPurchasePrompt = true;
  972. // 2秒后自动隐藏
  973. this.purchasePromptTimer = setTimeout(() => {
  974. this.showPurchasePrompt = false;
  975. }, 2000);
  976. },
  977. truncateString(str, maxLength) {
  978. return str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
  979. },
  980. goStore(item) {
  981. console.log("带过去storeId", item)
  982. if (!item.storeId) {
  983. uni.showToast({
  984. title: "当前直播间暂未开通店铺",
  985. icon: 'none'
  986. });
  987. return;
  988. }
  989. uni.navigateTo({
  990. url: '/pages_shop/store?liveId=' + item.liveId + "&storeId=" + item.storeId
  991. })
  992. },
  993. // 去订单列表
  994. goOrderList() {
  995. uni.navigateTo({
  996. url: "/pages_shop/order"
  997. })
  998. },
  999. // 初始化HLS播放器
  1000. initHlsPlayer() {
  1001. if (Hls.isSupported() && this.livingUrl) {
  1002. const video = document.getElementById('myVideo');
  1003. if (video) {
  1004. this.hlsPlayer = new Hls();
  1005. this.hlsPlayer.loadSource(this.livingUrl);
  1006. this.hlsPlayer.attachMedia(video);
  1007. this.hlsPlayer.on(Hls.Events.MANIFEST_PARSED, () => {
  1008. video.play();
  1009. });
  1010. }
  1011. }
  1012. },
  1013. // 视频错误处理
  1014. videoError(e, liveItem) {
  1015. if (!liveItem || liveItem.liveId !== this.liveId) return;
  1016. // 初始化重试计数
  1017. if (this.videoRetryCounts[liveItem.liveId] === undefined) {
  1018. this.videoRetryCounts[liveItem.liveId] = 0;
  1019. }
  1020. // 限制重试次数
  1021. if (this.videoRetryCounts[liveItem.liveId] >= 3) {
  1022. console.error(`直播间 ${liveItem.liveId} 视频加载失败,停止重试`);
  1023. // 显示错误提示
  1024. uni.showToast({
  1025. title: "视频加载失败,请检查网络",
  1026. icon: 'none',
  1027. duration: 2000
  1028. });
  1029. return;
  1030. }
  1031. this.videoRetryCounts[liveItem.liveId]++;
  1032. // 延迟重试
  1033. setTimeout(() => {
  1034. if (liveItem.liveId === this.liveId) {
  1035. console.log(`第${this.videoRetryCounts[liveItem.liveId]}次重试播放视频`);
  1036. this.playVideo(liveItem);
  1037. }
  1038. }, 2000);
  1039. },
  1040. // 修改获取直播信息方法
  1041. async getliving(liveItem) {
  1042. if (!liveItem || !liveItem.liveId) return;
  1043. // console.log("获取直播信息:", liveItem.liveId);
  1044. const param = {
  1045. id: liveItem.liveId
  1046. };
  1047. try {
  1048. const res = await getlive({
  1049. id: liveItem.liveId
  1050. });
  1051. if (res.code !== 200) {
  1052. uni.showToast({
  1053. title: res.msg,
  1054. icon: 'none'
  1055. });
  1056. return;
  1057. }
  1058. // 强制更新视频源(覆盖旧值)
  1059. if (res.data.liveType === 2) {
  1060. // 回放视频
  1061. this.$set(liveItem, 'videoUrl', res.data.videoUrl);
  1062. this.$set(liveItem, 'livingUrl', ''); // 清空直播流
  1063. this.$set(liveItem, 'placeholderText', "说点什么...");
  1064. } else if (res.data.liveType === 1) {
  1065. // 直播流
  1066. this.$set(liveItem, 'livingUrl', res.data.flvHlsUrl);
  1067. this.$set(liveItem, 'videoUrl', ''); // 清空回放视频
  1068. this.$set(liveItem, 'placeholderText', "说点什么...");
  1069. } else {
  1070. // 未开播
  1071. this.$set(liveItem, 'livingUrl', '');
  1072. this.$set(liveItem, 'videoUrl', '');
  1073. }
  1074. // 更新其他直播信息
  1075. // 仅当是当前激活的直播间时,才允许自动播放
  1076. const isCurrentLive = this.currentSwiperIndex === this.list.findIndex(item => item.liveId ===
  1077. liveItem.liveId);
  1078. this.$set(liveItem, 'autoplay', isCurrentLive && res.data.liveType !== 0);
  1079. this.$set(liveItem, 'showType', res.data.showType);
  1080. this.$set(liveItem, 'storeId', res.storeId);
  1081. this.queryCollect();
  1082. } catch (err) {
  1083. console.error("获取直播信息失败:", err);
  1084. uni.showToast({
  1085. title: "获取直播信息失败",
  1086. icon: 'none'
  1087. });
  1088. }
  1089. }, // 设置视频播放
  1090. setupVideoPlayback(liveItem, liveData) {
  1091. if (!liveItem.livingUrl) return;
  1092. // H5 平台:使用 HLS.js 处理 .m3u8 流
  1093. // #ifdef H5
  1094. if (liveItem.livingUrl.includes('.m3u8')) {
  1095. this.initHlsPlayer(liveItem);
  1096. return;
  1097. }
  1098. // #endif
  1099. // 小程序/App 平台:直接使用 video 组件
  1100. const videoId = `myVideo_${liveItem.liveId}`;
  1101. const videoContext = uni.createVideoContext(videoId, this);
  1102. if (liveData.liveType === 1) {
  1103. // 回放:跳转到指定位置
  1104. videoContext.seek(liveData.nowDuration || 0);
  1105. } else {
  1106. // 直播:直接播放
  1107. videoContext.play();
  1108. }
  1109. },
  1110. maskString(str, maskChar = '*') {
  1111. // 如果str是undefined或null,直接返回空字符串
  1112. if (!str) return '';
  1113. // 确保str是字符串(如果是数字等类型,先转为字符串)
  1114. const strVal = String(str);
  1115. return strVal.split('').map((char, index) => (index === 0 ? char : maskChar)).join('');
  1116. },
  1117. getPureDecimal(num, precision = 6) {
  1118. const decimalPart = Math.abs(num).toFixed(precision).split('.')[1];
  1119. return decimalPart?.replace(/0+$/, '') || ''; // 移除末尾多余的0
  1120. },
  1121. // 返回上一个页面并关闭WebSocket
  1122. goBack() {
  1123. // 暂停当前视频
  1124. const currentLive = this.list[this.currentSwiperIndex];
  1125. if (currentLive) {
  1126. this.pauseVideo(currentLive);
  1127. }
  1128. // 关闭所有WebSocket连接
  1129. this.closeWebSocket();
  1130. // 导航返回
  1131. const pages = getCurrentPages();
  1132. if (pages.length > 1) {
  1133. uni.navigateBack();
  1134. } else {
  1135. uni.reLaunch({
  1136. url: '/pages/list/index'
  1137. });
  1138. }
  1139. },
  1140. //正在购买
  1141. async getliveOrder() {
  1142. const currentLiveId = this.liveId;
  1143. if (!currentLiveId) return;
  1144. try {
  1145. const res = await liveOrderUser(currentLiveId);
  1146. if (res.code === 200) {
  1147. // 绑定到当前 liveItem
  1148. const currentLive = this.list[this.currentSwiperIndex];
  1149. if (currentLive) {
  1150. this.$set(currentLive, 'orderUser', res);
  1151. this.orderUser = res; // 同步全局变量
  1152. }
  1153. }
  1154. } catch (error) {
  1155. console.error('获取正在购买用户失败:', error);
  1156. }
  1157. },
  1158. // 获取直播间信息接口
  1159. getLiveinformation() {
  1160. if (!this.liveId) return;
  1161. getLiveInfo(this.liveId).then(res => {
  1162. if (res.code == 200) {
  1163. console.log("获取直播间信息接口>>>>", res)
  1164. this.livingUrl = res.livingUrl
  1165. } else {
  1166. uni.showToast({
  1167. title: res.msg,
  1168. icon: 'none'
  1169. });
  1170. }
  1171. },
  1172. rej => {}
  1173. );
  1174. },
  1175. // 点赞
  1176. async onLike(liveItem) {
  1177. if (!liveItem || !liveItem.liveId) return;
  1178. try {
  1179. const res = await liveDataLike(liveItem.liveId);
  1180. if (res?.like) {
  1181. liveItem.liveViewData.like++; // 只更新当前直播间的点赞数
  1182. } else {
  1183. uni.showToast({
  1184. title: res.msg,
  1185. icon: 'none'
  1186. });
  1187. }
  1188. } catch (error) {
  1189. console.error('点赞失败:', error);
  1190. }
  1191. },
  1192. // 点赞
  1193. // async onLike(liveItem) {
  1194. // // 基础校验
  1195. // if (!liveItem || !liveItem.liveId) return;
  1196. // // 确保liveViewData存在(初始化默认值)
  1197. // if (!liveItem.liveViewData) {
  1198. // await this.getliveViewData(liveItem);
  1199. // if (!liveItem.liveViewData) {
  1200. // uni.showToast({
  1201. // title: "数据加载中,请稍后再试",
  1202. // icon: 'none'
  1203. // });
  1204. // return;
  1205. // }
  1206. // // 初始化点赞数(防止undefined)
  1207. // liveItem.liveViewData.like = liveItem.liveViewData.like || 0;
  1208. // }
  1209. // // 限制最多10次点赞
  1210. // const maxLikeCount = 10;
  1211. // if (liveItem.liveViewData.like >= maxLikeCount) {
  1212. // uni.showToast({
  1213. // title: "最多可点赞10次哦~",
  1214. // icon: 'none'
  1215. // });
  1216. // return;
  1217. // }
  1218. // try {
  1219. // const res = await liveDataLike(liveItem.liveId);
  1220. // if (res.code === 200) {
  1221. // // 无论后端是否返回res.like,前端按规则累加(最多到10次)
  1222. // const newLikeCount = Math.min(liveItem.liveViewData.like + 1, maxLikeCount);
  1223. // liveItem.liveViewData.like = newLikeCount;
  1224. // } else {
  1225. // uni.showToast({
  1226. // title: res.msg || "点赞失败",
  1227. // icon: 'none'
  1228. // });
  1229. // }
  1230. // } catch (error) {
  1231. // console.error('点赞失败:', error);
  1232. // uni.showToast({
  1233. // title: "网络异常,点赞失败",
  1234. // icon: 'none'
  1235. // });
  1236. // }
  1237. // },
  1238. //直播间点赞、关注、在线人数数据
  1239. async getliveViewData(liveItem) {
  1240. if (!liveItem || !liveItem.liveId) return;
  1241. try {
  1242. const res = await getLiveViewData(liveItem.liveId);
  1243. if (res.code == 200) {
  1244. // 强制响应式更新,确保数据实时显示
  1245. this.$set(liveItem, 'liveViewData', res);
  1246. }
  1247. } catch (error) {
  1248. console.error("获取直播间数据失败:", error);
  1249. // 失败时兜底,避免显示异常
  1250. this.$set(liveItem, 'liveViewData', {
  1251. like: 0,
  1252. watchCount: 0
  1253. });
  1254. }
  1255. },
  1256. //弹出商品卡片
  1257. async getShowGoods(liveItem) {
  1258. if (!liveItem || !liveItem.liveId) return;
  1259. try {
  1260. const res = await showGoods(liveItem.liveId);
  1261. if (res.code == 200) {
  1262. this.$set(liveItem, 'goodsCard', res);
  1263. }
  1264. } catch (error) {
  1265. console.error("暂无商品卡片", error);
  1266. }
  1267. },
  1268. // 去购买,跳商品详情
  1269. goShop(productId, goodsId) {
  1270. const currentLive = this.list[this.currentSwiperIndex];
  1271. if (!currentLive || !currentLive.liveId) return;
  1272. uni.navigateTo({
  1273. url: '/pages_shop/goods?productId=' + productId + '&liveId=' + currentLive.liveId +
  1274. '&goodsId=' + goodsId + '&storeId=' + currentLive.storeId
  1275. })
  1276. },
  1277. // 查询店铺
  1278. async queryCollect() {
  1279. const currentLive = this.list[this.currentSwiperIndex];
  1280. if (!currentLive || !currentLive.liveId) return;
  1281. const {
  1282. storeId
  1283. } = currentLive;
  1284. // console.log("小黄车数据>>>", currentLive)
  1285. if (!storeId) return;
  1286. try {
  1287. const res = await store(currentLive.storeId, currentLive.inputInfo, currentLive.liveId);
  1288. if (res.code === 200) {
  1289. // 数据绑定到当前 liveItem,避免全局污染
  1290. this.$set(currentLive, 'products', res.data.goodsList);
  1291. this.$set(currentLive, 'store', res.data);
  1292. // 同步更新全局变量(供弹窗使用)
  1293. this.products = res.data.goodsList;
  1294. this.store = res.data;
  1295. }
  1296. } catch (error) {
  1297. console.error('获取小黄车商品失败:', error);
  1298. }
  1299. },
  1300. // 店铺收藏
  1301. onStoreCollect(liveItem) {
  1302. console.log("店铺收藏", liveItem)
  1303. if (!liveItem.storeId) return;
  1304. collectStore(liveItem.storeId).then(res => {
  1305. if (res.code == 200) {
  1306. uni.showToast({
  1307. title: res.msg,
  1308. icon: 'none'
  1309. });
  1310. liveItem.store.isFavorite = !liveItem.store.isFavorite
  1311. } else {
  1312. uni.showToast({
  1313. title: res.msg,
  1314. icon: 'none'
  1315. });
  1316. }
  1317. },
  1318. rej => {}
  1319. );
  1320. },
  1321. // 商品收藏
  1322. onGoodsCollect(item) {
  1323. console.log("商品收藏", item)
  1324. if (!item || item.length === 0 || !item.goodsId) {
  1325. return;
  1326. }
  1327. collectGoods(item.goodsId).then(res => {
  1328. if (res.code == 200) {
  1329. uni.showToast({
  1330. title: res.msg,
  1331. icon: 'none'
  1332. });
  1333. item.isFavorite = !item.isFavorite
  1334. } else {
  1335. uni.showToast({
  1336. title: res.msg,
  1337. icon: 'none'
  1338. });
  1339. }
  1340. },
  1341. rej => {}
  1342. );
  1343. },
  1344. // 关注
  1345. // async onFollow(liveItem) {
  1346. // if (!liveItem || !liveItem.liveId) return;
  1347. // try {
  1348. // const res = await follow(liveItem.liveId);
  1349. // liveItem.isFollow = !liveItem.isFollow;
  1350. // uni.showToast({
  1351. // title: res.msg,
  1352. // icon: 'none'
  1353. // });
  1354. // } catch (error) {
  1355. // console.error("关注操作失败:", error);
  1356. // }
  1357. // },
  1358. // 时间戳
  1359. initTime() {
  1360. const now = new Date();
  1361. this.timestamp = now.getTime(); // 例如:'2023-04-01 12:00:00'
  1362. },
  1363. openShop() {
  1364. },
  1365. openViews() {
  1366. this.$nextTick(() => {
  1367. const query = uni.createSelectorQuery().in(this);
  1368. query.select('.view-box').boundingClientRect(data => {
  1369. if (data) {
  1370. this.scrollHeight = data.height - 80 - 120;
  1371. }
  1372. }).exec();
  1373. });
  1374. },
  1375. openCart(liveItem) {
  1376. if (!liveItem.storeId) {
  1377. uni.showToast({
  1378. title: "当前直播间暂未开通店铺",
  1379. icon: 'none'
  1380. });
  1381. return;
  1382. }
  1383. liveItem.shopping = !liveItem.shopping
  1384. },
  1385. close() {
  1386. this.showadd = false
  1387. },
  1388. // closes() {
  1389. // this.showziliao = !this.showziliao
  1390. // },
  1391. // 关闭小黄车
  1392. closeShop() {
  1393. // 通过当前swiper索引获取当前直播间实例
  1394. const currentLive = this.list[this.currentSwiperIndex];
  1395. if (currentLive) {
  1396. this.$set(currentLive, 'shopping', !currentLive.shopping);
  1397. }
  1398. },
  1399. // 关闭红包
  1400. closeRed() {
  1401. this.showRed = !this.showRed
  1402. },
  1403. // 触摸结束
  1404. // handleTouchEnd() {
  1405. // this.isZoom = false; // 恢复原状
  1406. // },
  1407. getEWechatSdk() {
  1408. // 只在H5平台执行
  1409. // #ifdef H5
  1410. let eWechatSdk = '';
  1411. if (/(Android)/i.test(navigator.userAgent)) {
  1412. eWechatSdk = 'jWeixin';
  1413. } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
  1414. eWechatSdk = 'wx';
  1415. } else {
  1416. eWechatSdk = 'jWeixin';
  1417. }
  1418. uni.setStorageSync("wxSdk", eWechatSdk);
  1419. // #endif
  1420. },
  1421. // 修改关闭WebSocket方法
  1422. closeWebSocket(liveId = null) {
  1423. this.isManualClose = true;
  1424. clearInterval(this.pingpangTimes);
  1425. clearInterval(this.reconnectTimer);
  1426. if (liveId) {
  1427. // 添加空值检查
  1428. if (this.socketInstances[liveId] && this.socketInstances[liveId].instance) {
  1429. try {
  1430. this.socketInstances[liveId].instance.close();
  1431. console.log(`直播间 ${liveId} WebSocket 已安全关闭`);
  1432. } catch (e) {
  1433. console.error(`关闭直播间 ${liveId} WebSocket 时出错:`, e);
  1434. }
  1435. }
  1436. delete this.socketInstances[liveId];
  1437. } else {
  1438. Object.keys(this.socketInstances).forEach(id => {
  1439. // 添加空值检查
  1440. if (this.socketInstances[id] && this.socketInstances[id].instance) {
  1441. try {
  1442. this.socketInstances[id].instance.close();
  1443. console.log(`直播间 ${id} WebSocket 已安全关闭`);
  1444. } catch (e) {
  1445. console.error(`关闭直播间 ${id} WebSocket 时出错:`, e);
  1446. }
  1447. }
  1448. });
  1449. this.socketInstances = {};
  1450. }
  1451. isSocketOpen = false;
  1452. },
  1453. reConnect() {
  1454. var that = this;
  1455. try {
  1456. uni.closeSocket();
  1457. } catch (e) {
  1458. }
  1459. setTimeout(function() {
  1460. that.initSocket();
  1461. }, 10000);
  1462. },
  1463. startHeartbeat(liveId) {
  1464. clearInterval(this.pingpangTimes);
  1465. this.pingpangTimes = setInterval(() => {
  1466. const inst = this.socketInstances[liveId];
  1467. if (!inst || !inst.isOpen || !inst.instance) return;
  1468. const pingData = {
  1469. cmd: 'ping',
  1470. timestamp: Date.now()
  1471. };
  1472. try {
  1473. inst.instance.send({
  1474. data: JSON.stringify(pingData)
  1475. });
  1476. } catch (err) {
  1477. console.error('心跳发送失败:', err);
  1478. this.scheduleReconnect(liveId);
  1479. }
  1480. }, 30000);
  1481. },
  1482. async initSocket(liveItem) {
  1483. const currentLive = this.list[this.currentSwiperIndex];
  1484. if (!currentLive || currentLive.liveId !== liveItem.liveId) {
  1485. console.log(`拒绝为非活跃直播间 ${liveItem.liveId} 建立WebSocket`);
  1486. return;
  1487. }
  1488. if (!liveItem || !liveItem.liveId) return;
  1489. const liveId = liveItem.liveId;
  1490. // 检查是否已经是当前连接或正在连接
  1491. if (this.connectingLiveId === liveId ||
  1492. (this.socketInstances[liveId] && this.socketInstances[liveId].isOpen)) {
  1493. console.log(`直播间 ${liveId} 的WebSocket已经连接或正在连接,跳过初始化`);
  1494. return;
  1495. }
  1496. // 检查是否是当前活跃的直播间
  1497. if (this.currentSwiperIndex !== this.list.findIndex(item => item.liveId === liveId)) {
  1498. console.log(`不初始化非当前直播间 ${liveId} 的WebSocket`);
  1499. return;
  1500. }
  1501. // 关闭之前的连接(如果存在)
  1502. if (this.socketInstances[liveId]) {
  1503. this.closeWebSocket(liveId);
  1504. }
  1505. // 设置正在连接的直播间ID
  1506. this.connectingLiveId = liveId;
  1507. // 防止重复创建
  1508. if (this.reconnectCount >= this.maxReconnectAttempts) {
  1509. this.connectingLiveId = null;
  1510. return;
  1511. }
  1512. this.isManualClose = false;
  1513. const connectTimeout = setTimeout(() => {
  1514. if (!this.socketInstances[liveId]?.isOpen) {
  1515. console.error(`WebSocket连接超时: ${liveId}`);
  1516. this.scheduleReconnect(liveId);
  1517. }
  1518. }, 10000); // 10秒超时
  1519. // 生成签名
  1520. const signature = CryptoJS.HmacSHA256(
  1521. `${liveId}${this.userinfo.userId}${this.userType}${this.timestamp}`,
  1522. this.timestamp.toString()
  1523. ).toString(CryptoJS.enc.Hex);
  1524. // 初始化实例状态
  1525. this.socketInstances[liveId] = {
  1526. instance: null,
  1527. isOpen: false
  1528. };
  1529. try {
  1530. const socketTask = uni.connectSocket({
  1531. url: `${wsUrl}?userId=${this.userinfo.userId}&liveId=${liveId}&userType=${this.userType}&timestamp=${this.timestamp}&signature=${signature}`,
  1532. success: () => {
  1533. console.log('WebSocket API 调用成功,正在建立连接...');
  1534. },
  1535. fail: (err) => {
  1536. console.error('WebSocket 连接失败:', err);
  1537. this.connectingLiveId = null;
  1538. this.scheduleReconnect(liveId);
  1539. }
  1540. });
  1541. socketTask.onOpen((res) => {
  1542. console.log('WebSocket 连接已成功建立', res);
  1543. this.socketInstances[liveId].instance = socketTask;
  1544. this.socketInstances[liveId].isOpen = true;
  1545. clearTimeout(connectTimeout);
  1546. isSocketOpen = true;
  1547. this.connectingLiveId = null;
  1548. this.reconnectCount = 0;
  1549. // 改用 socketTask 的 send 作为心跳
  1550. this.startHeartbeat(liveId); // 修改 startHeartbeat 以接受 liveId 并使用 socketTask.send
  1551. });
  1552. socketTask.onMessage((res) => {
  1553. // 找到对应的直播间并更新数据
  1554. const targetLive = this.list.find(item => item.liveId === liveId);
  1555. if (targetLive) {
  1556. this.handleSocketMessage(res, targetLive);
  1557. }
  1558. });
  1559. socketTask.onError((err) => {
  1560. clearTimeout(connectTimeout);
  1561. console.error('WebSocket 连接错误:', err);
  1562. this.connectingLiveId = null;
  1563. this.scheduleReconnect(liveId);
  1564. });
  1565. socketTask.onClose(() => {
  1566. console.log(`WebSocket 连接已关闭: ${liveId}`);
  1567. this.connectingLiveId = null;
  1568. });
  1569. } catch (e) {
  1570. console.error('创建 WebSocket 异常:', e);
  1571. this.connectingLiveId = null;
  1572. this.scheduleReconnect(liveId);
  1573. }
  1574. },
  1575. // 处理Socket消息
  1576. handleSocketMessage(message, liveItem) {
  1577. let data = JSON.parse(message.data)
  1578. const socketMessage = data.data
  1579. // console.log("处理",data)
  1580. if (data.code == 200) {
  1581. const messageData = {
  1582. ...socketMessage, // 原数据(可能包含部分字段)
  1583. cmd: socketMessage.cmd || '' // 强制添加cmd,确保存在(默认空字符串)
  1584. };
  1585. // console.log("messageData是",messageData)
  1586. if (socketMessage.cmd == 'sendMsg') {
  1587. // this.$set(liveItem, 'talklist', [...liveItem.talklist, messageData]);
  1588. this.$nextTick(() => {
  1589. this.$set(liveItem, 'scrollIntoView', `list_${liveItem.talklist.length-1}`);
  1590. });
  1591. } else if (socketMessage.cmd == 'red') {
  1592. // 领红包
  1593. this.$set(liveItem, 'redInfo', JSON.parse(socketMessage.data));
  1594. console.log("红包是liveItem.redInfo", liveItem)
  1595. // liveItem.redInfo = JSON.parse(message.data.data);
  1596. } else if (socketMessage.cmd == 'sendRedPacketQuestion') {
  1597. const list = JSON.parse(message.data.data);
  1598. // 处理红包答题逻辑
  1599. } else if (socketMessage.cmd == 'entry' || socketMessage.cmd == 'out') {
  1600. this.$set(liveItem, 'talklist', [...liveItem.talklist, messageData]);
  1601. // 先重置为 false(避免残留状态)
  1602. this.$set(liveItem, 'showWelcomeMessage', false);
  1603. // 立即设为 true(触发 DOM 更新)
  1604. this.$set(liveItem, 'showWelcomeMessage', true);
  1605. this.getliveUser(false); // 调用获取在线用户接口
  1606. // console.log("开启欢迎消息:", liveItem.showWelcomeMessage);
  1607. if (liveItem.welcomeTimer) {
  1608. clearTimeout(liveItem.welcomeTimer);
  1609. }
  1610. // 存储定时器到 liveItem 中(避免引用丢失)
  1611. liveItem.welcomeTimer = setTimeout(() => {
  1612. this.$set(liveItem, 'showWelcomeMessage', false);
  1613. // console.log("关闭欢迎消息:", liveItem.showWelcomeMessage);
  1614. }, 1000); // 1秒后隐藏
  1615. } else if (socketMessage.cmd == 'Integral') {
  1616. // 观看奖励事件 弹出框2s 显示msg
  1617. uni.showToast({
  1618. title: socketMessage.msg,
  1619. icon: 'none',
  1620. duration: 2000
  1621. });
  1622. } else if (socketMessage.cmd == 'blockUser') {
  1623. //拉黑事件 主动删除用户token,强制跳转到登录页面
  1624. uni.removeStorage({
  1625. key: 'AppToken', // 存储 Token 时的 key
  1626. success: () => {
  1627. uni.reLaunch({
  1628. url: '/pages/auth/login' // 登录页路径,需根据项目实际路径调整
  1629. });
  1630. console.log('Token 删除成功');
  1631. },
  1632. fail: (err) => {
  1633. console.error('Token 删除失败:', err);
  1634. }
  1635. });
  1636. } else if (socketMessage.cmd == 'goods') {
  1637. this.$set(liveItem, 'goodsCard', JSON.parse(socketMessage.data));
  1638. } else if (socketMessage.cmd == 'out') {
  1639. // console.log("进入:", liveItem);
  1640. console.log("有人退出了:");
  1641. } else if (socketMessage.cmd == 'live_start') {
  1642. // 直播开始
  1643. } else if (socketMessage.cmd == 'live_end') {
  1644. // 直播结束
  1645. } else if (socketMessage.data.cmd == 'deleteId') {
  1646. uni.$emit('deleteId');
  1647. } else if (socketMessage.data.cmd == 'sendRedPacketQuestion') {
  1648. // const list = JSON.parse(socketMessage)
  1649. // liveItem.redanswerAll = [...liveItem.redanswerAll, ...list]
  1650. // if (liveItem.redanswerAll[1].randomAmount !== null) {
  1651. // liveItem.redanswertips = JSON.parse(liveItem.redanswerAll[0]
  1652. // .randomAmount)
  1653. // }
  1654. }
  1655. } else {
  1656. uni.showToast({
  1657. title: data.msg,
  1658. icon: 'none'
  1659. });
  1660. }
  1661. },
  1662. scheduleReconnect(liveId) {
  1663. if (this.isManualClose || this.reconnectCount >= this.maxReconnectAttempts) return;
  1664. this.reconnectCount++;
  1665. const delay = Math.min(3000 * this.reconnectCount, 30000);
  1666. clearInterval(this.reconnectTimer);
  1667. this.reconnectTimer = setTimeout(() => {
  1668. // 使用传入的liveId
  1669. const liveItem = this.list.find(item => item.liveId === liveId) || {
  1670. liveId
  1671. };
  1672. this.initSocket(liveItem);
  1673. }, delay);
  1674. },
  1675. sendMsg(liveItem) {
  1676. if (!liveItem || !liveItem.liveId) return;
  1677. // 防止连续点击发送两次(短时锁定)
  1678. if (liveItem.isSending) return;
  1679. liveItem.isSending = true;
  1680. setTimeout(() => {
  1681. liveItem.isSending = false;
  1682. }, 800); // 800ms 内禁止再次发送
  1683. const text = (liveItem.value || '').trim();
  1684. if (!text) {
  1685. uni.showToast({
  1686. title: "不能发送空消息",
  1687. icon: 'none'
  1688. });
  1689. return;
  1690. }
  1691. const liveId = liveItem.liveId;
  1692. const socketItem = this.socketInstances[liveId];
  1693. // 乐观更新:立即把消息加入到本地聊天列表并清空输入(更好的体验)
  1694. const localMsg = {
  1695. cmd: 'sendMsg',
  1696. msg: text,
  1697. nickName: this.userinfo.nickName,
  1698. avatar: this.userinfo.avatar,
  1699. userId: this.userinfo.userId,
  1700. local: true, // 标记为本地消息(可用于样式或后续差异处理)
  1701. ts: Date.now()
  1702. };
  1703. this.$set(liveItem, 'talklist', [...(liveItem.talklist || []), localMsg]);
  1704. this.$set(liveItem, 'value', ''); // 立即清空输入
  1705. if (!socketItem || !socketItem.instance || !socketItem.isOpen) {
  1706. // 如果 socket 未连接,尝试建立连接(但不要阻塞用户)
  1707. this.initSocket(liveItem);
  1708. uni.showToast({
  1709. title: "连接未建立,正在重连",
  1710. icon: 'none'
  1711. });
  1712. return;
  1713. }
  1714. const data = {
  1715. liveId,
  1716. userId: this.userinfo.userId,
  1717. userType: 0,
  1718. cmd: "sendMsg",
  1719. msg: text,
  1720. nickName: this.userinfo.nickName,
  1721. avatar: this.userinfo.avatar
  1722. };
  1723. try {
  1724. socketItem.instance.send({
  1725. data: JSON.stringify(data),
  1726. success: () => {
  1727. // 比如找到最后一条 local 消息并标记为 sent
  1728. },
  1729. fail: (err) => {
  1730. console.error("发送失败:", err);
  1731. uni.showToast({
  1732. title: "发送失败,请重试",
  1733. icon: 'none'
  1734. });
  1735. // 可选择回滚本地显示(此处简单提示即可)
  1736. }
  1737. });
  1738. } catch (err) {
  1739. console.error('socket send 异常', err);
  1740. }
  1741. }
  1742. }
  1743. };
  1744. </script>
  1745. <style scoped lang="scss">
  1746. .swiper-wrapper {
  1747. position: relative;
  1748. width: 100%;
  1749. height: 100vh;
  1750. overflow: hidden;
  1751. background-color: #000000;
  1752. }
  1753. .swiper-container {
  1754. width: 100%;
  1755. height: 100vh;
  1756. }
  1757. .container {
  1758. width: 100%;
  1759. height: 100%;
  1760. position: relative;
  1761. // 添加渐变过渡效果
  1762. transition: opacity 0.3s ease;
  1763. &.active {
  1764. opacity: 1;
  1765. }
  1766. // 非活动项半透明显示
  1767. // &:not(.active) {
  1768. // opacity: 0.7;
  1769. // }
  1770. }
  1771. .loading-tip {
  1772. position: absolute;
  1773. top: 50%;
  1774. left: 50%;
  1775. transform: translate(-50%, -50%);
  1776. display: flex;
  1777. flex-direction: column;
  1778. align-items: center;
  1779. justify-content: center;
  1780. z-index: 10;
  1781. .loading-text {
  1782. color: #ffffff;
  1783. font-size: 28rpx;
  1784. margin-top: 20rpx;
  1785. }
  1786. }
  1787. .loading-more,
  1788. .no-more {
  1789. display: flex;
  1790. justify-content: center;
  1791. align-items: center;
  1792. padding: 20rpx 0;
  1793. color: #999;
  1794. font-size: 24rpx;
  1795. }
  1796. .loading-more {
  1797. flex-direction: column;
  1798. }
  1799. .preload-indicator {
  1800. position: absolute;
  1801. top: 50%;
  1802. right: 30rpx;
  1803. transform: translateY(-50%);
  1804. z-index: 100;
  1805. background: rgba(0, 0, 0, 0.5);
  1806. border-radius: 50%;
  1807. padding: 16rpx;
  1808. }
  1809. /* button自带样式清除 */
  1810. .student-orther-icon button::after {
  1811. border: none !important;
  1812. padding: 0 !important;
  1813. margin: 0 !important;
  1814. }
  1815. .student-orther-icon button {
  1816. background-color: transparent !important;
  1817. padding: 0 !important;
  1818. line-height: inherit !important;
  1819. margin: 0 !important;
  1820. width: auto !important;
  1821. font-weight: 500 !important;
  1822. border-radius: none !important;
  1823. }
  1824. .welcome-message {
  1825. position: fixed;
  1826. width: 100%;
  1827. bottom: 460rpx;
  1828. left: 50%;
  1829. transform: translateX(-50%);
  1830. color: white;
  1831. padding: 10px 20px;
  1832. border-radius: 20px;
  1833. // animation: fadeOut 1s ease 1s forwards;
  1834. z-index: 1000;
  1835. transition: opacity 0.3s ease;
  1836. }
  1837. @keyframes fadeOut {
  1838. from {
  1839. opacity: 1;
  1840. }
  1841. to {
  1842. opacity: 0;
  1843. }
  1844. }
  1845. .send {
  1846. background-color: #fafafa;
  1847. border-radius: 28rpx;
  1848. padding: 14rpx 16rpx;
  1849. color: #181818;
  1850. font-weight: 500;
  1851. }
  1852. // .container {
  1853. // position: relative;
  1854. // width: 100%;
  1855. // height: 100vh;
  1856. // overflow: hidden;
  1857. // }
  1858. // .talktext {
  1859. // border-radius: 8rpx;
  1860. // background-color: rgba(255, 255, 255, 0.1);
  1861. // view {
  1862. // width: 100%;
  1863. // }
  1864. // }
  1865. .talk-list {
  1866. border-radius: 30rpx;
  1867. background-color: rgba(33, 33, 33, 0.5);
  1868. padding: 10rpx 30rpx;
  1869. }
  1870. // .zoom-button-active {
  1871. // transform: scale(1.5);
  1872. // }
  1873. // .background-image {
  1874. // position: absolute;
  1875. // top: 0;
  1876. // left: -40rpx;
  1877. // width: 110%;
  1878. // height: 110%;
  1879. // object-fit: cover;
  1880. // filter: blur(20px);
  1881. // z-index: 0;
  1882. // }
  1883. // .background-images {
  1884. // position: absolute;
  1885. // top: 0;
  1886. // left: -40rpx;
  1887. // width: 110%;
  1888. // height: 110%;
  1889. // object-fit: cover;
  1890. // filter: blur(20px);
  1891. // z-index: 6;
  1892. // }
  1893. // .blackbg {
  1894. // position: absolute;
  1895. // top: 0;
  1896. // left: 0;
  1897. // width: 100%;
  1898. // height: 100%;
  1899. // background: rgba(0, 0, 0, 0.7);
  1900. // object-fit: cover;
  1901. // filter: blur(10px);
  1902. // z-index: 1;
  1903. // }
  1904. .content {
  1905. position: relative;
  1906. z-index: 2;
  1907. height: 100%;
  1908. width: 100%;
  1909. top: 0;
  1910. left: 0;
  1911. display: flex;
  1912. flex-direction: column;
  1913. justify-content: space-between;
  1914. .siderow-group {
  1915. position: absolute;
  1916. top: 65%;
  1917. right: 30rpx;
  1918. z-index: 9;
  1919. display: flex;
  1920. flex-direction: column;
  1921. align-items: center;
  1922. .side-item {
  1923. font-weight: 500;
  1924. font-size: 24rpx;
  1925. color: #FFFFFF;
  1926. margin-bottom: 32rpx;
  1927. text-align: center;
  1928. .button {
  1929. background-color: transparent;
  1930. margin: 0;
  1931. line-height: 1;
  1932. padding: 0;
  1933. }
  1934. .image {
  1935. width: 72rpx;
  1936. height: 72rpx;
  1937. }
  1938. }
  1939. }
  1940. .side-group {
  1941. position: absolute;
  1942. // top: 30%;
  1943. top: 65%;
  1944. right: 30rpx;
  1945. z-index: 9;
  1946. display: flex;
  1947. flex-direction: column;
  1948. align-items: center;
  1949. .side-item {
  1950. font-weight: 500;
  1951. font-size: 24rpx;
  1952. color: #FFFFFF;
  1953. margin-bottom: 32rpx;
  1954. text-align: center;
  1955. .button {
  1956. background-color: transparent;
  1957. margin: 0;
  1958. line-height: 1;
  1959. padding: 0;
  1960. }
  1961. .image {
  1962. width: 72rpx;
  1963. height: 72rpx;
  1964. }
  1965. }
  1966. }
  1967. .content-top {
  1968. width: 100%;
  1969. margin-top: 68rpx;
  1970. display: flex;
  1971. justify-content: space-between;
  1972. padding: 0 24rpx;
  1973. box-sizing: border-box;
  1974. .sum {
  1975. width: 80rpx;
  1976. height: 52rpx;
  1977. background: rgba(0, 0, 0, 0.5);
  1978. border-radius: 26rpx 26rpx 26rpx 26rpx;
  1979. font-size: 24rpx;
  1980. color: #FFFFFF;
  1981. text-align: center;
  1982. line-height: 52rpx;
  1983. }
  1984. }
  1985. .follow-btn {
  1986. padding: 8rpx 16rpx;
  1987. background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
  1988. border-radius: 26rpx;
  1989. font-weight: 500;
  1990. font-size: 26rpx;
  1991. color: #FFFFFF;
  1992. }
  1993. }
  1994. .videolist {
  1995. position: relative;
  1996. .video {
  1997. height: 100vh;
  1998. /* 占屏幕高度的80% */
  1999. width: 100%;
  2000. background-color: rgba(57, 57, 57, 0.4);
  2001. .time {
  2002. color: #ffffff;
  2003. font-size: 20rpx;
  2004. margin-left: 10rpx;
  2005. }
  2006. .videotop {
  2007. width: 100%;
  2008. height: 100%;
  2009. }
  2010. .video_row {
  2011. width: 100%;
  2012. max-height: 500rpx;
  2013. overflow: hidden;
  2014. margin-top: 360rpx;
  2015. }
  2016. }
  2017. }
  2018. .goods {
  2019. position: fixed;
  2020. // bottom: 160rpx;
  2021. // right: 10rpx;
  2022. top: 50%;
  2023. left: 50%;
  2024. transform: translate(-50%, -50%);
  2025. z-index: 5;
  2026. background-color: #fff;
  2027. border-radius: 20rpx;
  2028. overflow: hidden;
  2029. width: 300rpx;
  2030. // width: 220rpx;
  2031. padding: 4rpx;
  2032. .top {
  2033. position: absolute;
  2034. top: 4rpx;
  2035. display: flex;
  2036. justify-content: space-between;
  2037. align-items: center;
  2038. color: #fff;
  2039. width: 100%;
  2040. padding-right: 10rpx;
  2041. box-sizing: border-box;
  2042. .left {
  2043. background-color: rgba(0, 0, 0, 0.8);
  2044. padding: 10rpx;
  2045. font-size: 20rpx;
  2046. display: flex;
  2047. justify-content: space-between;
  2048. align-items: center;
  2049. border-radius: 10rpx;
  2050. }
  2051. }
  2052. .photo {
  2053. width: 100%;
  2054. height: 250rpx;
  2055. border-radius: 16rpx 16rpx 0 0;
  2056. overflow: hidden;
  2057. }
  2058. .item {
  2059. padding: 4rpx;
  2060. .price {
  2061. .red {
  2062. color: #FF5701;
  2063. font-weight: 600;
  2064. margin-right: 10rpx;
  2065. }
  2066. .del {
  2067. color: #828282;
  2068. font-weight: 500;
  2069. font-size: 24rpx;
  2070. text-decoration: line-through
  2071. }
  2072. }
  2073. .title {
  2074. font-weight: 500;
  2075. font-size: 26rpx;
  2076. margin: 10rpx 0 12rpx;
  2077. }
  2078. .button {
  2079. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  2080. color: #fff;
  2081. text-align: center;
  2082. padding: 16rpx 0;
  2083. border-radius: 10rpx;
  2084. font-weight: 500;
  2085. }
  2086. }
  2087. }
  2088. .icon {
  2089. font-weight: 500;
  2090. font-size: 24rpx;
  2091. color: #FFFFFF;
  2092. text-align: center;
  2093. margin-bottom: -10rpx;
  2094. .button {
  2095. background-color: transparent;
  2096. margin: 0;
  2097. line-height: 1;
  2098. padding: 0;
  2099. }
  2100. }
  2101. .icon-bg {
  2102. background-color: rgba(57, 57, 57, 0.8);
  2103. border-radius: 50%;
  2104. width: 72rpx;
  2105. height: 72rpx;
  2106. display: flex;
  2107. justify-content: center;
  2108. align-items: center;
  2109. transition: transform 0.2s ease;
  2110. .button {
  2111. background-color: transparent;
  2112. margin: 0;
  2113. line-height: 1;
  2114. padding: 0;
  2115. }
  2116. }
  2117. .list {
  2118. width: 80%;
  2119. margin-bottom: 20rpx;
  2120. animation: xxxawdawd .2s;
  2121. }
  2122. @keyframes xxxawdawd {
  2123. from {
  2124. margin-top: 0rpx;
  2125. opacity: 0;
  2126. }
  2127. to {
  2128. margin-top: 20rpx;
  2129. opacity: 1;
  2130. }
  2131. }
  2132. .shop-prompt {
  2133. position: absolute;
  2134. bottom: 600rpx;
  2135. left: 24rpx;
  2136. padding: 6rpx 20rpx;
  2137. background: rgba(230, 154, 34, 0.7);
  2138. border-radius: 24rpx;
  2139. z-index: 9;
  2140. font-weight: 500;
  2141. font-size: 26rpx;
  2142. color: #FFFFFF;
  2143. transition: opacity 0.3s ease;
  2144. }
  2145. .red-box {
  2146. .button {
  2147. margin: 0 auto;
  2148. width: 80%;
  2149. line-height: 88rpx;
  2150. height: 88rpx;
  2151. background: linear-gradient(90deg, #FF5701 0%, #FFB501 100%);
  2152. box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(238, 124, 80, 0.2);
  2153. border-radius: 44rpx 44rpx 44rpx 44rpx;
  2154. font-weight: 600;
  2155. font-size: 32rpx;
  2156. color: #FFFFFF;
  2157. text-align: center;
  2158. }
  2159. }
  2160. .view-box {
  2161. position: relative;
  2162. height: 40vh;
  2163. /* 设置弹出层高度为视窗高度的70% */
  2164. padding: 40rpx 0rpx 120rpx;
  2165. box-sizing: border-box;
  2166. display: flex;
  2167. flex-direction: column;
  2168. .scroll-content {
  2169. flex: 1;
  2170. overflow-y: auto;
  2171. padding: 0 40rpx;
  2172. }
  2173. .bottom {
  2174. padding: 20rpx 40rpx;
  2175. position: absolute;
  2176. bottom: 0;
  2177. width: 100%;
  2178. box-shadow: 0rpx -4rpx 10rpx 0rpx rgba(195, 195, 195, 0.3);
  2179. background: #fff;
  2180. }
  2181. }
  2182. .shoppop {
  2183. padding: 22rpx 16rpx;
  2184. .shoppop-top {
  2185. display: flex;
  2186. justify-content: space-between;
  2187. align-items: center;
  2188. padding: 0 16rpx 22rpx;
  2189. .search-input {
  2190. width: 414rpx;
  2191. height: 76rpx;
  2192. background: #FFFFFF;
  2193. border-radius: 36rpx;
  2194. margin-left: 20rpx;
  2195. padding: 0 32rpx;
  2196. box-sizing: border-box;
  2197. font-size: 24rpx;
  2198. margin-right: 24rpx;
  2199. }
  2200. .search-top {
  2201. font-size: 20rpx;
  2202. color: #222222;
  2203. }
  2204. }
  2205. .shop-list {
  2206. overflow: hidden;
  2207. .list-item {
  2208. display: flex;
  2209. align-items: center;
  2210. padding: 20rpx 16rpx;
  2211. background: #FFFFFF;
  2212. border-radius: 16rpx;
  2213. margin-bottom: 16rpx;
  2214. .goods-img {
  2215. width: 200rpx;
  2216. height: 200rpx;
  2217. border-radius: 16rpx;
  2218. overflow: hidden;
  2219. position: relative;
  2220. margin-right: 24rpx;
  2221. image {
  2222. width: 100%;
  2223. height: 100%;
  2224. }
  2225. .goods-label {
  2226. position: absolute;
  2227. top: 0;
  2228. width: 64rpx;
  2229. height: 40rpx;
  2230. background: rgba(0, 0, 0, 0.5);
  2231. border-radius: 16rpx 0rpx 16rpx 0rpx;
  2232. text-align: center;
  2233. font-weight: 500;
  2234. font-size: 28rpx;
  2235. color: #FFFFFF;
  2236. }
  2237. }
  2238. .goods-right {
  2239. flex: 1;
  2240. .goods-title {
  2241. font-weight: 500;
  2242. font-size: 28rpx;
  2243. color: #000000;
  2244. }
  2245. .goods-details {
  2246. font-size: 24rpx;
  2247. color: #999999;
  2248. margin: 10rpx 0 20rpx;
  2249. }
  2250. .goods-people {
  2251. font-size: 22rpx;
  2252. color: #E69A22;
  2253. height: 56rpx;
  2254. }
  2255. .goods-shop {
  2256. display: flex;
  2257. justify-content: space-between;
  2258. .nummber {
  2259. color: #FF5C03;
  2260. font-size: 22rpx;
  2261. font-weight: 500;
  2262. }
  2263. .btn-group {
  2264. text-align: center;
  2265. line-height: 56rpx;
  2266. .collect-btn {
  2267. width: 72rpx;
  2268. background: #F5F7FA;
  2269. border-radius: 8rpx 0rpx 0rpx 8rpx;
  2270. }
  2271. .shop-btn {
  2272. width: 152rpx;
  2273. background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
  2274. border-radius: 0rpx 8rpx 8rpx 0rpx;
  2275. font-weight: 500;
  2276. font-size: 26rpx;
  2277. color: #FFFFFF;
  2278. }
  2279. }
  2280. }
  2281. }
  2282. }
  2283. }
  2284. }
  2285. :deep(.u-list-item) {
  2286. width: 100%;
  2287. display: flex;
  2288. align-items: center;
  2289. }
  2290. :deep(.u-safe-area-inset-bottom) {
  2291. padding-bottom: 0
  2292. }
  2293. </style>