living.vue 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539
  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="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="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. // 强制关闭并删除实例,确保连接被释放
  705. if (this.socketInstances[oldLive.liveId]) {
  706. try {
  707. this.socketInstances[oldLive.liveId].instance.close({
  708. code: 1000,
  709. reason: '切换直播间'
  710. });
  711. console.log(`关闭旧直播间 ${oldLive.liveId} WebSocket`);
  712. } catch (e) {
  713. console.error('关闭旧连接失败:', e);
  714. }
  715. delete this.socketInstances[oldLive.liveId]; // 彻底删除实例
  716. }
  717. }
  718. // 2. 处理新直播间(后续逻辑不变)
  719. this.currentSwiperIndex = newIndex;
  720. const newLive = this.list[newIndex];
  721. if (!newLive) return;
  722. this.liveId = newLive.liveId;
  723. this.resetUserListParams();
  724. await this.initCurrentLiveData(); // 内部会启动新直播间的定时器
  725. this.getliveUser(false);
  726. setTimeout(() => {
  727. this.playVideo(newLive);
  728. }, 100);
  729. },
  730. // 获取直播间列表
  731. async getList() {
  732. const data = {
  733. page: 1,
  734. page_size: 20
  735. };
  736. try {
  737. const res = await liveList(data);
  738. if (res.code === 200) {
  739. this.list = res.rows.map(item => ({
  740. ...item,
  741. talklist: [],
  742. loading: false,
  743. loaded: false,
  744. shopping: false,
  745. inputInfo: '',
  746. showWelcomeMessage: false,
  747. redInfo: {},
  748. goodsCard: {},
  749. totalTime: '00小时00分钟00秒', // 初始化差值为0
  750. timeTimer: null, // 存储当前直播间的定时器,用于后续清理
  751. // 预处理:统一将 startTime 转换为 iOS 兼容格式(避免重复转换)
  752. startTime: item.startTime ? item.startTime.replace(/-/g, '/') : ''
  753. // 其他初始化字段...
  754. }));
  755. console.log("直播间列表加载成功,数量:", this.list.length); // 确认数量是否 > 0
  756. } else {
  757. uni.showToast({
  758. title: res.msg,
  759. icon: "none"
  760. });
  761. this.list = []; // 接口失败时清空列表,避免后续错误
  762. }
  763. } catch (error) {
  764. console.error("获取直播间列表失败:", error);
  765. this.list = []; // 异常时清空列表
  766. }
  767. },
  768. // 播放视频
  769. playVideo(liveItem) {
  770. if (!liveItem) return;
  771. try {
  772. const videoId = `myVideo_${liveItem.liveId}`;
  773. const videoContext = uni.createVideoContext(videoId, this);
  774. if (videoContext) {
  775. videoContext.pause(() => {
  776. // 暂停完成后再播放
  777. videoContext.play();
  778. });
  779. }
  780. } catch (error) {
  781. console.error("播放视频失败:", error);
  782. }
  783. },
  784. pauseVideo(liveItem) {
  785. if (!liveItem) return;
  786. try {
  787. const videoId = `myVideo_${liveItem.liveId}`;
  788. const videoContext = uni.createVideoContext(videoId, this);
  789. if (videoContext) {
  790. videoContext.pause();
  791. }
  792. } catch (error) {
  793. console.error("暂停视频失败:", error);
  794. }
  795. },
  796. // 预加载相邻直播间
  797. async preloadNearbyLives(includeWebSocket = false) {
  798. this.preloading = true;
  799. const currentIndex = this.currentSwiperIndex;
  800. const preloadIndexes = [];
  801. // 只预加载数据,不初始化WebSocket(强制关闭WebSocket预加载)
  802. includeWebSocket = false; // 关键:强制不预加载WebSocket
  803. if (currentIndex > 0) preloadIndexes.push(currentIndex - 1);
  804. if (currentIndex < this.list.length - 1) preloadIndexes.push(currentIndex + 1);
  805. for (const index of preloadIndexes) {
  806. const liveItem = this.list[index];
  807. if (!liveItem || liveItem.loaded || liveItem.loading) continue;
  808. liveItem.loading = true;
  809. try {
  810. // 只加载基础数据,不初始化WebSocket
  811. await Promise.all([
  812. this.getliving(liveItem),
  813. this.getLiveMsg(liveItem),
  814. this.getliveViewData(liveItem),
  815. this.getShowGoods(liveItem)
  816. ]);
  817. liveItem.loaded = true;
  818. } catch (error) {
  819. console.error(`预加载直播间 ${index} 失败:`, error);
  820. liveItem.loaded = false;
  821. } finally {
  822. liveItem.loading = false;
  823. }
  824. }
  825. this.preloading = false;
  826. },
  827. openViews() {
  828. // 计算scroll-view高度
  829. this.$nextTick(() => {
  830. const query = uni.createSelectorQuery().in(this);
  831. query.select('.view-box').boundingClientRect(data => {
  832. if (data) {
  833. // 减去标题和底部固定区域的高度
  834. this.scrollHeight = data.height - 80 - 120; // 80是标题高度,120是底部高度
  835. }
  836. }).exec();
  837. });
  838. },
  839. // 重置直播间数据
  840. resetLiveData() {
  841. // 保留不需要重置的数据(如用户信息等)
  842. const keepData = {
  843. userinfo: this.userinfo,
  844. list: this.list,
  845. currentSwiperIndex: this.currentSwiperIndex
  846. };
  847. // 重置其他直播间特定数据
  848. this.liveUserTotal = null;
  849. // this.liveViewData = {};
  850. this.liveViewers = [];
  851. this.livingUrl = "";
  852. this.videoUrl = null;
  853. this.products = {};
  854. this.store = {};
  855. this.orderUser = {};
  856. this.talklist = [];
  857. this.livedata = {};
  858. // this.isFollow = false;
  859. this.shopping = false;
  860. this.inputInfo = ''
  861. // 恢复需要保留的数据
  862. Object.assign(this, keepData);
  863. },
  864. // 获取直播间用户
  865. async getliveUser(isLoadMore = false) {
  866. // 强制使用当前 liveId,避免使用旧值
  867. const currentLiveId = this.liveId;
  868. if (!currentLiveId) return;
  869. // if (this.viewLoading || this.viewNoMoreData) return;
  870. this.viewLoading = true;
  871. try {
  872. const res = await watchUserList(currentLiveId, this.viewPageSize, this.viewPageNum, false);
  873. if (res.code === 200) {
  874. // 若请求期间已切换直播间,忽略旧数据
  875. if (this.liveId !== currentLiveId) return;
  876. this.liveUserTotal = res.total;
  877. if (res.rows.length === 0) {
  878. this.viewNoMoreData = true;
  879. return;
  880. }
  881. this.liveViewers = isLoadMore ? [...this.liveViewers, ...res.rows] : res
  882. .rows; // 首次加载/切换直播间时重置数据
  883. this.viewPageNum++;
  884. // console.log("在线观众", this.liveViewers)
  885. }
  886. } catch (error) {
  887. console.error('获取观众列表失败:', error);
  888. } finally {
  889. this.viewLoading = false;
  890. }
  891. },
  892. // 滚动到底部触发
  893. handleScrollToLower() {
  894. // 清除上一次未执行的定时器,避免重复请求
  895. if (this.scrollTimer) {
  896. clearTimeout(this.scrollTimer);
  897. }
  898. // 延迟0.5秒(500毫秒)执行接口请求
  899. this.scrollTimer = setTimeout(() => {
  900. this.getliveUser(true); // 加载更多数据
  901. }, 1000); // 延迟时间:500毫秒
  902. },
  903. async getLiveMsg(liveItem) {
  904. // 强化校验:确保 liveItem 存在且包含 liveId
  905. if (!liveItem || !liveItem.liveId) {
  906. console.error('getLiveMsg 错误:无效的 liveItem', {
  907. liveItem: liveItem,
  908. currentIndex: this.currentSwiperIndex,
  909. listLength: this.list.length
  910. });
  911. return; // 直接返回,不执行后续逻辑
  912. }
  913. try {
  914. const res = await liveMsg(liveItem.liveId, 30, 1);
  915. if (res.code == 200) {
  916. // 确保使用响应式更新
  917. this.$set(liveItem, 'talklist', [...res.rows]);
  918. this.$nextTick(() => {
  919. this.$set(liveItem, 'scrollIntoView', `list_${liveItem.talklist.length-1}`);
  920. });
  921. }
  922. } catch (error) {
  923. console.error("获取聊天记录失败:", error);
  924. }
  925. },
  926. // 点击红包
  927. onRed(item) {
  928. // console.log("点了this.liveId", item)
  929. if (!item.liveId) return;
  930. // console.log("点了this.liveId", this.liveId)
  931. if (!item.redInfo?.redId) return;
  932. // console.log("点了this.redInfo?.redId", this.redInfo.redId)
  933. // console.log("点了this.userinfo.userId", this.userinfo.userId)
  934. let data = {
  935. liveId: item.liveId,
  936. userId: this.userinfo.userId,
  937. redId: item.redInfo.redId,
  938. }
  939. console.log("点了this.liveId", data)
  940. liveRed(data).then(res => {
  941. if (res.code == 200) {
  942. uni.showToast({
  943. title: res.msg,
  944. icon: 'none'
  945. });
  946. } else {
  947. uni.showToast({
  948. title: res.msg,
  949. icon: 'none'
  950. });
  951. }
  952. },
  953. rej => {}
  954. );
  955. },
  956. handleSearchInput() {
  957. // 使用防抖优化性能,避免频繁请求
  958. clearTimeout(this.searchTimer);
  959. this.searchTimer = setTimeout(() => {
  960. this.queryCollect();
  961. }, 500); // 500毫秒延迟
  962. },
  963. // 显示购买提示信息
  964. showPurchaseMessage() {
  965. // 清除之前的定时器
  966. if (this.purchasePromptTimer) {
  967. clearTimeout(this.purchasePromptTimer);
  968. }
  969. // 显示提示
  970. this.showPurchasePrompt = true;
  971. // 2秒后自动隐藏
  972. this.purchasePromptTimer = setTimeout(() => {
  973. this.showPurchasePrompt = false;
  974. }, 2000);
  975. },
  976. truncateString(str, maxLength) {
  977. return str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
  978. },
  979. goStore(item) {
  980. console.log("带过去storeId", item)
  981. if (!item.storeId) {
  982. uni.showToast({
  983. title: "当前直播间暂未开通店铺",
  984. icon: 'none'
  985. });
  986. return;
  987. }
  988. uni.navigateTo({
  989. url: '/pages_shop/store?liveId=' + item.liveId + "&storeId=" + item.storeId
  990. })
  991. },
  992. // 去订单列表
  993. goOrderList() {
  994. uni.navigateTo({
  995. url: "/pages_shop/order"
  996. })
  997. },
  998. // 初始化HLS播放器
  999. initHlsPlayer() {
  1000. if (Hls.isSupported() && this.livingUrl) {
  1001. const video = document.getElementById('myVideo');
  1002. if (video) {
  1003. this.hlsPlayer = new Hls();
  1004. this.hlsPlayer.loadSource(this.livingUrl);
  1005. this.hlsPlayer.attachMedia(video);
  1006. this.hlsPlayer.on(Hls.Events.MANIFEST_PARSED, () => {
  1007. video.play();
  1008. });
  1009. }
  1010. }
  1011. },
  1012. // 视频错误处理
  1013. videoError(e, liveItem) {
  1014. if (!liveItem || liveItem.liveId !== this.liveId) return;
  1015. // 初始化重试计数
  1016. if (this.videoRetryCounts[liveItem.liveId] === undefined) {
  1017. this.videoRetryCounts[liveItem.liveId] = 0;
  1018. }
  1019. // 限制重试次数
  1020. if (this.videoRetryCounts[liveItem.liveId] >= 3) {
  1021. console.error(`直播间 ${liveItem.liveId} 视频加载失败,停止重试`);
  1022. // 显示错误提示
  1023. uni.showToast({
  1024. title: "视频加载失败,请检查网络",
  1025. icon: 'none',
  1026. duration: 2000
  1027. });
  1028. return;
  1029. }
  1030. this.videoRetryCounts[liveItem.liveId]++;
  1031. // 延迟重试
  1032. setTimeout(() => {
  1033. if (liveItem.liveId === this.liveId) {
  1034. console.log(`第${this.videoRetryCounts[liveItem.liveId]}次重试播放视频`);
  1035. this.playVideo(liveItem);
  1036. }
  1037. }, 2000);
  1038. },
  1039. // 修改获取直播信息方法
  1040. async getliving(liveItem) {
  1041. if (!liveItem || !liveItem.liveId) return;
  1042. // console.log("获取直播信息:", liveItem.liveId);
  1043. const param = {
  1044. id: liveItem.liveId
  1045. };
  1046. try {
  1047. const res = await getlive({
  1048. id: liveItem.liveId
  1049. });
  1050. if (res.code !== 200) {
  1051. uni.showToast({
  1052. title: res.msg,
  1053. icon: 'none'
  1054. });
  1055. return;
  1056. }
  1057. // 强制更新视频源(覆盖旧值)
  1058. if (res.data.liveType === 2) {
  1059. // 回放视频
  1060. this.$set(liveItem, 'videoUrl', res.data.videoUrl);
  1061. this.$set(liveItem, 'livingUrl', ''); // 清空直播流
  1062. this.$set(liveItem, 'placeholderText', "说点什么...");
  1063. } else if (res.data.liveType === 1) {
  1064. // 直播流
  1065. this.$set(liveItem, 'livingUrl', res.data.flvHlsUrl);
  1066. this.$set(liveItem, 'videoUrl', ''); // 清空回放视频
  1067. this.$set(liveItem, 'placeholderText', "说点什么...");
  1068. } else {
  1069. // 未开播
  1070. this.$set(liveItem, 'livingUrl', '');
  1071. this.$set(liveItem, 'videoUrl', '');
  1072. }
  1073. // 更新其他直播信息
  1074. // 仅当是当前激活的直播间时,才允许自动播放
  1075. const isCurrentLive = this.currentSwiperIndex === this.list.findIndex(item => item.liveId ===
  1076. liveItem.liveId);
  1077. this.$set(liveItem, 'autoplay', isCurrentLive && res.data.liveType !== 0);
  1078. this.$set(liveItem, 'showType', res.data.showType);
  1079. this.$set(liveItem, 'storeId', res.storeId);
  1080. this.queryCollect();
  1081. } catch (err) {
  1082. console.error("获取直播信息失败:", err);
  1083. uni.showToast({
  1084. title: "获取直播信息失败",
  1085. icon: 'none'
  1086. });
  1087. }
  1088. }, // 设置视频播放
  1089. setupVideoPlayback(liveItem, liveData) {
  1090. if (!liveItem.livingUrl) return;
  1091. // H5 平台:使用 HLS.js 处理 .m3u8 流
  1092. // #ifdef H5
  1093. if (liveItem.livingUrl.includes('.m3u8')) {
  1094. this.initHlsPlayer(liveItem);
  1095. return;
  1096. }
  1097. // #endif
  1098. // 小程序/App 平台:直接使用 video 组件
  1099. const videoId = `myVideo_${liveItem.liveId}`;
  1100. const videoContext = uni.createVideoContext(videoId, this);
  1101. if (liveData.liveType === 1) {
  1102. // 回放:跳转到指定位置
  1103. videoContext.seek(liveData.nowDuration || 0);
  1104. } else {
  1105. // 直播:直接播放
  1106. videoContext.play();
  1107. }
  1108. },
  1109. maskString(str, maskChar = '*') {
  1110. // 如果str是undefined或null,直接返回空字符串
  1111. if (!str) return '';
  1112. // 确保str是字符串(如果是数字等类型,先转为字符串)
  1113. const strVal = String(str);
  1114. return strVal.split('').map((char, index) => (index === 0 ? char : maskChar)).join('');
  1115. },
  1116. getPureDecimal(num, precision = 6) {
  1117. const decimalPart = Math.abs(num).toFixed(precision).split('.')[1];
  1118. return decimalPart?.replace(/0+$/, '') || ''; // 移除末尾多余的0
  1119. },
  1120. // 返回上一个页面并关闭WebSocket
  1121. goBack() {
  1122. // 暂停当前视频
  1123. const currentLive = this.list[this.currentSwiperIndex];
  1124. if (currentLive) {
  1125. this.pauseVideo(currentLive);
  1126. }
  1127. // 关闭所有WebSocket连接
  1128. this.closeWebSocket();
  1129. // 导航返回
  1130. const pages = getCurrentPages();
  1131. if (pages.length > 1) {
  1132. uni.navigateBack();
  1133. } else {
  1134. uni.reLaunch({
  1135. url: '/pages/list/index'
  1136. });
  1137. }
  1138. },
  1139. //正在购买
  1140. async getliveOrder() {
  1141. const currentLiveId = this.liveId;
  1142. if (!currentLiveId) return;
  1143. try {
  1144. const res = await liveOrderUser(currentLiveId);
  1145. if (res.code === 200) {
  1146. // 绑定到当前 liveItem
  1147. const currentLive = this.list[this.currentSwiperIndex];
  1148. if (currentLive) {
  1149. this.$set(currentLive, 'orderUser', res);
  1150. this.orderUser = res; // 同步全局变量
  1151. }
  1152. }
  1153. } catch (error) {
  1154. console.error('获取正在购买用户失败:', error);
  1155. }
  1156. },
  1157. // 获取直播间信息接口
  1158. getLiveinformation() {
  1159. if (!this.liveId) return;
  1160. getLiveInfo(this.liveId).then(res => {
  1161. if (res.code == 200) {
  1162. console.log("获取直播间信息接口>>>>", res)
  1163. this.livingUrl = res.livingUrl
  1164. } else {
  1165. uni.showToast({
  1166. title: res.msg,
  1167. icon: 'none'
  1168. });
  1169. }
  1170. },
  1171. rej => {}
  1172. );
  1173. },
  1174. // 点赞
  1175. async onLike(liveItem) {
  1176. if (!liveItem || !liveItem.liveId) return;
  1177. try {
  1178. const res = await liveDataLike(liveItem.liveId);
  1179. if (res?.like) {
  1180. liveItem.liveViewData.like++; // 只更新当前直播间的点赞数
  1181. } else {
  1182. uni.showToast({
  1183. title: res.msg,
  1184. icon: 'none'
  1185. });
  1186. }
  1187. } catch (error) {
  1188. console.error('点赞失败:', error);
  1189. }
  1190. },
  1191. // 点赞
  1192. // async onLike(liveItem) {
  1193. // // 基础校验
  1194. // if (!liveItem || !liveItem.liveId) return;
  1195. // // 确保liveViewData存在(初始化默认值)
  1196. // if (!liveItem.liveViewData) {
  1197. // await this.getliveViewData(liveItem);
  1198. // if (!liveItem.liveViewData) {
  1199. // uni.showToast({
  1200. // title: "数据加载中,请稍后再试",
  1201. // icon: 'none'
  1202. // });
  1203. // return;
  1204. // }
  1205. // // 初始化点赞数(防止undefined)
  1206. // liveItem.liveViewData.like = liveItem.liveViewData.like || 0;
  1207. // }
  1208. // // 限制最多10次点赞
  1209. // const maxLikeCount = 10;
  1210. // if (liveItem.liveViewData.like >= maxLikeCount) {
  1211. // uni.showToast({
  1212. // title: "最多可点赞10次哦~",
  1213. // icon: 'none'
  1214. // });
  1215. // return;
  1216. // }
  1217. // try {
  1218. // const res = await liveDataLike(liveItem.liveId);
  1219. // if (res.code === 200) {
  1220. // // 无论后端是否返回res.like,前端按规则累加(最多到10次)
  1221. // const newLikeCount = Math.min(liveItem.liveViewData.like + 1, maxLikeCount);
  1222. // liveItem.liveViewData.like = newLikeCount;
  1223. // } else {
  1224. // uni.showToast({
  1225. // title: res.msg || "点赞失败",
  1226. // icon: 'none'
  1227. // });
  1228. // }
  1229. // } catch (error) {
  1230. // console.error('点赞失败:', error);
  1231. // uni.showToast({
  1232. // title: "网络异常,点赞失败",
  1233. // icon: 'none'
  1234. // });
  1235. // }
  1236. // },
  1237. //直播间点赞、关注、在线人数数据
  1238. async getliveViewData(liveItem) {
  1239. if (!liveItem || !liveItem.liveId) return;
  1240. try {
  1241. const res = await getLiveViewData(liveItem.liveId);
  1242. if (res.code == 200) {
  1243. // 强制响应式更新,确保数据实时显示
  1244. this.$set(liveItem, 'liveViewData', res);
  1245. }
  1246. } catch (error) {
  1247. console.error("获取直播间数据失败:", error);
  1248. // 失败时兜底,避免显示异常
  1249. this.$set(liveItem, 'liveViewData', {
  1250. like: 0,
  1251. watchCount: 0
  1252. });
  1253. }
  1254. },
  1255. //弹出商品卡片
  1256. async getShowGoods(liveItem) {
  1257. if (!liveItem || !liveItem.liveId) return;
  1258. try {
  1259. const res = await showGoods(liveItem.liveId);
  1260. if (res.code == 200) {
  1261. this.$set(liveItem, 'goodsCard', res);
  1262. }
  1263. } catch (error) {
  1264. console.error("暂无商品卡片", error);
  1265. }
  1266. },
  1267. // 去购买,跳商品详情
  1268. goShop(productId, goodsId) {
  1269. const currentLive = this.list[this.currentSwiperIndex];
  1270. if (!currentLive || !currentLive.liveId) return;
  1271. uni.navigateTo({
  1272. url: '/pages_shop/goods?productId=' + productId + '&liveId=' + currentLive.liveId +
  1273. '&goodsId=' + goodsId + '&storeId=' + currentLive.storeId
  1274. })
  1275. },
  1276. // 查询店铺
  1277. async queryCollect() {
  1278. const currentLive = this.list[this.currentSwiperIndex];
  1279. if (!currentLive || !currentLive.liveId) return;
  1280. const {
  1281. storeId
  1282. } = currentLive;
  1283. // console.log("小黄车数据>>>", currentLive)
  1284. if (!storeId) return;
  1285. try {
  1286. const res = await store(currentLive.storeId, currentLive.inputInfo, currentLive.liveId);
  1287. if (res.code === 200) {
  1288. // 数据绑定到当前 liveItem,避免全局污染
  1289. this.$set(currentLive, 'products', res.data.goodsList);
  1290. this.$set(currentLive, 'store', res.data);
  1291. // 同步更新全局变量(供弹窗使用)
  1292. this.products = res.data.goodsList;
  1293. this.store = res.data;
  1294. }
  1295. } catch (error) {
  1296. console.error('获取小黄车商品失败:', error);
  1297. }
  1298. },
  1299. // 店铺收藏
  1300. onStoreCollect(liveItem) {
  1301. console.log("店铺收藏", liveItem)
  1302. if (!liveItem.storeId) return;
  1303. collectStore(liveItem.storeId).then(res => {
  1304. if (res.code == 200) {
  1305. uni.showToast({
  1306. title: res.msg,
  1307. icon: 'none'
  1308. });
  1309. liveItem.store.isFavorite = !liveItem.store.isFavorite
  1310. } else {
  1311. uni.showToast({
  1312. title: res.msg,
  1313. icon: 'none'
  1314. });
  1315. }
  1316. },
  1317. rej => {}
  1318. );
  1319. },
  1320. // 商品收藏
  1321. onGoodsCollect(item) {
  1322. console.log("商品收藏", item)
  1323. if (!item || item.length === 0 || !item.goodsId) {
  1324. return;
  1325. }
  1326. collectGoods(item.goodsId).then(res => {
  1327. if (res.code == 200) {
  1328. uni.showToast({
  1329. title: res.msg,
  1330. icon: 'none'
  1331. });
  1332. item.isFavorite = !item.isFavorite
  1333. } else {
  1334. uni.showToast({
  1335. title: res.msg,
  1336. icon: 'none'
  1337. });
  1338. }
  1339. },
  1340. rej => {}
  1341. );
  1342. },
  1343. // 关注
  1344. // async onFollow(liveItem) {
  1345. // if (!liveItem || !liveItem.liveId) return;
  1346. // try {
  1347. // const res = await follow(liveItem.liveId);
  1348. // liveItem.isFollow = !liveItem.isFollow;
  1349. // uni.showToast({
  1350. // title: res.msg,
  1351. // icon: 'none'
  1352. // });
  1353. // } catch (error) {
  1354. // console.error("关注操作失败:", error);
  1355. // }
  1356. // },
  1357. // 时间戳
  1358. initTime() {
  1359. const now = new Date();
  1360. this.timestamp = now.getTime(); // 例如:'2023-04-01 12:00:00'
  1361. },
  1362. openShop() {
  1363. },
  1364. openViews() {
  1365. this.$nextTick(() => {
  1366. const query = uni.createSelectorQuery().in(this);
  1367. query.select('.view-box').boundingClientRect(data => {
  1368. if (data) {
  1369. this.scrollHeight = data.height - 80 - 120;
  1370. }
  1371. }).exec();
  1372. });
  1373. },
  1374. openCart(liveItem) {
  1375. if (!liveItem.storeId) {
  1376. uni.showToast({
  1377. title: "当前直播间暂未开通店铺",
  1378. icon: 'none'
  1379. });
  1380. return;
  1381. }
  1382. liveItem.shopping = !liveItem.shopping
  1383. },
  1384. close() {
  1385. this.showadd = false
  1386. },
  1387. // closes() {
  1388. // this.showziliao = !this.showziliao
  1389. // },
  1390. // 关闭小黄车
  1391. closeShop() {
  1392. // 通过当前swiper索引获取当前直播间实例
  1393. const currentLive = this.list[this.currentSwiperIndex];
  1394. if (currentLive) {
  1395. this.$set(currentLive, 'shopping', !currentLive.shopping);
  1396. }
  1397. },
  1398. // 关闭红包
  1399. closeRed() {
  1400. this.showRed = !this.showRed
  1401. },
  1402. // 触摸结束
  1403. // handleTouchEnd() {
  1404. // this.isZoom = false; // 恢复原状
  1405. // },
  1406. getEWechatSdk() {
  1407. // 只在H5平台执行
  1408. // #ifdef H5
  1409. let eWechatSdk = '';
  1410. if (/(Android)/i.test(navigator.userAgent)) {
  1411. eWechatSdk = 'jWeixin';
  1412. } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
  1413. eWechatSdk = 'wx';
  1414. } else {
  1415. eWechatSdk = 'jWeixin';
  1416. }
  1417. uni.setStorageSync("wxSdk", eWechatSdk);
  1418. // #endif
  1419. },
  1420. // 修改关闭WebSocket方法
  1421. closeWebSocket(liveId = null) {
  1422. this.isManualClose = true;
  1423. clearInterval(this.pingpangTimes);
  1424. clearInterval(this.reconnectTimer);
  1425. if (liveId) {
  1426. // 添加空值检查
  1427. if (this.socketInstances[liveId] && this.socketInstances[liveId].instance) {
  1428. try {
  1429. this.socketInstances[liveId].instance.close();
  1430. console.log(`直播间 ${liveId} WebSocket 已安全关闭`);
  1431. } catch (e) {
  1432. console.error(`关闭直播间 ${liveId} WebSocket 时出错:`, e);
  1433. }
  1434. }
  1435. delete this.socketInstances[liveId];
  1436. } else {
  1437. Object.keys(this.socketInstances).forEach(id => {
  1438. // 添加空值检查
  1439. if (this.socketInstances[id] && this.socketInstances[id].instance) {
  1440. try {
  1441. this.socketInstances[id].instance.close();
  1442. console.log(`直播间 ${id} WebSocket 已安全关闭`);
  1443. } catch (e) {
  1444. console.error(`关闭直播间 ${id} WebSocket 时出错:`, e);
  1445. }
  1446. }
  1447. });
  1448. this.socketInstances = {};
  1449. }
  1450. isSocketOpen = false;
  1451. },
  1452. reConnect() {
  1453. var that = this;
  1454. try {
  1455. uni.closeSocket();
  1456. } catch (e) {
  1457. }
  1458. setTimeout(function() {
  1459. that.initSocket();
  1460. }, 10000);
  1461. },
  1462. startHeartbeat(liveId) {
  1463. clearInterval(this.pingpangTimes);
  1464. this.pingpangTimes = setInterval(() => {
  1465. const inst = this.socketInstances[liveId];
  1466. if (!inst || !inst.isOpen || !inst.instance) return;
  1467. const pingData = {
  1468. cmd: 'ping',
  1469. timestamp: Date.now()
  1470. };
  1471. try {
  1472. inst.instance.send({
  1473. data: JSON.stringify(pingData)
  1474. });
  1475. } catch (err) {
  1476. console.error('心跳发送失败:', err);
  1477. this.scheduleReconnect(liveId);
  1478. }
  1479. }, 30000);
  1480. },
  1481. async initSocket(liveItem) {
  1482. const currentLive = this.list[this.currentSwiperIndex];
  1483. if (!currentLive || currentLive.liveId !== liveItem.liveId) {
  1484. console.log(`拒绝为非活跃直播间 ${liveItem.liveId} 建立WebSocket`);
  1485. return;
  1486. }
  1487. if (!liveItem || !liveItem.liveId) return;
  1488. const liveId = liveItem.liveId;
  1489. // 检查是否已经是当前连接或正在连接
  1490. if (this.connectingLiveId === liveId ||
  1491. (this.socketInstances[liveId] && this.socketInstances[liveId].isOpen)) {
  1492. console.log(`直播间 ${liveId} 的WebSocket已经连接或正在连接,跳过初始化`);
  1493. return;
  1494. }
  1495. // 检查是否是当前活跃的直播间
  1496. if (this.currentSwiperIndex !== this.list.findIndex(item => item.liveId === liveId)) {
  1497. console.log(`不初始化非当前直播间 ${liveId} 的WebSocket`);
  1498. return;
  1499. }
  1500. // 关闭之前的连接(如果存在)
  1501. if (this.socketInstances[liveId]) {
  1502. this.closeWebSocket(liveId);
  1503. }
  1504. // 设置正在连接的直播间ID
  1505. this.connectingLiveId = liveId;
  1506. // 防止重复创建
  1507. if (this.reconnectCount >= this.maxReconnectAttempts) {
  1508. this.connectingLiveId = null;
  1509. return;
  1510. }
  1511. this.isManualClose = false;
  1512. const connectTimeout = setTimeout(() => {
  1513. if (!this.socketInstances[liveId]?.isOpen) {
  1514. console.error(`WebSocket连接超时: ${liveId}`);
  1515. this.scheduleReconnect(liveId);
  1516. }
  1517. }, 10000); // 10秒超时
  1518. // 生成签名
  1519. const signature = CryptoJS.HmacSHA256(
  1520. `${liveId}${this.userinfo.userId}${this.userType}${this.timestamp}`,
  1521. this.timestamp.toString()
  1522. ).toString(CryptoJS.enc.Hex);
  1523. // 初始化实例状态
  1524. this.socketInstances[liveId] = {
  1525. instance: null,
  1526. isOpen: false
  1527. };
  1528. try {
  1529. const socketTask = uni.connectSocket({
  1530. url: `${wsUrl}?userId=${this.userinfo.userId}&liveId=${liveId}&userType=${this.userType}&timestamp=${this.timestamp}&signature=${signature}`,
  1531. success: () => {
  1532. console.log('WebSocket API 调用成功,正在建立连接...');
  1533. },
  1534. fail: (err) => {
  1535. console.error('WebSocket 连接失败:', err);
  1536. this.connectingLiveId = null;
  1537. this.scheduleReconnect(liveId);
  1538. }
  1539. });
  1540. socketTask.onOpen((res) => {
  1541. console.log('WebSocket 连接已成功建立', res);
  1542. this.socketInstances[liveId].instance = socketTask;
  1543. this.socketInstances[liveId].isOpen = true;
  1544. clearTimeout(connectTimeout);
  1545. isSocketOpen = true;
  1546. this.connectingLiveId = null;
  1547. this.reconnectCount = 0;
  1548. // 改用 socketTask 的 send 作为心跳
  1549. this.startHeartbeat(liveId); // 修改 startHeartbeat 以接受 liveId 并使用 socketTask.send
  1550. });
  1551. socketTask.onMessage((res) => {
  1552. // 找到对应的直播间并更新数据
  1553. const targetLive = this.list.find(item => item.liveId === liveId);
  1554. if (targetLive) {
  1555. this.handleSocketMessage(res, targetLive);
  1556. }
  1557. });
  1558. socketTask.onError((err) => {
  1559. clearTimeout(connectTimeout);
  1560. console.error('WebSocket 连接错误:', err);
  1561. this.connectingLiveId = null;
  1562. this.scheduleReconnect(liveId);
  1563. });
  1564. socketTask.onClose(() => {
  1565. console.log(`WebSocket 连接已关闭: ${liveId}`);
  1566. this.connectingLiveId = null;
  1567. });
  1568. } catch (e) {
  1569. console.error('创建 WebSocket 异常:', e);
  1570. this.connectingLiveId = null;
  1571. this.scheduleReconnect(liveId);
  1572. }
  1573. },
  1574. // 处理Socket消息
  1575. handleSocketMessage(message, liveItem) {
  1576. let data = JSON.parse(message.data)
  1577. const socketMessage = data.data
  1578. // console.log("处理",data)
  1579. if (data.code == 200) {
  1580. const messageData = {
  1581. ...socketMessage, // 原数据(可能包含部分字段)
  1582. cmd: socketMessage.cmd || '' // 强制添加cmd,确保存在(默认空字符串)
  1583. };
  1584. // console.log("messageData是",messageData)
  1585. if (socketMessage.cmd == 'sendMsg') {
  1586. // this.$set(liveItem, 'talklist', [...liveItem.talklist, messageData]);
  1587. this.$nextTick(() => {
  1588. this.$set(liveItem, 'scrollIntoView', `list_${liveItem.talklist.length-1}`);
  1589. });
  1590. } else if (socketMessage.cmd == 'red') {
  1591. // 领红包
  1592. this.$set(liveItem, 'redInfo', JSON.parse(socketMessage.data));
  1593. console.log("红包是liveItem.redInfo", liveItem)
  1594. // liveItem.redInfo = JSON.parse(message.data.data);
  1595. } else if (socketMessage.cmd == 'sendRedPacketQuestion') {
  1596. const list = JSON.parse(message.data.data);
  1597. // 处理红包答题逻辑
  1598. } else if (socketMessage.cmd == 'entry' || socketMessage.cmd == 'out') {
  1599. this.$set(liveItem, 'talklist', [...liveItem.talklist, messageData]);
  1600. // 先重置为 false(避免残留状态)
  1601. this.$set(liveItem, 'showWelcomeMessage', false);
  1602. // 立即设为 true(触发 DOM 更新)
  1603. this.$set(liveItem, 'showWelcomeMessage', true);
  1604. this.getliveUser(false); // 调用获取在线用户接口
  1605. // console.log("开启欢迎消息:", liveItem.showWelcomeMessage);
  1606. if (liveItem.welcomeTimer) {
  1607. clearTimeout(liveItem.welcomeTimer);
  1608. }
  1609. // 存储定时器到 liveItem 中(避免引用丢失)
  1610. liveItem.welcomeTimer = setTimeout(() => {
  1611. this.$set(liveItem, 'showWelcomeMessage', false);
  1612. // console.log("关闭欢迎消息:", liveItem.showWelcomeMessage);
  1613. }, 1000); // 1秒后隐藏
  1614. } else if (socketMessage.cmd == 'Integral') {
  1615. // 观看奖励事件 弹出框2s 显示msg
  1616. uni.showToast({
  1617. title: socketMessage.msg,
  1618. icon: 'none',
  1619. duration: 2000
  1620. });
  1621. } else if (socketMessage.cmd == 'blockUser') {
  1622. //拉黑事件 主动删除用户token,强制跳转到登录页面
  1623. uni.removeStorage({
  1624. key: 'AppToken', // 存储 Token 时的 key
  1625. success: () => {
  1626. uni.reLaunch({
  1627. url: '/pages/auth/login' // 登录页路径,需根据项目实际路径调整
  1628. });
  1629. console.log('Token 删除成功');
  1630. },
  1631. fail: (err) => {
  1632. console.error('Token 删除失败:', err);
  1633. }
  1634. });
  1635. } else if (socketMessage.cmd == 'goods') {
  1636. this.$set(liveItem, 'goodsCard', JSON.parse(socketMessage.data));
  1637. } else if (socketMessage.cmd == 'out') {
  1638. // console.log("进入:", liveItem);
  1639. console.log("有人退出了:");
  1640. } else if (socketMessage.cmd == 'live_start') {
  1641. // 直播开始
  1642. } else if (socketMessage.cmd == 'live_end') {
  1643. // 直播结束
  1644. } else if (socketMessage.data.cmd == 'deleteId') {
  1645. uni.$emit('deleteId');
  1646. } else if (socketMessage.data.cmd == 'sendRedPacketQuestion') {
  1647. // const list = JSON.parse(socketMessage)
  1648. // liveItem.redanswerAll = [...liveItem.redanswerAll, ...list]
  1649. // if (liveItem.redanswerAll[1].randomAmount !== null) {
  1650. // liveItem.redanswertips = JSON.parse(liveItem.redanswerAll[0]
  1651. // .randomAmount)
  1652. // }
  1653. }
  1654. } else {
  1655. uni.showToast({
  1656. title: data.msg,
  1657. icon: 'none'
  1658. });
  1659. }
  1660. },
  1661. scheduleReconnect(liveId) {
  1662. if (this.isManualClose || this.reconnectCount >= this.maxReconnectAttempts) return;
  1663. this.reconnectCount++;
  1664. const delay = Math.min(3000 * this.reconnectCount, 30000);
  1665. clearInterval(this.reconnectTimer);
  1666. this.reconnectTimer = setTimeout(() => {
  1667. // 使用传入的liveId
  1668. const liveItem = this.list.find(item => item.liveId === liveId) || {
  1669. liveId
  1670. };
  1671. this.initSocket(liveItem);
  1672. }, delay);
  1673. },
  1674. sendMsg(liveItem) {
  1675. if (!liveItem || !liveItem.liveId) return;
  1676. // 防止连续点击发送两次(短时锁定)
  1677. if (liveItem.isSending) return;
  1678. liveItem.isSending = true;
  1679. setTimeout(() => {
  1680. liveItem.isSending = false;
  1681. }, 800); // 800ms 内禁止再次发送
  1682. const text = (liveItem.value || '').trim();
  1683. if (!text) {
  1684. uni.showToast({
  1685. title: "不能发送空消息",
  1686. icon: 'none'
  1687. });
  1688. return;
  1689. }
  1690. const liveId = liveItem.liveId;
  1691. const socketItem = this.socketInstances[liveId];
  1692. // 乐观更新:立即把消息加入到本地聊天列表并清空输入(更好的体验)
  1693. const localMsg = {
  1694. cmd: 'sendMsg',
  1695. msg: text,
  1696. nickName: this.userinfo.nickName,
  1697. avatar: this.userinfo.avatar,
  1698. userId: this.userinfo.userId,
  1699. local: true, // 标记为本地消息(可用于样式或后续差异处理)
  1700. ts: Date.now()
  1701. };
  1702. this.$set(liveItem, 'talklist', [...(liveItem.talklist || []), localMsg]);
  1703. this.$set(liveItem, 'value', ''); // 立即清空输入
  1704. if (!socketItem || !socketItem.instance || !socketItem.isOpen) {
  1705. // 如果 socket 未连接,尝试建立连接(但不要阻塞用户)
  1706. this.initSocket(liveItem);
  1707. uni.showToast({
  1708. title: "连接未建立,正在重连",
  1709. icon: 'none'
  1710. });
  1711. return;
  1712. }
  1713. const data = {
  1714. liveId,
  1715. userId: this.userinfo.userId,
  1716. userType: 0,
  1717. cmd: "sendMsg",
  1718. msg: text,
  1719. nickName: this.userinfo.nickName,
  1720. avatar: this.userinfo.avatar
  1721. };
  1722. try {
  1723. socketItem.instance.send({
  1724. data: JSON.stringify(data),
  1725. success: () => {
  1726. // 比如找到最后一条 local 消息并标记为 sent
  1727. },
  1728. fail: (err) => {
  1729. console.error("发送失败:", err);
  1730. uni.showToast({
  1731. title: "发送失败,请重试",
  1732. icon: 'none'
  1733. });
  1734. // 可选择回滚本地显示(此处简单提示即可)
  1735. }
  1736. });
  1737. } catch (err) {
  1738. console.error('socket send 异常', err);
  1739. }
  1740. }
  1741. }
  1742. };
  1743. </script>
  1744. <style scoped lang="scss">
  1745. .swiper-wrapper {
  1746. position: relative;
  1747. width: 100%;
  1748. height: 100vh;
  1749. overflow: hidden;
  1750. background-color: #000000;
  1751. }
  1752. .swiper-container {
  1753. width: 100%;
  1754. height: 100vh;
  1755. }
  1756. .container {
  1757. width: 100%;
  1758. height: 100%;
  1759. position: relative;
  1760. // 添加渐变过渡效果
  1761. transition: opacity 0.3s ease;
  1762. &.active {
  1763. opacity: 1;
  1764. }
  1765. // 非活动项半透明显示
  1766. // &:not(.active) {
  1767. // opacity: 0.7;
  1768. // }
  1769. }
  1770. .loading-tip {
  1771. position: absolute;
  1772. top: 50%;
  1773. left: 50%;
  1774. transform: translate(-50%, -50%);
  1775. display: flex;
  1776. flex-direction: column;
  1777. align-items: center;
  1778. justify-content: center;
  1779. z-index: 10;
  1780. .loading-text {
  1781. color: #ffffff;
  1782. font-size: 28rpx;
  1783. margin-top: 20rpx;
  1784. }
  1785. }
  1786. .loading-more,
  1787. .no-more {
  1788. display: flex;
  1789. justify-content: center;
  1790. align-items: center;
  1791. padding: 20rpx 0;
  1792. color: #999;
  1793. font-size: 24rpx;
  1794. }
  1795. .loading-more {
  1796. flex-direction: column;
  1797. }
  1798. .preload-indicator {
  1799. position: absolute;
  1800. top: 50%;
  1801. right: 30rpx;
  1802. transform: translateY(-50%);
  1803. z-index: 100;
  1804. background: rgba(0, 0, 0, 0.5);
  1805. border-radius: 50%;
  1806. padding: 16rpx;
  1807. }
  1808. /* button自带样式清除 */
  1809. .student-orther-icon button::after {
  1810. border: none !important;
  1811. padding: 0 !important;
  1812. margin: 0 !important;
  1813. }
  1814. .student-orther-icon button {
  1815. background-color: transparent !important;
  1816. padding: 0 !important;
  1817. line-height: inherit !important;
  1818. margin: 0 !important;
  1819. width: auto !important;
  1820. font-weight: 500 !important;
  1821. border-radius: none !important;
  1822. }
  1823. .welcome-message {
  1824. position: fixed;
  1825. width: 100%;
  1826. bottom: 460rpx;
  1827. left: 50%;
  1828. transform: translateX(-50%);
  1829. color: white;
  1830. padding: 10px 20px;
  1831. border-radius: 20px;
  1832. // animation: fadeOut 1s ease 1s forwards;
  1833. z-index: 1000;
  1834. transition: opacity 0.3s ease;
  1835. }
  1836. @keyframes fadeOut {
  1837. from {
  1838. opacity: 1;
  1839. }
  1840. to {
  1841. opacity: 0;
  1842. }
  1843. }
  1844. .send {
  1845. background-color: #fafafa;
  1846. border-radius: 28rpx;
  1847. padding: 14rpx 16rpx;
  1848. color: #181818;
  1849. font-weight: 500;
  1850. }
  1851. // .container {
  1852. // position: relative;
  1853. // width: 100%;
  1854. // height: 100vh;
  1855. // overflow: hidden;
  1856. // }
  1857. // .talktext {
  1858. // border-radius: 8rpx;
  1859. // background-color: rgba(255, 255, 255, 0.1);
  1860. // view {
  1861. // width: 100%;
  1862. // }
  1863. // }
  1864. .talk-list {
  1865. border-radius: 30rpx;
  1866. background-color: rgba(33, 33, 33, 0.5);
  1867. padding: 10rpx 30rpx;
  1868. }
  1869. // .zoom-button-active {
  1870. // transform: scale(1.5);
  1871. // }
  1872. // .background-image {
  1873. // position: absolute;
  1874. // top: 0;
  1875. // left: -40rpx;
  1876. // width: 110%;
  1877. // height: 110%;
  1878. // object-fit: cover;
  1879. // filter: blur(20px);
  1880. // z-index: 0;
  1881. // }
  1882. // .background-images {
  1883. // position: absolute;
  1884. // top: 0;
  1885. // left: -40rpx;
  1886. // width: 110%;
  1887. // height: 110%;
  1888. // object-fit: cover;
  1889. // filter: blur(20px);
  1890. // z-index: 6;
  1891. // }
  1892. // .blackbg {
  1893. // position: absolute;
  1894. // top: 0;
  1895. // left: 0;
  1896. // width: 100%;
  1897. // height: 100%;
  1898. // background: rgba(0, 0, 0, 0.7);
  1899. // object-fit: cover;
  1900. // filter: blur(10px);
  1901. // z-index: 1;
  1902. // }
  1903. .content {
  1904. position: relative;
  1905. z-index: 2;
  1906. height: 100%;
  1907. width: 100%;
  1908. top: 0;
  1909. left: 0;
  1910. display: flex;
  1911. flex-direction: column;
  1912. justify-content: space-between;
  1913. .siderow-group {
  1914. position: absolute;
  1915. top: 65%;
  1916. right: 30rpx;
  1917. z-index: 9;
  1918. display: flex;
  1919. flex-direction: column;
  1920. align-items: center;
  1921. .side-item {
  1922. font-weight: 500;
  1923. font-size: 24rpx;
  1924. color: #FFFFFF;
  1925. margin-bottom: 32rpx;
  1926. text-align: center;
  1927. .button {
  1928. background-color: transparent;
  1929. margin: 0;
  1930. line-height: 1;
  1931. padding: 0;
  1932. }
  1933. .image {
  1934. width: 72rpx;
  1935. height: 72rpx;
  1936. }
  1937. }
  1938. }
  1939. .side-group {
  1940. position: absolute;
  1941. // top: 30%;
  1942. top: 65%;
  1943. right: 30rpx;
  1944. z-index: 9;
  1945. display: flex;
  1946. flex-direction: column;
  1947. align-items: center;
  1948. .side-item {
  1949. font-weight: 500;
  1950. font-size: 24rpx;
  1951. color: #FFFFFF;
  1952. margin-bottom: 32rpx;
  1953. text-align: center;
  1954. .button {
  1955. background-color: transparent;
  1956. margin: 0;
  1957. line-height: 1;
  1958. padding: 0;
  1959. }
  1960. .image {
  1961. width: 72rpx;
  1962. height: 72rpx;
  1963. }
  1964. }
  1965. }
  1966. .content-top {
  1967. width: 100%;
  1968. margin-top: 68rpx;
  1969. display: flex;
  1970. justify-content: space-between;
  1971. padding: 0 24rpx;
  1972. box-sizing: border-box;
  1973. .sum {
  1974. width: 80rpx;
  1975. height: 52rpx;
  1976. background: rgba(0, 0, 0, 0.5);
  1977. border-radius: 26rpx 26rpx 26rpx 26rpx;
  1978. font-size: 24rpx;
  1979. color: #FFFFFF;
  1980. text-align: center;
  1981. line-height: 52rpx;
  1982. }
  1983. }
  1984. .follow-btn {
  1985. padding: 8rpx 16rpx;
  1986. background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
  1987. border-radius: 26rpx;
  1988. font-weight: 500;
  1989. font-size: 26rpx;
  1990. color: #FFFFFF;
  1991. }
  1992. }
  1993. .videolist {
  1994. position: relative;
  1995. .video {
  1996. height: 100vh;
  1997. /* 占屏幕高度的80% */
  1998. width: 100%;
  1999. background-color: rgba(57, 57, 57, 0.4);
  2000. .time {
  2001. color: #ffffff;
  2002. font-size: 20rpx;
  2003. margin-left: 10rpx;
  2004. }
  2005. .videotop {
  2006. width: 100%;
  2007. height: 100%;
  2008. }
  2009. .video_row {
  2010. width: 100%;
  2011. max-height: 500rpx;
  2012. overflow: hidden;
  2013. margin-top: 360rpx;
  2014. }
  2015. }
  2016. }
  2017. .goods {
  2018. position: fixed;
  2019. // bottom: 160rpx;
  2020. // right: 10rpx;
  2021. top: 50%;
  2022. left: 50%;
  2023. transform: translate(-50%, -50%);
  2024. z-index: 5;
  2025. background-color: #fff;
  2026. border-radius: 20rpx;
  2027. overflow: hidden;
  2028. width: 300rpx;
  2029. // width: 220rpx;
  2030. padding: 4rpx;
  2031. .top {
  2032. position: absolute;
  2033. top: 4rpx;
  2034. display: flex;
  2035. justify-content: space-between;
  2036. align-items: center;
  2037. color: #fff;
  2038. width: 100%;
  2039. padding-right: 10rpx;
  2040. box-sizing: border-box;
  2041. .left {
  2042. background-color: rgba(0, 0, 0, 0.8);
  2043. padding: 10rpx;
  2044. font-size: 20rpx;
  2045. display: flex;
  2046. justify-content: space-between;
  2047. align-items: center;
  2048. border-radius: 10rpx;
  2049. }
  2050. }
  2051. .photo {
  2052. width: 100%;
  2053. height: 250rpx;
  2054. border-radius: 16rpx 16rpx 0 0;
  2055. overflow: hidden;
  2056. }
  2057. .item {
  2058. padding: 4rpx;
  2059. .price {
  2060. .red {
  2061. color: #FF5701;
  2062. font-weight: 600;
  2063. margin-right: 10rpx;
  2064. }
  2065. .del {
  2066. color: #828282;
  2067. font-weight: 500;
  2068. font-size: 24rpx;
  2069. text-decoration: line-through
  2070. }
  2071. }
  2072. .title {
  2073. font-weight: 500;
  2074. font-size: 26rpx;
  2075. margin: 10rpx 0 12rpx;
  2076. }
  2077. .button {
  2078. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  2079. color: #fff;
  2080. text-align: center;
  2081. padding: 16rpx 0;
  2082. border-radius: 10rpx;
  2083. font-weight: 500;
  2084. }
  2085. }
  2086. }
  2087. .icon {
  2088. font-weight: 500;
  2089. font-size: 24rpx;
  2090. color: #FFFFFF;
  2091. text-align: center;
  2092. margin-bottom: -10rpx;
  2093. .button {
  2094. background-color: transparent;
  2095. margin: 0;
  2096. line-height: 1;
  2097. padding: 0;
  2098. }
  2099. }
  2100. .icon-bg {
  2101. background-color: rgba(157, 157, 157, 0.8);
  2102. border-radius: 50%;
  2103. width: 72rpx;
  2104. height: 72rpx;
  2105. display: flex;
  2106. justify-content: center;
  2107. align-items: center;
  2108. transition: transform 0.2s ease;
  2109. .button {
  2110. background-color: transparent;
  2111. margin: 0;
  2112. line-height: 1;
  2113. padding: 0;
  2114. }
  2115. }
  2116. .list {
  2117. width: 80%;
  2118. margin-bottom: 20rpx;
  2119. animation: xxxawdawd .2s;
  2120. }
  2121. @keyframes xxxawdawd {
  2122. from {
  2123. margin-top: 0rpx;
  2124. opacity: 0;
  2125. }
  2126. to {
  2127. margin-top: 20rpx;
  2128. opacity: 1;
  2129. }
  2130. }
  2131. .shop-prompt {
  2132. position: absolute;
  2133. bottom: 600rpx;
  2134. left: 24rpx;
  2135. padding: 6rpx 20rpx;
  2136. background: rgba(230, 154, 34, 0.7);
  2137. border-radius: 24rpx;
  2138. z-index: 9;
  2139. font-weight: 500;
  2140. font-size: 26rpx;
  2141. color: #FFFFFF;
  2142. transition: opacity 0.3s ease;
  2143. }
  2144. .red-box {
  2145. .button {
  2146. margin: 0 auto;
  2147. width: 80%;
  2148. line-height: 88rpx;
  2149. height: 88rpx;
  2150. background: linear-gradient(90deg, #FF5701 0%, #FFB501 100%);
  2151. box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(238, 124, 80, 0.2);
  2152. border-radius: 44rpx 44rpx 44rpx 44rpx;
  2153. font-weight: 600;
  2154. font-size: 32rpx;
  2155. color: #FFFFFF;
  2156. text-align: center;
  2157. }
  2158. }
  2159. .view-box {
  2160. position: relative;
  2161. height: 40vh;
  2162. /* 设置弹出层高度为视窗高度的70% */
  2163. padding: 40rpx 0rpx 120rpx;
  2164. box-sizing: border-box;
  2165. display: flex;
  2166. flex-direction: column;
  2167. .scroll-content {
  2168. flex: 1;
  2169. overflow-y: auto;
  2170. padding: 0 40rpx;
  2171. }
  2172. .bottom {
  2173. padding: 20rpx 40rpx;
  2174. position: absolute;
  2175. bottom: 0;
  2176. width: 100%;
  2177. box-shadow: 0rpx -4rpx 10rpx 0rpx rgba(195, 195, 195, 0.3);
  2178. background: #fff;
  2179. }
  2180. }
  2181. .shoppop {
  2182. padding: 22rpx 16rpx;
  2183. .shoppop-top {
  2184. display: flex;
  2185. justify-content: space-between;
  2186. align-items: center;
  2187. padding: 0 16rpx 22rpx;
  2188. .search-input {
  2189. width: 414rpx;
  2190. height: 76rpx;
  2191. background: #FFFFFF;
  2192. border-radius: 36rpx;
  2193. margin-left: 20rpx;
  2194. padding: 0 32rpx;
  2195. box-sizing: border-box;
  2196. font-size: 24rpx;
  2197. margin-right: 24rpx;
  2198. }
  2199. .search-top {
  2200. font-size: 20rpx;
  2201. color: #222222;
  2202. }
  2203. }
  2204. .shop-list {
  2205. overflow: hidden;
  2206. .list-item {
  2207. display: flex;
  2208. align-items: center;
  2209. padding: 20rpx 16rpx;
  2210. background: #FFFFFF;
  2211. border-radius: 16rpx;
  2212. margin-bottom: 16rpx;
  2213. .goods-img {
  2214. width: 200rpx;
  2215. height: 200rpx;
  2216. border-radius: 16rpx;
  2217. overflow: hidden;
  2218. position: relative;
  2219. margin-right: 24rpx;
  2220. image {
  2221. width: 100%;
  2222. height: 100%;
  2223. }
  2224. .goods-label {
  2225. position: absolute;
  2226. top: 0;
  2227. width: 64rpx;
  2228. height: 40rpx;
  2229. background: rgba(0, 0, 0, 0.5);
  2230. border-radius: 16rpx 0rpx 16rpx 0rpx;
  2231. text-align: center;
  2232. font-weight: 500;
  2233. font-size: 28rpx;
  2234. color: #FFFFFF;
  2235. }
  2236. }
  2237. .goods-right {
  2238. flex: 1;
  2239. .goods-title {
  2240. font-weight: 500;
  2241. font-size: 28rpx;
  2242. color: #000000;
  2243. }
  2244. .goods-details {
  2245. font-size: 24rpx;
  2246. color: #999999;
  2247. margin: 10rpx 0 20rpx;
  2248. }
  2249. .goods-people {
  2250. font-size: 22rpx;
  2251. color: #E69A22;
  2252. height: 56rpx;
  2253. }
  2254. .goods-shop {
  2255. display: flex;
  2256. justify-content: space-between;
  2257. .nummber {
  2258. color: #FF5C03;
  2259. font-size: 22rpx;
  2260. font-weight: 500;
  2261. }
  2262. .btn-group {
  2263. text-align: center;
  2264. line-height: 56rpx;
  2265. .collect-btn {
  2266. width: 72rpx;
  2267. background: #F5F7FA;
  2268. border-radius: 8rpx 0rpx 0rpx 8rpx;
  2269. }
  2270. .shop-btn {
  2271. width: 152rpx;
  2272. background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
  2273. border-radius: 0rpx 8rpx 8rpx 0rpx;
  2274. font-weight: 500;
  2275. font-size: 26rpx;
  2276. color: #FFFFFF;
  2277. }
  2278. }
  2279. }
  2280. }
  2281. }
  2282. }
  2283. }
  2284. :deep(.u-list-item) {
  2285. width: 100%;
  2286. display: flex;
  2287. align-items: center;
  2288. }
  2289. :deep(.u-safe-area-inset-bottom) {
  2290. padding-bottom: 0
  2291. }
  2292. </style>