living.vue 68 KB

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