living.vue 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560
  1. <template>
  2. <view class="swiper-wrapper">
  3. <view class="container">
  4. <view class="content">
  5. <view style="position: fixed;top: 0;z-index: 5;" class="content-top">
  6. <view class="x-f">
  7. <image v-if="!scene" @click="goBack" class="w60 h64 mr26" src="/static/images/return3.png" />
  8. <view class="align-center"
  9. style="padding: 6rpx 8rpx;height: 64rpx;background: rgba(0,0,0,0.5);border-radius: 32rpx;">
  10. <u-avatar :src="liveItem.liveImgUrl||'/static/images/avatar.png'" :size="32"></u-avatar>
  11. <view class="colorf ml10 mr6">
  12. <view>{{liveItem.liveName?truncateString(liveItem.liveName,8):"未命名"}}</view>
  13. </view>
  14. </view>
  15. </view>
  16. <view v-if="Array.isArray(filteredViewers)" class=" align-center" @click="toggleViewerList"
  17. style="margin-top: 120rpx;">
  18. <view v-for="(item,viewerIndex) in filteredViewers" :key="viewerIndex">
  19. <image v-if="item.avatar" class="w52 h52 mr4" style="border-radius: 26rpx;"
  20. :src="item.avatar" />
  21. <view v-else class="w52 h52 mr4"
  22. :style="{backgroundColor: getUserRandomColor(item.userId), borderRadius:'50%'}">
  23. <text class="text-white text-xs">{{getNicknameInitial(item.nickName)}}</text>
  24. </view>
  25. </view>
  26. <view class="sum">{{liveUserTotal||0}}</view>
  27. </view>
  28. </view>
  29. <!-- 右边的side -->
  30. <view class="side-group">
  31. <view class="side-item" @click="onLike">
  32. <LikeButton :initialCount="100" :heartsPerClick="5" @like="onLike" />
  33. <view>{{liveViewData && liveViewData.like||0}}</view>
  34. </view>
  35. <view class="side-item">
  36. <button open-type="share" class="button">
  37. <image class="image" src="/static/images/weixin.png" mode="widthFix" />
  38. </button>
  39. <view>分享</view>
  40. </view>
  41. </view>
  42. <view class="activity-box">
  43. <view class="item-box" @click="onRed()" v-if="isShowRed">
  44. <view class="x-f">
  45. <view class="tip">领红包</view>
  46. <view class="item">
  47. <image class="w70 img" src="/static/images/redbag.png" mode="widthFix" />
  48. </view>
  49. </view>
  50. </view>
  51. <view class="item-box" @click="onLottery()" v-if="isShowLottery&&countdown">
  52. <view class="x-f">
  53. <view class="tip">抽奖</view>
  54. <view class="item">
  55. <image class="w60" src="/static/images/lottery.png" mode="widthFix" />
  56. </view>
  57. </view>
  58. </view>
  59. <!-- v-if="isShowCoupon" -->
  60. <!-- <view class="item-box" @click="isShowCoupon=true">
  61. <view class="x-f">
  62. <view class="tip">优惠券</view>
  63. <view class="item">
  64. <image class="w60" src="/static/images/coupon.png" mode="widthFix" />
  65. </view>
  66. </view>
  67. </view> -->
  68. </view>
  69. <view class="shop-prompt f30 x-f"
  70. v-if="showPurchasePrompt&&orderUser&&orderUser.count&&liveItem.status==2">
  71. <image class="w32 h32 mr8" src="/static/images/shopping.png" />
  72. <text>{{ orderUser.count || 0 }}人正在去购买</text>
  73. </view>
  74. <view class="videolist" v-if="liveItem.status==2">
  75. <view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
  76. <!-- 视频组件 -->
  77. <live-player v-if="liveItem.livingUrl && liveItem.liveType == 1" :id="'myLivePlayer_' + liveId"
  78. :src="liveItem.livingUrl" autoplay mode="live" object-fit="contain" :muted="false"
  79. orientation="vertical" :enable-play-gesture="true" min-cache="1" max-cache="3"
  80. @statechange="onLiveStateChange($event, liveItem)" @error="onLiveError($event, liveItem)"
  81. class="item"></live-player>
  82. <!-- 录播 -->
  83. <video v-if="liveItem.videoUrl&&liveItem.liveType==2" :id="`myVideo_${liveId}`" class="item"
  84. :src="liveItem.videoUrl" :controls="false" object-fit="contain" :custom-cache="false"
  85. :enable-progress-gesture="false" vslide-gesture-in-fullscreen="true"
  86. :show-center-play-btn="false" :http-cache="false" loop @error="videoError"
  87. @timeupdate="onVideoTimeUpdate" @loadeddata="onVideoLoaded"
  88. @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause" @play="onVideoPlay">
  89. </video>
  90. <!-- 直播回放 -->
  91. <video v-if="liveItem.videoUrl&&liveItem.liveType==3" :id="`myVideo_${liveId}`" class="item"
  92. :src="liveItem.videoUrl" :controls="true" object-fit="contain" :custom-cache="false"
  93. :enable-progress-gesture="liveItem.isSpeedAllowed" vslide-gesture-in-fullscreen="true"
  94. :show-center-play-btn="true" :http-cache="false" loop @error="videoError"
  95. @timeupdate="onVideoTimeUpdate" @loadeddata="onVideoLoaded"
  96. @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause" @play="onVideoPlay"
  97. @seek="onVideoSeek">
  98. </video>
  99. <view v-if="liveItem.videoUrl&&liveItem.liveType==2" class="time">{{liveItem.totalTime}}
  100. </view>
  101. <view v-if="liveItem.videoUrl&&liveItem.liveType==3" class="lable">直播回放</view>
  102. </view>
  103. </view>
  104. <view class="trailer-box" v-if="liveItem.status==1">
  105. <video v-if="liveItem.previewUrl" :id="`myVideo_${liveId}`" class="item" :src="liveItem.previewUrl"
  106. :autoplay="true" :controls="false" object-fit="contain" :custom-cache="false"
  107. :enable-progress-gesture="false" vslide-gesture-in-fullscreen="false"
  108. :show-center-play-btn="false" :http-cache="false" loop @error="videoError"
  109. @loadeddata="onVideoLoaded" @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause"
  110. @play="onVideoPlay" :disable-progress="true">
  111. </video>
  112. <image v-if="liveItem.status==1&&!liveItem.previewUrl" class="img" src="/static/images/no_live.png">
  113. </image>
  114. <view class="countdown-item mt30 mb30" v-if="liveItem.status==1&&liveCountdown">
  115. 开播倒计时
  116. <view class="x-f">
  117. <view class="white">
  118. {{liveCountdown.hours||"00"}}
  119. </view>
  120. <view class="white">
  121. {{ liveCountdown.minutes||"00"}}
  122. </view>
  123. <view class="white">
  124. {{ liveCountdown.seconds||"00" }}
  125. </view>
  126. </view>
  127. </view>
  128. <view class="name"> {{liveItem.liveName}}</view>
  129. <view class="title" v-if="liveCountdown">暂未开播</view>
  130. <view class="button" v-if="!isAgreement" @click="handleAgreement">预约直播</view>
  131. <view class="button ash" v-if="isAgreement">已预约</view>
  132. <view class="title" v-if="!liveCountdown">主播还在来的路上</view>
  133. </view>
  134. <view class="trailer-box" v-if="!liveItem">
  135. <image class="img" src="/static/images/no_live.png">
  136. </image>
  137. <view class="title">暂无直播</view>
  138. </view>
  139. <!-- 底部聊天区域 -->
  140. <view :style="{position: 'fixed',width: '100%',bottom: chatHeight + 'rpx',zIndex:999}">
  141. <view class="mt20" :style="{ height: chatHeight ? '64rpx' : '30vh' }">
  142. <scroll-view v-if="Array.isArray(talklist)" enable-flex scroll-y="true"
  143. class="pl20 scrolly flex-1 column" style="width: calc(100% - 20rpx); height: 100%;"
  144. :scroll-top="scrollTop" ref="scrollView">
  145. <!-- 聊天消息列表 -->
  146. <view class="list justify-start" v-for="(item,talkIndex) in (talklist||[])" :key="talkIndex"
  147. :id="`list_${talkIndex}`" v-show="item.cmd!='red'&&item.cmd!='out'&&item.cmd!='entry'">
  148. <view class="talk-list justify-start">
  149. <view class="fs30" style="max-width: 100%;">
  150. <text style="color: #FFDA73;">{{item.nickName||"未命名"}}:</text>
  151. <text class='colorf'>{{item.msg}}</text>
  152. </view>
  153. </view>
  154. </view>
  155. <!-- 欢迎消息 -->
  156. <view v-if="showWelcomeMessage" class="welcome-message" style="max-width: 100%;">
  157. <view class="list justify-start" v-show="inAndOut.cmd=='entry'||inAndOut.cmd=='out'">
  158. <view class="talk-list justify-start">
  159. <view class="fs30">
  160. <text style="color: #ff89d6;">{{inAndOut.nickName||"未命名"}} </text>
  161. <text class='colorf'>{{inAndOut.msg}}直播间</text>
  162. </view>
  163. </view>
  164. </view>
  165. </view>
  166. </scroll-view>
  167. </view>
  168. <!-- 底部输入框和操作按钮 -->
  169. <view class="justify-between p24">
  170. <view class="x-f"
  171. :style="{background:'#393939' ,padding: '10rpx 14rpx 10rpx 32rpx',boxSizing: 'border-box',borderRadius: '36rpx',width: isFocus ? '100%' : '580rpx'}">
  172. <u-input :placeholder="placeholderText" border="none" customStyle='font-size:24rpx;'
  173. v-model="value" shape='circle' color="#ffffff" placeholderStyle="color:#e7e7e7"
  174. :adjust-position="false" :scroll-with-animation="false" class="ml20" @focus="inputFocus"
  175. @blur="inputBlur">
  176. </u-input>
  177. <view class="send" @click="sendMsg()">发送</view>
  178. </view>
  179. <view class="justify-between mr15 align-center" v-if="!isFocus">
  180. <view class="icon-bg ml20" @click="openCart()">
  181. <image src="/static/images/shopping.png" class="w58 h58" />
  182. </view>
  183. </view>
  184. </view>
  185. </view>
  186. </view>
  187. <view class="goods" v-if="isShowGoods">
  188. <view class="top">
  189. <view class="left">
  190. <image class="w30 h30 mr8" src="/static/images/signal.png" />讲解中
  191. </view>
  192. <image @click="isShowGoods=false" class="w40 h40 " src="/static/images/del2.png" />
  193. </view>
  194. <image class="photo" :src="goodsCard.imgUrl" />
  195. <view class="item">
  196. <view class="price"><text class="red">¥{{goodsCard.price}} </text><text
  197. class="del">¥{{goodsCard.otPrice}}</text></view>
  198. <view class="title oneline-hide">{{goodsCard.productName}}</view>
  199. <view class="button" @click="goShop(goodsCard.productId,goodsCard.goodsId)">
  200. 立即抢购
  201. </view>
  202. </view>
  203. </view>
  204. <u-popup :show="isShowLotteryPop&&countdown" round='40rpx'>
  205. <view class="prize-box" style="border-radius: 40rpx;height: fit-content;">
  206. <image class="nav-img " src="/static/images/red_head.png" mode="widthFix" />
  207. <image class="bg-img " src="/static/images/red_bg.png" />
  208. <view class="prize-content">
  209. <view class=" mr20">
  210. <u-icon class="x-end" name="close" color="#fff" size="20"
  211. @click="isShowLotteryPop=false"></u-icon>
  212. </view>
  213. <view class="column align-center ">
  214. <image class="w446 h80" src="/static/images/red_title.png" />
  215. <view class="fs24 colorf x-f mt30 mb30">
  216. 开奖倒计时
  217. <view class="x-f">
  218. <view class="white-item">
  219. {{countdown.hours||"00"}}
  220. </view>
  221. <view class="white-item">
  222. {{ countdown.minutes||"00" }}
  223. </view>
  224. <view class="white-item">
  225. {{ countdown.seconds||"00" }}
  226. </view>
  227. </view>
  228. </view>
  229. <view class="item-group">
  230. <ThreeItemSwiper :products="lotteryProducts"></ThreeItemSwiper>
  231. </view>
  232. <view class="point-group" v-for="(item,index) in lotteryProducts" :key="index">
  233. </view>
  234. <view class="colorf fs28">
  235. 观看直播参与抽奖
  236. </view>
  237. <view class="button" @click="onClaim">参与抽奖</view>
  238. </view>
  239. </view>
  240. </view>
  241. </u-popup>
  242. <u-popup :show="!!integral.status" round='20rpx' mode="center" bgColor='#ffffff' zIndex='10076'>
  243. <view class="integral-box">
  244. <view class="top">
  245. <view class="title">观看视频领芳华币</view>
  246. <image class="photo" src="/static/images/integral_bg.png" mode="widthFix" />
  247. </view>
  248. <view class="item">
  249. <view class="title ">{{integral.msg}}</view>
  250. <view class="button" @click="integral.status=false">确认</view>
  251. </view>
  252. </view>
  253. </u-popup>
  254. <u-popup :show="isShowRedCard" round='20rpx' mode="center" bgColor='transparent' zIndex='10076'>
  255. <view class="red-card">
  256. <image class="img" src="/static/images/red_card.png" />
  257. <view class="red-content">
  258. <view class="title">{{redCard.msg}}</view>
  259. <view class="txt ">直播惊喜芳华币</view>
  260. <view class="button" @click="isShowRedCard=false">确认</view>
  261. </view>
  262. </view>
  263. </u-popup>
  264. <!-- 中奖和未中奖 -->
  265. <u-popup :show="isShowPrize" round='20rpx' mode="center" bgColor='#fff' zIndex='10076'>
  266. <view class="prize-card" v-if="isCurrentUserWon">
  267. <image class="nav-img " src="/static/images/red_head.png" mode="widthFix" />
  268. <view class="title">{{prizeInfo.length}}位幸运观众</view>
  269. <view class="prize-content" v-for="(item,index) in (prizeInfo||[])" :key="index">
  270. <view>{{item.userName}}</view>
  271. <view>{{item.userId}}</view>
  272. <view class="txt">{{item.prizeLevel}}等奖</view>
  273. </view>
  274. <view class="tip">请截图联系客服领取奖品</view>
  275. <view class="button" @click="isShowPrize=false">确认</view>
  276. </view>
  277. <view class="no-prize-card" v-else>
  278. <image class="img" src="/static/images/no-prize.png" mode="widthFix" />
  279. <view class="tip">很遗憾 您未中奖</view>
  280. <view class="button" @click="isShowPrize=false">确认</view>
  281. </view>
  282. </u-popup>
  283. <!-- 观众列表弹窗 -->
  284. <u-popup :show="showadd" @close="close" @open="openViews" round='20rpx' bgColor='#ffffff' zIndex='10077'>
  285. <view class="view-box">
  286. <view class="fs32" style="text-align: center;">在线观众</view>
  287. <scroll-view v-if="Array.isArray(liveViewers)" scroll-y class="scroll-content"
  288. :style="{height: scrollHeight + 'px'}" @scrolltolower="handleScrollToLower">
  289. <view class="fs28 x-f mb20 mt20" v-for="(item,index) in (liveViewers||[])" :key="index">
  290. <view
  291. :style="{color: index === 0 ? '#FF3B30' : index === 1 ? '#FF9500' : index === 2 ? '#FFCC00' : '#8E8E93',fontWeight: index < 3 ? 'bold' : 'normal',width: '50rpx'}"
  292. class="mr10">{{index+1}}</view>
  293. <u-avatar v-if="item.avatar" :src="item.avatar" :size="36"></u-avatar>
  294. <view v-else class="w72 h72"
  295. :style="{backgroundColor: getUserRandomColor(item.userId), borderRadius:'50%'}">
  296. <text class="text-white text-xs">{{getNicknameInitial(item.nickName)}}</text>
  297. </view>
  298. <text class="ml16 f30">{{item.nickName||"未命名"}}</text>
  299. </view>
  300. </scroll-view>
  301. </view>
  302. </u-popup>
  303. <!-- 商品弹窗 -->
  304. <u-popup :show="shopping" @close="closeShop" round='20rpx' bgColor='#f3f5f9' zIndex='10075'>
  305. <view class="shoppop">
  306. <view class="shoppop-top">
  307. <view class="search-input x-f">
  308. <image class="w24 mr16" src="/static/images/search.png" mode="widthFix" />
  309. <input placeholder="请搜索商品" v-model="inputInfo" @input="handleSearchInput" />
  310. </view>
  311. <view class=" search-top" @click="goOrderList()">
  312. <image class="w48 h48" src="/static/images/order.png" />
  313. <view>订单</view>
  314. </view>
  315. </view>
  316. <scroll-view enable-flex scroll-y class="shop-list" :style="{ height: boxHeight + 'px' }">
  317. <view class="list-item" v-for="(item,index) in products" :key="index">
  318. <view class="goods-img">
  319. <image class="img" :src="item.imgUrl" mode="widthFix" />
  320. <view class="goods-label">{{index+1}}</view>
  321. </view>
  322. <view class="goods-right">
  323. <view class="goods-title">{{item.productName}}</view>
  324. <view class="goods-people">{{item.sales}} 人已购</view>
  325. <view class="goods-shop">
  326. <text class="nummber"><text style="font-size: 20rpx;font-weight: 600;">¥</text><text
  327. style="font-size: 36rpx;font-weight: bold;">{{Math.trunc(item.price)}}</text>.{{getPureDecimal(item.price)?getPureDecimal(item.price):'00'}}</text>
  328. <view class="btn-group x-f">
  329. <view class="collect-btn">
  330. <image v-if="item.isFavorite" @click="onGoodsCollect(item)" class="w36 h36"
  331. style="vertical-align: middle;"
  332. src="/static/images/collect_select.png" />
  333. <image v-else @click="onGoodsCollect(item)" class="w36 h36"
  334. style="vertical-align: middle;" src="/static/images/collect.png" />
  335. </view>
  336. <view v-if="item.status==1" class="shop-btn"
  337. @click="goShop(item.productId,item.goodsId)">去购买 </view>
  338. <view v-else-if="item.status==0" class="shop-btn">
  339. 已下架</view>
  340. </view>
  341. </view>
  342. </view>
  343. </view>
  344. </scroll-view>
  345. </view>
  346. </u-popup>
  347. <!-- 优惠券弹窗 -->
  348. <view class="coupon-pop" v-if="isShowCoupon">
  349. <view class="coupon-block">
  350. <image class="bg" src="/static/images/coupon_bg.png" />
  351. <image class="nav" src="/static/images/coupon_top.png" />
  352. <image @click="isShowCoupon=false" class="w40 h40 close" src="/static/images/close1.png" />
  353. <view class="item">
  354. <view class="title">{{couponInfo.couponName}}</view>
  355. <view class="price">¥<text class="bold">{{couponInfo.couponPrice}}</text></view>
  356. <view class="txt">满{{couponInfo.useMinPrice}}元可用</view>
  357. <view class="txt" style="margin-top: 26rpx;">指定商品可用</view>
  358. <view class="txt">自领取起{{couponInfo.couponTime}}天内有效</view>
  359. <view class="button" @click="onCoupon()">
  360. 立即领券
  361. </view>
  362. </view>
  363. </view>
  364. </view>
  365. </view>
  366. </view>
  367. </template>
  368. <script>
  369. import LikeButton from '@/pages_course/components/like.vue'
  370. import ThreeItemSwiper from '@/pages_course/components/ThreeItemSwiper.vue'
  371. import CryptoJS from 'crypto-js'
  372. import {
  373. coupon, //领取优惠券
  374. liveLottery, // 抽奖查询
  375. claim, //抽奖
  376. liveRed, // 点击领红包
  377. liveDataLike, // 点赞
  378. collectStore, // 店铺收藏/取消收藏
  379. collectGoods, // 商品收藏/取消收藏
  380. watchUserList, //获取直播间用户(展示在线用户)
  381. liveMsg, //获取最近聊天记录
  382. // 小黄车
  383. liveStore, //店铺展示,
  384. liveOrderUser, //正在购买
  385. getLiveInfo, //获取直播间信息接口
  386. getLiveViewData, //直播间点赞、关注、在线人数数据
  387. currentActivities, //红包 卡片 抽奖
  388. getlive,
  389. subNotifyLive,
  390. internetTraffic // 流量(缓冲百分比)
  391. } from '@/api/living.js'
  392. import {
  393. getUserInfo
  394. } from '@/api/user'
  395. import {
  396. generateRandomString
  397. } from "@/utils/common.js"
  398. import dayjs from 'dayjs';
  399. import {
  400. nextTick
  401. } from "vue"
  402. // var wsUrl = "wss://live.test.ylrztop.com/ws/live-api/app/webSocket"; //余红奇
  403. // var pingpangTimes = null;
  404. // var initTimes = null;
  405. var isSocketOpen = false;
  406. var socket = null;
  407. export default {
  408. components: {
  409. ThreeItemSwiper,
  410. LikeButton
  411. },
  412. data() {
  413. return {
  414. stayTime: 0,
  415. startTime: 0,
  416. scrollTop: 0,
  417. isOnload: false,
  418. isConnecting: false, // 是否正在连接中
  419. previousToken: null,
  420. hasInitialized: false,
  421. couponsList: [],
  422. liveViewersData: [],
  423. liveUserCalled: false, //调用过watchUserList没
  424. liveViewDataTimer: null,
  425. userRandomColors: {}, // 缓存用户ID -> 随机色的映射
  426. randomColor: '#8978e2',
  427. heartBeatRetryCount: 0, // 心跳发送重试次数(避免一次失败就重连)
  428. maxHeartBeatRetries: 2, // 心跳最大重试次数
  429. pingTimeout: 20000, // 心跳超时时间从10s延长到20s(应对网络波动)
  430. shownEntryUsers: new Set(), // 存储已显示过「进入提示」的用户ID
  431. isPageUnloading: false, // 标记页面是否正在卸载(区分主动离开vs重连out)
  432. templateId: 'fxYJu817lxHNKXl0hJypb54UnGRCNAoI72Qf-xjKCik',
  433. isAgreement: false,
  434. socket: null, // WebSocket 实例
  435. isSocketOpen: false, // 连接是否已打开
  436. heartBeatTimer: null, // 心跳定时器
  437. heartBeatInterval: 15000, // 心跳发送间隔(15秒)
  438. reconnectTimer: null, // 重连定时器
  439. reconnectCount: 0, // 当前重连次数
  440. maxReconnectAttempts: 3, // 最大重连次数
  441. isManualClose: false, // 是否手动关闭(用于区分主动关闭和异常断开)
  442. pingTimeoutTimer: null, // 心跳超时定时器
  443. // wsNewUrl: 'wss://api.fhhx.runtzh.com/app/webSocket',
  444. wsNewUrl: 'wss://api.fhhx.runtzh.com/ws/app/webSocket',
  445. // wsNewUrl: 'ws://192.168.10.166:7114/ws/app/webSocket',
  446. // wsNewUrl:'ws://192.168.10.166:7014/app/webSocket',
  447. qrFrom: null,
  448. scene: '',
  449. liveCountdown: {}, //直播倒计时
  450. countdown: {}, //抽奖倒计时
  451. liveViewData: {},
  452. chatHeight: 0,
  453. keyboardHeight: 0,
  454. videoCurrentTime: 0, // 当前视频播放时间
  455. isVideoPlaying: false, // 视频是否正在播放
  456. videoProgressKey: '', // 存储进度的key
  457. inAndOut: {},
  458. isShowPrize: false,
  459. isShowCoupon: false,
  460. prizeInfo: [],
  461. timeData: {},
  462. countDownKey: 0,
  463. lotteryProducts: [],
  464. lotteryList: [],
  465. talklist: [],
  466. isShowLotteryPop: false,
  467. liveItem: {},
  468. isSending: false,
  469. welcomeTimer: null,
  470. redTimer: null,
  471. liveStartTimer: null,
  472. lotteryTimer: null,
  473. isShowLottery: false,
  474. isShowRedCard: false,
  475. redCard: null, //点击红包出现弹窗
  476. integral: {},
  477. lotteryInfo: {},
  478. goodsCard: {},
  479. couponInfo: {},
  480. redInfo: {},
  481. storeId: null,
  482. isFocus: false,
  483. shopping: false,
  484. inputInfo: '',
  485. showWelcomeMessage: false,
  486. scrollIntoView: '',
  487. isShowGoods: false,
  488. isShowRed: false,
  489. lastClickTime: 0,
  490. clickDelay: 300, // 300ms内只响应一次点击
  491. videoRetryCounts: {}, // 记录每个直播间的视频重试次数,格式: { liveId: 次数 }
  492. placeholderText: '说点什么...',
  493. liveUserTotal: 0,
  494. viewPageSize: 10, // 每页数量
  495. viewPageNum: 1, // 当前页码
  496. viewLoading: false, // 是否正在加载
  497. scrollHeight: 0,
  498. scrollTimer: null, // 滚动防抖定时器
  499. showRed: true,
  500. searchTimer: null,
  501. isCollect: false,
  502. showPurchasePrompt: false,
  503. purchasePromptTimer: null,
  504. prevOrderCount: 0, // 用于记录上一次的购买人数
  505. videoUrl: null,
  506. showType: 1, //横屏1 竖屏2
  507. boxHeight: 300, //小黄车高度
  508. liveViewers: [], //观众
  509. likeName: 0,
  510. hlsPlayer: null, // HLS播放器实例,
  511. livingUrl: "",
  512. products: [],
  513. store: {},
  514. orderUser: {}, //正在购买
  515. userType: 0,
  516. timestamp: '',
  517. liveId: null,
  518. userinfo: '', //用户信息
  519. // path: 'http://192.168.10.166/dev-api', //余红奇
  520. // path: 'http://v56c9b8e.natappfree.cc', //余红奇
  521. // path: 'live.test.ylrztop.com/prod-api', //余红奇
  522. value: '',
  523. talkdisabled: false, //输入框是否禁用
  524. autoplay: false, //视频自动播放
  525. showadd: false,
  526. videoContext: '',
  527. livedata: {}, //直播间点赞、关注、在线人数数据
  528. userData: {},
  529. //流量
  530. uuId: "",
  531. };
  532. },
  533. onLoad(options) {
  534. if (options.liveId) {
  535. this.liveId = options.liveId;
  536. }
  537. this.getUserInfo()
  538. this.previousToken = uni.getStorageSync('AppToken')
  539. this.initTime();
  540. this.userinfo = uni.getStorageSync("userInfo")
  541. this.userData = uni.getStorageSync("userData")
  542. console.log("全部参数", options)
  543. //获取键盘高度
  544. this.keyboardListener = uni.onKeyboardHeightChange(res => {
  545. console.log('键盘高度', res.height);
  546. this.keyboardHeight = res.height * 2;
  547. });
  548. // 扫码传来的参数
  549. if (options.scene) {
  550. this.scene = options.scene;
  551. const decodedScene = decodeURIComponent(this.scene);
  552. const params = {};
  553. decodedScene.split('&').forEach(item => {
  554. const [key, value] = item.split('=');
  555. params[key] = value;
  556. this.liveId = params.a;
  557. })
  558. if (params.b && params.c) {
  559. this.qrFrom = `&companyId=${params.b}&companyUserId=${params.c}`;
  560. }
  561. }
  562. if (options.companyId && options.companyUserId) {
  563. this.qrFrom = `&companyId=${options.companyId}&companyUserId=${options.companyUserId}`;
  564. }
  565. // 初始化直播间列表
  566. this.$nextTick(() => {
  567. if (this.liveId) {
  568. this.getliving(this.liveId);
  569. this.isOnload = true
  570. } else {
  571. console.error("直播间 ID(liveId)未获取到");
  572. }
  573. })
  574. // if (!this.previousToken) {
  575. // console.log("未检测到AppToken,跳转到登录页");
  576. // // let backUrl = '/pages_course/living?liveId=' + (this.liveId || '');
  577. // uni.navigateTo({
  578. // url: '/pages/auth/login?&isLive=ture'
  579. // });
  580. // return;
  581. // }
  582. },
  583. onPullDownRefresh() {
  584. this.getLiveMsg(this.liveId)
  585. this.getliveUser()
  586. setTimeout(() => {
  587. uni.stopPullDownRefresh()
  588. }, 1000)
  589. },
  590. async onShow() {
  591. if (this.liveId && !this.isOnload) {
  592. await this.getLiveMsg(this.liveItem);
  593. }
  594. if (!this.userData) {
  595. await this.getUserInfo()
  596. }
  597. this.uuId = generateRandomString(16)
  598. const currentToken = await uni.getStorageSync('AppToken')
  599. console.log("token在这里", currentToken)
  600. const isLiveLogin = uni.getStorageSync('isLiveLogin')
  601. this.share = uni.getStorageSync('share')
  602. this.scene = uni.getStorageSync('scene')
  603. console.log("onshow分享", this.share)
  604. console.log("onshow扫码", this.scene)
  605. if (this.share && this.share.length > 0) {
  606. this.liveId = this.share.liveId
  607. this.qrFrom = `&companyId=${this.share.companyId}&companyUserId=${this.share.companyUserId}`;
  608. uni.removeStorageSync('share')
  609. }
  610. if (this.scene) {
  611. console.log("有扫码")
  612. const decodedScene = decodeURIComponent(this.scene);
  613. console.log("有扫码decodedScene", decodedScene)
  614. const params = {};
  615. decodedScene.split('&').forEach(item => {
  616. const [key, value] = item.split('=');
  617. params[key] = value;
  618. console.log("扫码参数", params)
  619. this.liveId = params.a;
  620. })
  621. if (params.b && params.c) {
  622. this.qrFrom = `&companyId=${params.b}&companyUserId=${params.c}`;
  623. }
  624. uni.removeStorageSync('scene')
  625. }
  626. if (isLiveLogin) {
  627. console.log("登录了")
  628. if (this.liveId) {
  629. await this.getliving(this.liveId)
  630. this.getCurrentActivities()
  631. this.getliveOrder()
  632. this.initSocket()
  633. }
  634. this.hasInitialized = true
  635. uni.removeStorageSync('isLiveLogin');
  636. }
  637. // 恢复播放和连接
  638. await this.resumePageActivity()
  639. this.userinfo = JSON.parse(uni.getStorageSync("userInfo"))
  640. // this.userData =await uni.getStorageSync("userData")
  641. this.isAgreement = uni.getStorageSync('isAgreement')
  642. this.previousToken = currentToken
  643. this.randomColor = this.getRandomHexColor()
  644. this.$nextTick(() => {
  645. this.setVideoProgress();
  646. });
  647. console.log("预约liveiD", this.liveId)
  648. if (this.lookTimer) {
  649. clearInterval(this.lookTimer)
  650. this.lookTimer = null;
  651. this.stayTime = 0;
  652. this.startTime = 0;
  653. }
  654. this.startTimer()
  655. },
  656. //分享给好友
  657. onShareAppMessage() {
  658. return {
  659. title: '邀请你来观看直播:' + this.liveItem.liveName,
  660. path: '/pages_course/living?companyId=-2&companyUserId=' + this.userData.userId + '&liveId=' + this.liveId,
  661. imageUrl: '/static/images/logo.png',
  662. success(res) {
  663. console.log("分享成功", res);
  664. },
  665. fail(err) {
  666. console.error("分享失败", err);
  667. }
  668. };
  669. },
  670. computed: {
  671. filteredViewers() {
  672. // 1. 强制兜底:若 liveViewers 不是数组(如 null/undefined),直接返回空数组
  673. const safeLiveViewers = Array.isArray(this.liveViewersData) ? this.liveViewersData : [];
  674. // 2. 截取前3项(空数组 slice 不会报错)
  675. return safeLiveViewers.slice(0, 3);
  676. },
  677. isCurrentUserWon() {
  678. // 兜底条件:确保prizeInfo是数组、当前用户ID存在
  679. if (!Array.isArray(this.prizeInfo) || !this.userData?.userId) {
  680. return false;
  681. }
  682. // 匹配逻辑:检查prizeInfo中是否有userId与当前用户一致的项
  683. return this.prizeInfo.some(item => {
  684. // 兼容item.userId可能是数字/字符串的情况,统一转为字符串比较
  685. return String(item.userId) === String(this.userData.userId);
  686. });
  687. }
  688. },
  689. onHide() {
  690. },
  691. onUnload() {
  692. this.suspendPageActivity()
  693. this.liveUserCalled = false
  694. // if (this.liveItem) {
  695. // this.pauseVideo();
  696. // this.clearTimeTimer();
  697. // }
  698. this.loadUserColorsFromStorage();
  699. if (this.liveViewDataTimer) {
  700. clearInterval(this.liveViewDataTimer);
  701. this.liveViewDataTimer = null;
  702. }
  703. // console.log('页面卸载,清理资源');
  704. this.isPageUnloading = true; // 标记为主动离开
  705. // 1. 先关闭WebSocket
  706. this.closeWebSocket(true);
  707. // 2. 清除所有定时器
  708. this.clearAllTimers();
  709. // 3. 暂停视频
  710. const videoId = `myVideo_${this.liveId}`;
  711. const videoContext = uni.createVideoContext(videoId, this);
  712. if (videoContext) {
  713. videoContext.pause();
  714. }
  715. // 4. 移除事件监听
  716. // 5. 清除特定定时器
  717. if (this.redTimer) {
  718. clearInterval(this.redTimer);
  719. this.redTimer = null;
  720. }
  721. if (this.liveStartTimer) {
  722. clearInterval(this.liveStartTimer);
  723. this.liveStartTimer = null;
  724. }
  725. if (this.lotteryTimer) {
  726. clearInterval(this.lotteryTimer);
  727. this.lotteryTimer = null;
  728. }
  729. if (this.welcomeTimer) {
  730. clearInterval(this.welcomeTimer);
  731. this.welcomeTimer = null;
  732. }
  733. if (this.trafficInterval != null) {
  734. clearInterval(this.trafficInterval)
  735. }
  736. if (this.lookTimer) {
  737. clearInterval(this.lookTimer)
  738. this.lookTimer = null;
  739. this.stayTime = 0;
  740. this.startTime = 0;
  741. }
  742. },
  743. mounted() {
  744. this.getCurrentActivities();
  745. this.getliveOrder()
  746. },
  747. watch: {
  748. // 新增:监听liveItem.status的变化
  749. 'liveItem.status': {
  750. // status变化时执行的逻辑
  751. handler(newStatus, oldStatus) {
  752. // 1. 过滤无效场景:避免初始值/空值触发无效请求
  753. if (newStatus === undefined || oldStatus === undefined) return;
  754. // 2. 过滤相同状态:仅当状态真的变化时才请求(避免重复调用)
  755. if (newStatus === oldStatus) return;
  756. // 3. 确保liveId存在(getliving依赖liveId)
  757. if (!this.liveId) {
  758. console.warn("liveId不存在,无法触发getliving请求");
  759. return;
  760. }
  761. // 4. 状态变化时,调用getliving更新直播间数据
  762. console.log(`liveItem.status从${oldStatus}变为${newStatus},触发getliving请求`);
  763. this.getliving(this.liveId);
  764. },
  765. deep: true,
  766. // immediate: true(若需页面初始化时就触发一次,根据需求决定是否开启)
  767. },
  768. // 监听orderUser.count的变化
  769. 'orderUser.count': {
  770. handler(newVal, oldVal) {
  771. if (newVal !== this.prevOrderCount) {
  772. this.prevOrderCount = newVal;
  773. this.showPurchaseMessage();
  774. }
  775. },
  776. immediate: true
  777. }
  778. },
  779. methods: {
  780. startTimer() {
  781. this.startTime = Date.now()
  782. this.lookTimer = setInterval(() => {
  783. this.stayTime = Math.floor((Date.now() - this.startTime) / 1000)
  784. }, 1000)
  785. },
  786. // 缓冲
  787. getInternetTraffic() {
  788. console.log("流量>>>>")
  789. // if(!this.liveId) return
  790. // const playVideoTime = Math.ceil(this.playTime / this.duration * 100) // 播放百分比
  791. // if(this.bufferRate == 0 || this.bufferRate < playVideoTime) {
  792. // this.bufferRate = playVideoTime
  793. // }
  794. // if(this.bufferRate == 0 || Number(this.bufferRate.toFixed(2)) == 0) return
  795. const currentTime = this.stayTime / this.liveItem.duration * 100;
  796. console.log("currentTime是什么", currentTime)
  797. const param = {
  798. companyId: this.companyId || '',
  799. companyUserId: this.companyUserId || '',
  800. userId: this.userData.userId || '',
  801. liveId: this.liveId || '',
  802. videoType: this.liveItem.videoType,
  803. videoId: this.liveItem.videoId,
  804. uuId: dayjs().format('YYYYMMDD') + this.uuId,
  805. duration: this.liveItem.duration,
  806. bufferRate: currentTime,
  807. }
  808. // if(!param.bufferRate) return
  809. // internetTraffic(param)
  810. console.log("流量1>>>>")
  811. internetTraffic(param).then(res => {
  812. if (res.code == 200) {
  813. console.log("流量成功>>>>", res)
  814. }
  815. }).catch(error => {
  816. console.error("流量失败:", error);
  817. });
  818. },
  819. scrollToBottom() {
  820. this.$nextTick(() => {
  821. setTimeout(() => {
  822. const query = uni.createSelectorQuery().in(this);
  823. // 获取 scroll-view 和内容的高度
  824. query.select('.scrolly').boundingClientRect(scrollRect => {
  825. query.select('.scrolly').scrollOffset(scrollOffset => {
  826. // 计算新的滚动位置
  827. const newScrollTop = scrollOffset.scrollHeight - scrollRect
  828. .height;
  829. this.scrollTop = newScrollTop;
  830. }).exec();
  831. }).exec();
  832. }, 100);
  833. });
  834. },
  835. // 恢复页面活动
  836. async resumePageActivity() {
  837. console.log("恢复了")
  838. if (this.liveItem) {
  839. this.playVideo()
  840. this.startTimeTimer(this.liveItem)
  841. }
  842. if (!this.isSocketAvailable()) {
  843. this.initSocket()
  844. }
  845. },
  846. // 暂停页面活动
  847. suspendPageActivity() {
  848. this.stopHeartBeat()
  849. this.saveVideoProgress()
  850. if (this.liveItem) {
  851. this.pauseVideo()
  852. this.clearTimeTimer()
  853. }
  854. },
  855. // 获取用户专属随机色(缓存机制:同一用户始终用同一颜色)
  856. getUserRandomColor(userId) {
  857. if (!userId) {
  858. return '#8978e2'; // 默认颜色
  859. }
  860. //如果缓存中已有该用户的颜色,直接返回
  861. if (this.userRandomColors[userId]) {
  862. return this.userRandomColors[userId];
  863. }
  864. //为新用户生成固定颜色(基于用户ID生成,不是完全随机)
  865. const color = this.generateStableColor(userId);
  866. this.userRandomColors[userId] = color;
  867. // 存储到本地缓存,确保页面刷新后颜色不变
  868. this.saveUserColorsToStorage();
  869. return color;
  870. }, // 基于用户ID生成稳定颜色(不是完全随机)
  871. generateStableColor(userId) {
  872. // 将用户ID转换为数字种子
  873. let seed = 0;
  874. for (let i = 0; i < userId.length; i++) {
  875. seed = (seed * 31 + userId.charCodeAt(i)) % 1000000;
  876. }
  877. const colorPool = [
  878. '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
  879. '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9',
  880. '#F8C471', '#82E0AA', '#F1948A', '#85C1E9', '#D7BDE2'
  881. ];
  882. return colorPool[seed % colorPool.length];
  883. }, // 保存颜色映射到本地存储
  884. saveUserColorsToStorage() {
  885. try {
  886. uni.setStorageSync('userRandomColors', this.userRandomColors);
  887. } catch (e) {
  888. console.warn('保存用户颜色缓存失败:', e);
  889. }
  890. },
  891. // 从本地存储加载颜色映射
  892. loadUserColorsFromStorage() {
  893. try {
  894. const cached = uni.getStorageSync('userRandomColors');
  895. if (cached) {
  896. this.userRandomColors = cached;
  897. }
  898. } catch (e) {
  899. console.warn('加载用户颜色缓存失败:', e);
  900. }
  901. },
  902. //头像名字
  903. getNicknameInitial(nickName) {
  904. if (!nickName || typeof nickName !== 'string') return '未';
  905. if (/^[\u4e00-\u9fa5]/.test(nickName[0])) {
  906. return nickName[0];
  907. }
  908. return nickName[0].toUpperCase();
  909. },
  910. // 引入前面的随机颜色方法
  911. getRandomHexColor() {
  912. const getValidValue = () => Math.floor(Math.random() * 130) + 100;
  913. const red = getValidValue().toString(16).padStart(2, '0');
  914. const green = getValidValue().toString(16).padStart(2, '0');
  915. const blue = getValidValue().toString(16).padStart(2, '0');
  916. return `#${red}${green}${blue}`;
  917. },
  918. async getUserInfo() {
  919. await getUserInfo().then(
  920. res => {
  921. if (res.code == 200) {
  922. console.log("用户信息>>", res)
  923. this.userData = res.user;
  924. } else {
  925. uni.showToast({
  926. icon: 'none',
  927. title: "请求失败",
  928. });
  929. }
  930. },
  931. rej => {}
  932. );
  933. }, // 检查WebSocket连接状态
  934. getSocketState() {
  935. if (!this.socket) return 'CLOSED';
  936. const states = {
  937. 0: 'CONNECTING',
  938. 1: 'OPEN',
  939. 2: 'CLOSING',
  940. 3: 'CLOSED'
  941. };
  942. return states[this.socket.readyState] || 'UNKNOWN';
  943. },
  944. // 在控制台输出连接状态(调试用)
  945. logSocketState() {
  946. console.log('WebSocket状态:', {
  947. socket: !!this.socket,
  948. isSocketOpen: this.isSocketOpen,
  949. readyState: this.getSocketState(),
  950. reconnectCount: this.reconnectCount
  951. });
  952. },
  953. handleAgreement() {
  954. const templateId = this.templateId; // 先保存到局部变量
  955. uni.requestSubscribeMessage({
  956. tmplIds: [templateId],
  957. success: (res) => { // 使用箭头函数保持this指向
  958. console.log("订阅结果", res);
  959. console.log("模板订阅状态", res[templateId]);
  960. if (res[templateId] === "accept") {
  961. uni.showToast({
  962. title: '订阅成功,开播将提醒您',
  963. icon: 'success'
  964. });
  965. this.callSendMessageApi()
  966. } else if (res[templateId] === 'reject') {
  967. uni.showToast({
  968. title: '您已拒绝订阅,将无法收到提醒',
  969. icon: 'none'
  970. });
  971. } else if (res[templateId] === 'ban') {
  972. uni.showToast({
  973. title: '您已关闭所有订阅权限,请在设置中开启',
  974. icon: 'none'
  975. });
  976. }
  977. },
  978. fail: (err) => {
  979. console.error('订阅消息失败', err);
  980. uni.showToast({
  981. title: '订阅失败,请重试',
  982. icon: 'none'
  983. });
  984. }
  985. });
  986. },
  987. // 调用后端发送订阅消息的接口
  988. async callSendMessageApi() {
  989. if (!this.userData.userId) return;
  990. console.log("订阅在这里", this.userData.userId)
  991. const templateData = {
  992. taskName: this.liveId,
  993. userId: this.userData.userId,
  994. templateId: this.templateId, // 你的模板ID
  995. data: {
  996. thing6: this.liveItem.liveName,
  997. date7: this.liveItem.startTime,
  998. }
  999. };
  1000. // 调用后端接口(后端负责调用微信订阅消息发送接口)
  1001. subNotifyLive(templateData).then(res => {
  1002. if (res.code == 200) {
  1003. this.isAgreement = true;
  1004. uni.setStorageSync('isAgreement', true);
  1005. console.log("订阅消息", res)
  1006. } else {
  1007. uni.showToast({
  1008. title: res.msg,
  1009. icon: 'none'
  1010. });
  1011. }
  1012. },
  1013. rej => {}
  1014. );
  1015. },
  1016. sendHeartBeat() {
  1017. if (!this.isSocketAvailable()) return;
  1018. try {
  1019. const heartBeatMsg = JSON.stringify({
  1020. cmd: "heartbeat",
  1021. msg: "ping",
  1022. userId: this.userData.userId || '',
  1023. liveId: this.liveId
  1024. });
  1025. this.socket.send({
  1026. data: heartBeatMsg,
  1027. success: () => {
  1028. this.heartBeatRetryCount = 0; // 成功后重置重试次数
  1029. this.startPingTimeout(); // 启动超时检测
  1030. },
  1031. fail: (err) => {
  1032. console.error("心跳包发送失败:", err);
  1033. this.heartBeatRetryCount++;
  1034. // 心跳失败先重试,重试次数用完再重连
  1035. if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
  1036. setTimeout(() => this.sendHeartBeat(), 2000); // 2秒后重试
  1037. } else {
  1038. this.heartBeatRetryCount = 0;
  1039. this.handleReconnect(); // 重试用完才重连
  1040. }
  1041. }
  1042. });
  1043. } catch (err) {
  1044. console.error("心跳发送异常:", err);
  1045. this.heartBeatRetryCount++;
  1046. if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
  1047. setTimeout(() => this.sendHeartBeat(), 2000);
  1048. } else {
  1049. this.heartBeatRetryCount = 0;
  1050. this.handleReconnect();
  1051. }
  1052. }
  1053. }, // 启动心跳超时检测
  1054. startPingTimeout() {
  1055. // 清除之前的超时定时器
  1056. if (this.pingTimeoutTimer) {
  1057. clearTimeout(this.pingTimeoutTimer);
  1058. this.pingTimeoutTimer = null;
  1059. }
  1060. // 超时后触发重连
  1061. this.pingTimeoutTimer = setTimeout(() => {
  1062. // console.error("心跳响应超时,连接异常");
  1063. this.handleReconnect();
  1064. }, this.pingTimeout);
  1065. },
  1066. stopHeartBeat() {
  1067. if (this.heartBeatTimer) {
  1068. clearInterval(this.heartBeatTimer);
  1069. this.heartBeatTimer = null;
  1070. }
  1071. if (this.pingTimeoutTimer) {
  1072. clearTimeout(this.pingTimeoutTimer);
  1073. this.pingTimeoutTimer = null;
  1074. }
  1075. }, // 封装通用的连接状态校验方法
  1076. isSocketAvailable() {
  1077. // WebSocket readyState:0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED
  1078. return this.socket && this.isSocketOpen && this.socket.readyState === 1;
  1079. },
  1080. // 处理重连逻辑
  1081. handleReconnect() {
  1082. this.resetReconnectState();
  1083. this.stopHeartBeat();
  1084. if (this.reconnectCount < this.maxReconnectAttempts) {
  1085. this.reconnectCount++;
  1086. const delay = 1000;
  1087. console.log(`第${this.reconnectCount}次重连,延迟${delay}ms`);
  1088. this.reconnectTimer = setInterval(() => {
  1089. this.initSocket();
  1090. }, delay);
  1091. } else {
  1092. console.log(`停止重连(手动关闭/已达最大次数)`);
  1093. this.closeWebSocket(true);
  1094. }
  1095. },
  1096. // 重置重连状态
  1097. resetReconnectState() {
  1098. this.reconnectCount = 0;
  1099. if (this.reconnectTimer) {
  1100. clearInterval(this.reconnectTimer);
  1101. this.reconnectTimer = null;
  1102. }
  1103. },
  1104. //输入框
  1105. inputFocus() {
  1106. this.chatHeight = this.keyboardHeight;
  1107. this.isFocus = true;
  1108. },
  1109. inputBlur() {
  1110. this.chatHeight = 0;
  1111. this.isFocus = false
  1112. },
  1113. getTimeDifferenceInSeconds(createTimeStr) {
  1114. const createTime = new Date(createTimeStr.replace(/-/g, '/'));
  1115. const now = new Date();
  1116. const timeDiffMs = now - createTime;
  1117. const timeDiffSeconds = Math.floor(timeDiffMs / 1000);
  1118. return Math.max(0, timeDiffSeconds);
  1119. },
  1120. // 录播时间点
  1121. onVideoMetaLoaded(e) {
  1122. this.videoProgressKey = `videoProgress_${this.liveId}`;
  1123. this.setVideoProgress();
  1124. },
  1125. setVideoProgress() {
  1126. // 只有录播和回放需要设置进度
  1127. if (this.liveItem.liveType !== 2 && this.liveItem.liveType !== 3) {
  1128. return;
  1129. }
  1130. let currentTime = 0;
  1131. if (this.liveItem.liveType === 2) {
  1132. // 录播:计算当前时间与开始时间的差值,对视频总时长取模
  1133. const diff = this.getTimeDifferenceInSeconds(this.liveItem.startTime);
  1134. currentTime = diff % this.liveItem.duration;
  1135. } else if (this.liveItem.liveType === 3) {
  1136. // 回放:从存储中获取进度
  1137. const storedProgress = uni.getStorageSync(this.videoProgressKey);
  1138. currentTime = storedProgress || 0;
  1139. }
  1140. const videoId = `myVideo_${this.liveId}`;
  1141. const videoContext = uni.createVideoContext(videoId, this);
  1142. if (videoContext) {
  1143. videoContext.seek(currentTime);
  1144. console.log(`设置视频播放位置: ${currentTime}秒`);
  1145. }
  1146. },
  1147. // 视频数据加载完成
  1148. onVideoLoaded(e) {
  1149. console.log('视频数据加载完成');
  1150. },
  1151. // 视频时间更新
  1152. onVideoTimeUpdate(e) {
  1153. // 获取当前播放时间
  1154. this.videoCurrentTime = e.detail.currentTime;
  1155. // 每隔5秒保存一次进度(避免频繁存储)
  1156. if (Math.floor(this.videoCurrentTime) % 5 === 0) {
  1157. this.saveVideoProgress();
  1158. }
  1159. },
  1160. // 视频暂停
  1161. onVideoPause(e) {
  1162. // this.isVideoPlaying = false;
  1163. // 暂停时保存进度
  1164. this.saveVideoProgress();
  1165. },
  1166. // 视频播放
  1167. onVideoPlay(e) {
  1168. // this.isVideoPlaying = true;
  1169. },
  1170. // 设置视频当前时间
  1171. // setVideoCurrentTime(time) {
  1172. // if (!time) return;
  1173. // const videoId = `myVideo_${this.liveId}`;
  1174. // const videoContext = uni.createVideoContext(videoId, this);
  1175. // if (videoContext) {
  1176. // videoContext.seek(time);
  1177. // console.log(`设置视频播放位置: ${time}秒`);
  1178. // }
  1179. // },
  1180. // 保存视频进度
  1181. saveVideoProgress() {
  1182. if (this.videoProgressKey) {
  1183. uni.setStorage({
  1184. key: this.videoProgressKey,
  1185. data: this.videoCurrentTime,
  1186. success: () => {},
  1187. fail: (err) => {
  1188. console.error('保存视频进度失败:', err);
  1189. }
  1190. });
  1191. }
  1192. },
  1193. // 点击红包
  1194. onRed() {
  1195. if (!this.liveId) return;
  1196. if (!this.redInfo?.redId) return;
  1197. if (this.redTimer) {
  1198. clearInterval(this.redTimer);
  1199. this.redTimer = null;
  1200. }
  1201. let data = {
  1202. liveId: this.liveId,
  1203. userId: this.userData.userId,
  1204. redId: this.redInfo.redId,
  1205. }
  1206. liveRed(data).then(res => {
  1207. this.isShowRed = false
  1208. this.redCard = res
  1209. this.isShowRedCard = true
  1210. },
  1211. rej => {}
  1212. );
  1213. },
  1214. //领取优惠券
  1215. onCoupon() {
  1216. if (!this.couponInfo.couponIssueId) return;
  1217. let data = {
  1218. goodsId: this.couponInfo.goodsId,
  1219. couponIssueId: this.couponInfo.couponIssueId,
  1220. liveId: this.liveId
  1221. };
  1222. coupon(data)
  1223. .then(res => {
  1224. if (res.code == 200) {
  1225. uni.showToast({
  1226. title: res.msg,
  1227. icon: 'none'
  1228. });
  1229. this.isShowCoupon = false
  1230. // const couponData = res.data || {};
  1231. } else {
  1232. uni.showToast({
  1233. title: res.msg,
  1234. icon: 'none'
  1235. });
  1236. }
  1237. })
  1238. .catch(rej => {});
  1239. },
  1240. // 抽奖
  1241. onLottery() {
  1242. if (!this.lotteryInfo) return;
  1243. let data = {
  1244. lotteryId: this.lotteryInfo.lotteryId
  1245. };
  1246. liveLottery(data)
  1247. .then(res => {
  1248. if (res.code == 200) {
  1249. const resData = res.data || {}; // 兜底 res.data 为对象,避免访问 res.data.products 报错
  1250. this.lotteryList = Array.isArray(resData) ? resData : [];
  1251. // 兜底 products 为数组
  1252. this.lotteryProducts = Array.isArray(resData.products) ? resData.products : [];
  1253. if (resData.duration) {
  1254. this.isShowLotteryPop = true;
  1255. }
  1256. } else {
  1257. uni.showToast({
  1258. title: res.msg,
  1259. icon: 'none'
  1260. });
  1261. this.lotteryList = [];
  1262. this.lotteryProducts = [];
  1263. }
  1264. })
  1265. .catch(rej => {
  1266. uni.showToast({
  1267. title: '获取抽奖信息失败',
  1268. icon: 'none'
  1269. });
  1270. // 失败时强制重置为数组
  1271. this.lotteryList = [];
  1272. this.lotteryProducts = [];
  1273. });
  1274. },
  1275. // 参与抽奖
  1276. onClaim() {
  1277. let data = {
  1278. liveId: this.liveId,
  1279. lotteryId: this.lotteryInfo.lotteryId,
  1280. }
  1281. claim(data).then(res => {
  1282. if (res.code == 200) {
  1283. uni.showToast({
  1284. title: res.msg,
  1285. icon: 'none'
  1286. });
  1287. this.isShowLotteryPop = false
  1288. } else {
  1289. uni.showToast({
  1290. title: res.msg,
  1291. icon: 'none'
  1292. });
  1293. }
  1294. },
  1295. rej => {}
  1296. );
  1297. },
  1298. // 商品收藏
  1299. onGoodsCollect(item) {
  1300. if (!item || item.length === 0 || !item.goodsId) {
  1301. return;
  1302. }
  1303. collectGoods(item.goodsId).then(res => {
  1304. if (res.code == 200) {
  1305. uni.showToast({
  1306. title: res.msg,
  1307. icon: 'none'
  1308. });
  1309. item.isFavorite = !item.isFavorite
  1310. } else {
  1311. uni.showToast({
  1312. title: res.msg,
  1313. icon: 'none'
  1314. });
  1315. }
  1316. },
  1317. rej => {}
  1318. );
  1319. },
  1320. //正在购买
  1321. getliveOrder(item) {
  1322. if (!this.liveId) {
  1323. return;
  1324. }
  1325. liveOrderUser(this.liveId).then(res => {
  1326. // console.log("正在购买", res)
  1327. if (res.code == 200) {
  1328. this.orderUser = res;
  1329. } else {
  1330. console.log('获取正在购买用户失败');
  1331. }
  1332. },
  1333. rej => {}
  1334. );
  1335. },
  1336. onLiveStateChange(e, liveItem) {
  1337. // console.log('直播状态变化:', e.detail.code, e.detail);
  1338. // 可以根据状态码处理不同的直播状态
  1339. const stateCode = e.detail.code;
  1340. // 2001: 已经连接服务器
  1341. // 2002: 已经连接服务器,开始拉流
  1342. // 2003: 网络接收到首个视频数据包(IDR)
  1343. // 2004: 视频播放开始
  1344. // 2005: 视频播放进度
  1345. // 2006: 视频播放结束
  1346. // 2007: 视频播放Loading
  1347. // 2008: 解码器启动
  1348. // -2301: 网络断连,且经多次重连抢救无效,更多重试请自行重启播放
  1349. // -2302: 获取加速拉流地址失败
  1350. }, // 直播错误事件
  1351. onLiveError(e, liveItem) {
  1352. this.videoError(e, liveItem);
  1353. },
  1354. // 红包 卡片 抽奖
  1355. getCurrentActivities() {
  1356. if (!this.liveId) return;
  1357. currentActivities(this.liveId).then(res => {
  1358. if (res.code === 200) {
  1359. // 提取数据(默认空数组/对象避免报错)
  1360. this.redInfo = (res.red || [])[0];
  1361. this.lotteryInfo = (res.lottery || [])[0];
  1362. this.goodsCard = res.goods || {};
  1363. this.isShowGoods = this.goodsCard && this.goodsCard.status == 1;
  1364. this.isShowRed = this.redInfo && this.redInfo.redStatus == 1;
  1365. this.isShowLottery = this.lotteryInfo && this.lotteryInfo.lotteryStatus == 1;
  1366. if (this.isShowRed) {
  1367. this.redTimer = setInterval(() => {
  1368. const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo
  1369. .duration)
  1370. if (!redCountdown) {
  1371. this.isShowRed = false
  1372. clearInterval(this.redTimer)
  1373. }
  1374. }, 1000);
  1375. }
  1376. // 处理抽奖定时器
  1377. if (this.isShowLottery) {
  1378. this.lotteryTimer = setInterval(() => {
  1379. this.countdown = this.handleTime(this.lotteryInfo.updateTime, this
  1380. .lotteryInfo
  1381. .duration)
  1382. }, 1000);
  1383. }
  1384. } else {
  1385. uni.showToast({
  1386. title: res.msg,
  1387. icon: 'none'
  1388. });
  1389. }
  1390. }, rej => {});
  1391. },
  1392. // 计算当前时间与 liveItem.startTime 的差值,并更新 totalTime
  1393. calculateTimeDiff(item) {
  1394. // 防御1:item 不存在直接返回
  1395. if (!item.startTime) return;
  1396. // 步骤1:提取对应场景的时间字符串(直播用startTime,抽奖用updateTime)
  1397. let timeStr = item.startTime;
  1398. // 转换时间格式(适配iOS,将 "-" 替换为 "/")
  1399. const iosCompatibleTime = timeStr.replace(/-/g, "/");
  1400. const time = new Date(iosCompatibleTime);
  1401. if (isNaN(time.getTime())) {
  1402. return;
  1403. }
  1404. const now = new Date();
  1405. let diffMs = Math.max(0, now - time); // 直播:已播放时长(现在-开始时间)
  1406. // 步骤4:转换为 时:分:秒(补零处理)
  1407. const totalSeconds = Math.floor(diffMs / 1000);
  1408. const hours = this.padZero(Math.floor(totalSeconds / 3600));
  1409. const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
  1410. const seconds = this.padZero(totalSeconds % 60);
  1411. this.$set(this.liveItem, "totalTime", `${hours}:${minutes}:${seconds}`);
  1412. this.$set(this.liveItem, "totalSeconds", totalSeconds);
  1413. },
  1414. padZero(num) {
  1415. return num < 10 ? `0${num}` : num;
  1416. },
  1417. // 启动当前直播间的时间差值定时器
  1418. startTimeTimer(item) {
  1419. // 防御:若 item 不存在,直接返回
  1420. if (!item) return;
  1421. // 立即计算一次(避免等待1秒才显示)
  1422. const totalTime = this.calculateTimeDiff(item);
  1423. item.timeTimer = setInterval(() => {
  1424. const totalTime = this.calculateTimeDiff(item);
  1425. }, 1000);
  1426. },
  1427. // 清除指定直播间的时间定时器
  1428. clearTimeTimer() {
  1429. if (this.liveItem.timeTimer) {
  1430. clearInterval(this.liveItem.timeTimer);
  1431. this.liveItem.timeTimer = null; // 清空定时器标识
  1432. }
  1433. },
  1434. toggleViewerList() {
  1435. const now = Date.now();
  1436. if (now - this.lastClickTime > this.clickDelay) {
  1437. this.showadd = !this.showadd;
  1438. if (this.showadd) {
  1439. this.getliveUser(false); // 加载第一页观众
  1440. }
  1441. this.lastClickTime = now;
  1442. }
  1443. },
  1444. closeAllWebSockets() {
  1445. this.isManualClose = true;
  1446. this.isSocketOpen = false; // 应该是 this.isSocketOpen
  1447. this.closeWebSocket(true);
  1448. },
  1449. // 清理所有定时器
  1450. clearAllTimers() {
  1451. if (this.intervalId) {
  1452. clearInterval(this.intervalId);
  1453. this.intervalId = null;
  1454. }
  1455. // if (this.pingpangTimes) {
  1456. // clearInterval(this.pingpangTimes);
  1457. // this.pingpangTimes = null;
  1458. // }
  1459. if (this.reconnectTimer) {
  1460. clearInterval(this.reconnectTimer);
  1461. this.reconnectTimer = null;
  1462. }
  1463. if (this.scrollTimer) {
  1464. clearTimeout(this.scrollTimer);
  1465. this.scrollTimer = null;
  1466. }
  1467. if (this.searchTimer) {
  1468. clearTimeout(this.searchTimer);
  1469. this.searchTimer = null;
  1470. }
  1471. if (this.purchasePromptTimer) {
  1472. clearTimeout(this.purchasePromptTimer);
  1473. this.purchasePromptTimer = null;
  1474. }
  1475. },
  1476. // 播放视频
  1477. playVideo() {
  1478. if (!this.liveItem) {
  1479. console.log('liveItem 为空,无法播放视频');
  1480. return;
  1481. }
  1482. try {
  1483. // 直播流使用live-player
  1484. if (this.liveItem.liveType === 1 && this.liveItem.livingUrl && this.liveItem.status == 2) {
  1485. const livePlayerId = `myLivePlayer_${this.liveId}`;
  1486. const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  1487. if (livePlayerContext) {
  1488. livePlayerContext.play();
  1489. }
  1490. } else if (this.liveItem.status == 1 && this.liveItem.previewUrl) {
  1491. const videoId = `myVideo_${this.liveId}`;
  1492. const videoContext = uni.createVideoContext(videoId, this);
  1493. if (videoContext) {
  1494. videoContext.play();
  1495. }
  1496. }
  1497. // 回放视频使用video
  1498. else if (this.liveItem.liveType === 2 && this.liveItem.videoUrl && this.liveItem.status == 2) {
  1499. const videoId = `myVideo_${this.liveId}`;
  1500. const videoContext = uni.createVideoContext(videoId, this);
  1501. if (videoContext) {
  1502. videoContext.play();
  1503. }
  1504. } else if (this.liveItem.liveType === 3 && this.liveItem.videoUrl && this.liveItem.status == 2) {
  1505. const videoId = `myVideo_${this.liveId}`;
  1506. const videoContext = uni.createVideoContext(videoId, this);
  1507. if (videoContext) {
  1508. videoContext.play();
  1509. }
  1510. }
  1511. } catch (error) {
  1512. console.error("播放视频失败:", error);
  1513. }
  1514. },
  1515. pauseVideo() {
  1516. if (!this.liveItem) return;
  1517. try {
  1518. // 直播流使用live-player
  1519. if (this.liveItem.status == 1) {
  1520. const videoId = `myVideo_${this.liveId}`;
  1521. const videoContext = uni.createVideoContext(videoId, this);
  1522. if (videoContext) {
  1523. videoContext.pause();
  1524. }
  1525. } else if (this.liveItem.status == 2) {
  1526. if (this.liveItem.liveType === 1) {
  1527. const livePlayerId = `myLivePlayer_${this.liveId}`;
  1528. const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  1529. if (livePlayerContext) {
  1530. livePlayerContext.pause();
  1531. }
  1532. } else if (this.liveItem.liveType === 2) {
  1533. const videoId = `myVideo_${this.liveId}`;
  1534. const videoContext = uni.createVideoContext(videoId, this);
  1535. if (videoContext) {
  1536. videoContext.pause();
  1537. }
  1538. }
  1539. }
  1540. } catch (error) {
  1541. console.error("暂停视频失败:", error);
  1542. }
  1543. },
  1544. // 视频错误处理
  1545. videoError(e, liveItem) {
  1546. if (!liveItem || !this.liveId) return;
  1547. // 初始化重试计数
  1548. if (this.videoRetryCounts[liveItem.liveId] === undefined) {
  1549. this.videoRetryCounts[liveItem.liveId] = 0;
  1550. }
  1551. // 限制重试次数
  1552. if (this.videoRetryCounts[liveItem.liveId] >= 3) {
  1553. console.error(`直播间 ${this.liveId} 视频加载失败,停止重试`);
  1554. // 显示错误提示
  1555. uni.showToast({
  1556. title: "视频加载失败,请检查网络",
  1557. icon: 'none',
  1558. duration: 2000
  1559. });
  1560. return;
  1561. }
  1562. this.videoRetryCounts[this.liveId]++;
  1563. // 延迟重试
  1564. setTimeout(() => {
  1565. if (this.liveId === this.liveId) {
  1566. console.log(`第${this.videoRetryCounts[this.liveId]}次重试播放视频`);
  1567. this.playVideo();
  1568. }
  1569. }, 2000);
  1570. },
  1571. openViews() {
  1572. // 计算scroll-view高度
  1573. this.$nextTick(() => {
  1574. const query = uni.createSelectorQuery().in(this);
  1575. query.select('.view-box').boundingClientRect(data => {
  1576. if (data) {
  1577. // 减去标题和底部固定区域的高度
  1578. this.scrollHeight = data.height - 80 - 120; // 80是标题高度,120是底部高度
  1579. }
  1580. }).exec();
  1581. });
  1582. },
  1583. // 滚动到底部触发
  1584. handleScrollToLower() {
  1585. // 清除上一次未执行的定时器,避免重复请求
  1586. if (this.scrollTimer) {
  1587. clearTimeout(this.scrollTimer);
  1588. }
  1589. // 延迟0.5秒(500毫秒)执行接口请求
  1590. this.scrollTimer = setTimeout(() => {
  1591. this.getliveUser(true); // 加载更多数据
  1592. }, 1000); // 延迟时间:500毫秒
  1593. },
  1594. async getLiveMsg(liveItem) {
  1595. if (!liveItem || !this.liveId) {
  1596. console.error('getLiveMsg 错误:无效的 liveItem');
  1597. return;
  1598. }
  1599. try {
  1600. const res = await liveMsg(this.liveId, 30, 1);
  1601. if (res.code == 200) {
  1602. const rows = Array.isArray(res.rows) ? res.rows : [];
  1603. const reversedTalkList = [...rows].reverse();
  1604. this.talklist = Array.isArray(reversedTalkList) ? reversedTalkList : [];
  1605. // 获取历史消息后也滚动到底部
  1606. this.$nextTick(() => {
  1607. this.scrollToBottom();
  1608. });
  1609. } else {
  1610. this.talklist = [];
  1611. }
  1612. } catch (error) {
  1613. this.talklist = [];
  1614. console.error("获取聊天记录失败:", error);
  1615. }
  1616. },
  1617. // 获取直播间用户
  1618. // getliveUser(isLoadMore = false) {
  1619. // this.viewLoading = true;
  1620. // watchUserList(this.liveId, this.viewPageSize, this.viewPageNum, false)
  1621. // .then(res => {
  1622. // if (res.code === 200) {
  1623. // const userRows = Array.isArray(res.rows) ? res.rows : [];
  1624. // this.liveViewersData = userRows.map(item => ({
  1625. // avatar: item.avatar || '',
  1626. // userId: item.userId || '',
  1627. // nickName: item.nickName || '未命名'
  1628. // }));
  1629. // console.log("请求到了",this.liveViewersData)
  1630. // this.liveUserTotal = res.total || 0;
  1631. // const newRows = Array.isArray(res.rows) ? res.rows : [];
  1632. // const currentViewers = Array.isArray(this.liveViewers) ? this.liveViewers : [];
  1633. // this.liveViewers = isLoadMore ? [...currentViewers, ...newRows] : newRows;
  1634. // this.viewPageNum++;
  1635. // } else {
  1636. // this.liveViewers = []; // 接口失败时强制置空数组
  1637. // }
  1638. // })
  1639. // .catch(error => {
  1640. // console.error('获取观众列表失败:', error);
  1641. // this.liveViewers = []; // 捕获异常时强制置空数组
  1642. // })
  1643. // .finally(() => {
  1644. // this.viewLoading = false; // 无论成功失败都关闭加载状态
  1645. // });
  1646. // },
  1647. async getliveUser(isLoadMore = false) {
  1648. this.viewLoading = true;
  1649. try {
  1650. const res = await watchUserList(this.liveId, this.viewPageSize, this.viewPageNum, false);
  1651. if (res.code === 200) {
  1652. const userRows = Array.isArray(res.rows) ? res.rows : [];
  1653. this.liveViewersData = userRows.map(item => ({
  1654. avatar: item.avatar || '',
  1655. userId: item.userId || '',
  1656. nickName: item.nickName || '未命名'
  1657. }));
  1658. this.liveUserTotal = res.total || 0;
  1659. const newRows = Array.isArray(res.rows) ? res.rows : [];
  1660. const currentViewers = Array.isArray(this.liveViewers) ? this.liveViewers : [];
  1661. this.liveViewers = isLoadMore ? [...currentViewers, ...newRows] : newRows;
  1662. this.viewPageNum++;
  1663. }
  1664. } catch (error) {
  1665. console.error('获取观众列表失败:', error);
  1666. } finally {
  1667. this.viewLoading = false;
  1668. }
  1669. },
  1670. //小黄车搜索商品
  1671. handleSearchInput() {
  1672. // 使用防抖优化性能,避免频繁请求
  1673. clearTimeout(this.searchTimer);
  1674. this.searchTimer = setTimeout(() => {
  1675. this.queryCollect();
  1676. }, 500); // 500毫秒延迟
  1677. },
  1678. // 显示购买提示信息
  1679. showPurchaseMessage() {
  1680. // 清除之前的定时器
  1681. if (this.purchasePromptTimer) {
  1682. clearTimeout(this.purchasePromptTimer);
  1683. }
  1684. // 显示提示
  1685. this.showPurchasePrompt = true;
  1686. // 2秒后自动隐藏
  1687. this.purchasePromptTimer = setTimeout(() => {
  1688. this.showPurchasePrompt = false;
  1689. }, 2000);
  1690. },
  1691. //名字超过省略
  1692. truncateString(str, maxLength) {
  1693. if (typeof str !== 'string' || str.length <= maxLength) {
  1694. return str;
  1695. }
  1696. return str.slice(0, maxLength) + '...'; // 截断后加省略号
  1697. },
  1698. // 去订单列表
  1699. goOrderList() {
  1700. uni.navigateTo({
  1701. url: "/pages_shopping/live/order"
  1702. })
  1703. },
  1704. // 修改获取直播信息方法
  1705. async getliving(liveId) {
  1706. if (!liveId) return;
  1707. const param = {
  1708. id: liveId
  1709. };
  1710. try {
  1711. const res = await getlive(param);
  1712. if (res.code !== 200) {
  1713. uni.showToast({
  1714. title: res.msg,
  1715. icon: 'none'
  1716. });
  1717. return;
  1718. }
  1719. // 关键:用 Object.assign 合并旧数据与新数据,确保原有响应式属性不丢失
  1720. // 同时通过 $set 触发整体更新(若 liveItem 初始为空,需先初始化)
  1721. this.liveItem = Object.assign({}, this.liveItem, res.data);
  1722. // this.liveItem = res.data;
  1723. this.talklist = Array.isArray((res.data || {}).talklist) ? res.data.talklist : [];
  1724. this.startTimeTimer(this.liveItem);
  1725. // 清除旧定时器(如预告倒计时)
  1726. if (this.liveStartTimer) {
  1727. clearInterval(this.liveStartTimer);
  1728. this.liveStartTimer = null;
  1729. }
  1730. if (res.data.status == 1) {
  1731. // 直播预告
  1732. this.liveStartTimer = setInterval(async () => {
  1733. this.liveCountdown = this.handleTime(res.data.startTime, 0);
  1734. if (!this.liveCountdown) {
  1735. await this.getliving(this.liveId);
  1736. clearInterval(this.liveStartTimer);
  1737. }
  1738. }, 1000);
  1739. this.$set(this.liveItem, 'previewUrl', res.data.previewUrl);
  1740. this.$set(this.liveItem, 'livingUrl', ''); // 清空直播流
  1741. this.$set(this.liveItem, 'videoUrl', ''); // 清空回放视频
  1742. } else if (res.data.status == 2) {
  1743. if (res.data.liveType == 1) {
  1744. // 直播流
  1745. let cTime = Math.floor(Math.random() * 10000) + 1;
  1746. let livingUrl = res.data.flvHlsUrl + "&t=" + cTime;
  1747. console.log("地址在", this.liveItem.livingUrl)
  1748. this.$set(this.liveItem, 'livingUrl', livingUrl);
  1749. this.$set(this.liveItem, 'videoUrl', ''); // 清空回放视频
  1750. } else if (res.data.liveType === 2 || res.data.liveType === 3) {
  1751. // 回放视频 2录播 3直播回放
  1752. this.$set(this.liveItem, 'videoUrl', res.data.videoUrl);
  1753. this.$set(this.liveItem, 'livingUrl', '');
  1754. } else {
  1755. // 未开播
  1756. this.$set(this.liveItem, 'livingUrl', '');
  1757. this.$set(this.liveItem, 'videoUrl', '');
  1758. }
  1759. }
  1760. await this.getLiveMsg(this.liveItem);
  1761. await this.getliveViewData(this.liveItem);
  1762. //流量
  1763. let that = this
  1764. if (this.trafficInterval != null) {
  1765. clearInterval(that.trafficInterval)
  1766. }
  1767. this.trafficInterval = setInterval(function() {
  1768. that.getInternetTraffic()
  1769. }, 5000);
  1770. this.$set(this.liveItem, 'autoplay', res.data.liveType !== 0);
  1771. this.$set(this.liveItem, 'showType', res.data.showType);
  1772. this.storeId = res.storeId;
  1773. // 2. 启动“10秒刷新直播间数据”的定时器
  1774. this.startLiveViewDataTimer();
  1775. this.playVideo();
  1776. // live_start 时主动初始化播放组件
  1777. // this.initPlayerComponent();
  1778. } catch (err) {
  1779. console.error("获取直播信息失败:", err);
  1780. uni.showToast({
  1781. title: "获取直播信息失败",
  1782. icon: 'none'
  1783. });
  1784. }
  1785. },
  1786. // initPlayerComponent() {
  1787. // const {
  1788. // liveType,
  1789. // status,
  1790. // liveId,
  1791. // livingUrl,
  1792. // videoUrl
  1793. // } = this.liveItem;
  1794. // // 仅在“直播中”(status:2)时初始化
  1795. // if (status !== 2) return;
  1796. // this.$nextTick(() => { // 等待视图更新后再操作组件
  1797. // // 1. 直播流(liveType:1):初始化 live-player
  1798. // if (liveType === 1 && livingUrl) {
  1799. // const livePlayerId = `myLivePlayer_${liveId}`;
  1800. // const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  1801. // if (livePlayerContext) {
  1802. // livePlayerContext.stop(); // 先停止旧流
  1803. // livePlayerContext.play(); // 播放新流
  1804. // }
  1805. // }
  1806. // // 2. 录播/回放(liveType:2/3):初始化 video
  1807. // if ((liveType === 2 || liveType === 3) && videoUrl) {
  1808. // const videoId = `myVideo_${liveId}`;
  1809. // const videoContext = uni.createVideoContext(videoId, this);
  1810. // if (videoContext) {
  1811. // videoContext.stop(); // 停止旧视频
  1812. // videoContext.seek(0); // 重置到开头
  1813. // videoContext.play(); // 播放新视频
  1814. // }
  1815. // }
  1816. // });
  1817. // },
  1818. // 设置视频播放
  1819. maskString(str, maskChar = '*') {
  1820. // 如果str是undefined或null,直接返回空字符串
  1821. if (!str) return '';
  1822. // 确保str是字符串(如果是数字等类型,先转为字符串)
  1823. const strVal = String(str);
  1824. return strVal.split('').map((char, index) => (index === 0 ? char : maskChar)).join(
  1825. '');
  1826. },
  1827. getPureDecimal(num, precision = 6) {
  1828. const decimalPart = Math.abs(num).toFixed(precision).split('.')[1];
  1829. return decimalPart?.replace(/0+$/, '') || ''; // 移除末尾多余的0
  1830. },
  1831. // 返回上一个页面并关闭WebSocket
  1832. goBack() {
  1833. // 暂停当前视频
  1834. if (this.liveItem) {
  1835. this.pauseVideo();
  1836. }
  1837. // 关闭WebSocket连接
  1838. this.closeWebSocket(true);
  1839. // 导航返回
  1840. const pages = getCurrentPages();
  1841. if (pages.length > 1) {
  1842. uni.navigateBack();
  1843. } else {
  1844. uni.reLaunch({
  1845. url: '/pages_course/livingList'
  1846. });
  1847. }
  1848. },
  1849. // 点赞
  1850. async onLike() {
  1851. if (!this.liveId) return;
  1852. try {
  1853. const res = await liveDataLike(this.liveId);
  1854. if (res?.like) {
  1855. this.liveViewData.like++; // 只更新当前直播间的点赞数
  1856. } else {
  1857. uni.showToast({
  1858. title: res.msg,
  1859. icon: 'none'
  1860. });
  1861. }
  1862. } catch (error) {
  1863. console.error('点赞失败:', error);
  1864. }
  1865. },
  1866. //直播间点赞、关注、在线人数数据
  1867. getliveViewData(liveItem) {
  1868. if (!liveItem || !this.liveId) return;
  1869. getLiveViewData(this.liveId).then(res => {
  1870. if (res.code == 200) {
  1871. // 强制响应式更新,确保数据实时显示
  1872. this.liveViewData = res;
  1873. }
  1874. }).catch(error => {
  1875. console.error("获取直播间数据失败:", error);
  1876. // 失败时兜底,避免显示异常
  1877. this.liveViewData = {
  1878. like: 0,
  1879. watchCount: 0
  1880. };
  1881. });
  1882. },
  1883. startLiveViewDataTimer() {
  1884. // 先清除旧定时器(防止重复创建)
  1885. if (this.liveViewDataTimer) {
  1886. clearInterval(this.liveViewDataTimer);
  1887. this.liveViewDataTimer = null;
  1888. }
  1889. // 启动新定时器,每3秒执行一次
  1890. this.liveViewDataTimer = setInterval(() => {
  1891. // 安全校验:确保liveItem和liveId存在(避免无效请求)
  1892. if (this.liveItem && this.liveId) {
  1893. this.getliveViewData(this.liveItem);
  1894. }
  1895. }, 10000);
  1896. },
  1897. // 去购买,跳商品详情
  1898. goShop(productId, goodsId) {
  1899. if (!this.liveId) return;
  1900. uni.navigateTo({
  1901. url: '/pages_shopping/live/goods?productId=' + productId + '&liveId=' + this.liveId +
  1902. '&goodsId=' +
  1903. goodsId + '&storeId=' + this.storeId
  1904. })
  1905. },
  1906. // 查询店铺
  1907. async queryCollect() {
  1908. if (!this.liveId) return;
  1909. if (this.inputInfo == null) this.inputInfo = ''
  1910. try {
  1911. const res = await liveStore(this.liveId, this.inputInfo);
  1912. if (res.code === 200) {
  1913. // 数据绑定到当前 liveItem,避免全局污染
  1914. this.products = Array.isArray(res.data) ? res.data : [];
  1915. }
  1916. } catch (error) {
  1917. console.error('获取小黄车商品失败:', error);
  1918. }
  1919. },
  1920. // 时间戳
  1921. initTime() {
  1922. const now = new Date();
  1923. this.timestamp = now.getTime(); // 例如:'2023-04-01 12:00:00'
  1924. },
  1925. openCart() {
  1926. this.queryCollect()
  1927. this.shopping = true
  1928. },
  1929. close() {
  1930. this.showadd = false
  1931. },
  1932. // 关闭小黄车
  1933. closeShop() {
  1934. this.shopping = false;
  1935. },
  1936. // 修改关闭WebSocket方法
  1937. // closeWebSocket() {
  1938. // this.socket?.close();
  1939. // },
  1940. // 关闭WebSocket连接(isManual:是否手动关闭)
  1941. closeWebSocket(isManual = true) {
  1942. // 修复判断条件:当 socket 为 null 或未打开时,直接返回
  1943. if (!this.socket || !this.isSocketOpen) {
  1944. console.warn("WebSocket 任务不存在或未打开,无需关闭");
  1945. return;
  1946. }
  1947. console.log("websocket 连接关闭");
  1948. this.isManualClose = isManual;
  1949. this.stopHeartBeat();
  1950. this.resetReconnectState();
  1951. try {
  1952. // 先保存引用,避免在关闭过程中被置为null
  1953. const socketToClose = this.socket;
  1954. this.socket = null;
  1955. this.isSocketOpen = false;
  1956. socketToClose.close({
  1957. code: 1000,
  1958. reason: isManual ? "主动关闭" : "异常关闭"
  1959. });
  1960. console.log("WebSocket连接已发起关闭");
  1961. } catch (err) {
  1962. console.error("关闭WebSocket失败:", err);
  1963. // 即使关闭失败,也要重置状态
  1964. this.socket = null;
  1965. this.isSocketOpen = false;
  1966. }
  1967. },
  1968. startHeartBeat() {
  1969. this.stopHeartBeat(); // 先停止现有心跳,防止重复
  1970. this.sendHeartBeat(); // 立即发送一次心跳
  1971. // 按间隔循环发送心跳
  1972. this.heartBeatTimer = setInterval(() => {
  1973. this.sendHeartBeat();
  1974. }, this.heartBeatInterval);
  1975. },
  1976. initSocket() {
  1977. if (!this.userData) {
  1978. this.getUserInfo()
  1979. }
  1980. if (this.isConnecting) {
  1981. return;
  1982. }
  1983. // 如果已经存在连接且状态为open,则退出
  1984. if (this.socket && this.socket.readyState === 1) {
  1985. return;
  1986. }
  1987. if (this.socket && (this.socket.readyState === 0 || this.socket.readyState === 1)) {
  1988. console.log('关闭现有WebSocket连接,创建新连接');
  1989. this.closeWebSocket(true);
  1990. }
  1991. // 校验必要参数
  1992. if (!this.liveId) {
  1993. console.error("缺失直播间ID,无法初始化WebSocket");
  1994. return;
  1995. }
  1996. console.log("用户信息", this.userData)
  1997. if (!this.userData || !this.userData.userId) {
  1998. console.error("用户信息缺失,无法初始化WebSocket");
  1999. return;
  2000. }
  2001. // 清除之前的重连定时器
  2002. this.resetReconnectState();
  2003. const now = new Date();
  2004. this.timestamp = now.getTime(); // 生成签名
  2005. const signature = CryptoJS.HmacSHA256(
  2006. `${this.liveId}${this.userData.userId}${this.userType}${this.timestamp}`,
  2007. this.timestamp.toString()
  2008. ).toString(CryptoJS.enc.Hex);
  2009. try {
  2010. const baseWsUrl = 'wss://api.fhhx.runtzh.com/ws/app/webSocket';
  2011. // const baseWsUrl = 'ws://192.168.10.166:7114/ws/app/webSocket';
  2012. let wsUrl =
  2013. `${baseWsUrl}?userId=${this.userData.userId}&liveId=${this.liveId}&userType=${this.userType}&timestamp=${this.timestamp}&signature=${signature}`;
  2014. if (this.qrFrom) {
  2015. wsUrl += this.qrFrom;
  2016. }
  2017. // console.log("创建新的WebSocket连接:", wsUrl);
  2018. const socketTask = uni.connectSocket({
  2019. url: wsUrl,
  2020. success: () => console.log("Socket连接请求发送成功"),
  2021. fail: (err) => {
  2022. console.error("Socket连接请求失败:", err);
  2023. this.handleReconnect();
  2024. }
  2025. });
  2026. // 连接打开事件
  2027. socketTask.onOpen((res) => {
  2028. console.log("WebSocket连接已打开");
  2029. this.socket = socketTask;
  2030. this.isConnecting = false;
  2031. this.isSocketOpen = true;
  2032. this.reconnectCount = 0;
  2033. this.resetReconnectState();
  2034. this.heartBeatRetryCount = 0; // 重置心跳重试次数
  2035. this.shownEntryUsers.clear(); // 重连后重置进入提示记录
  2036. this.startHeartBeat();
  2037. });
  2038. // 消息接收事件
  2039. socketTask.onMessage((res) => {
  2040. try {
  2041. const data = JSON.parse(res.data);
  2042. // 处理服务端心跳响应(根据服务端协议调整cmd字段)
  2043. if (data.cmd === "heartBeatAck") {
  2044. this.stopHeartBeat(); // 清除当前超时检测
  2045. this.startHeartBeat(); // 重新启动心跳周期
  2046. return;
  2047. }
  2048. this.handleSocketMessage(res);
  2049. } catch (err) {
  2050. console.error("消息解析异常:", err);
  2051. }
  2052. });
  2053. // 连接错误事件
  2054. socketTask.onError((err) => {
  2055. console.error("WebSocket连接错误:", err);
  2056. this.isSocketOpen = false;
  2057. this.stopHeartBeat();
  2058. this.isConnecting = false;
  2059. this.handleReconnect(); // 错误直接触发重连
  2060. });
  2061. // 连接关闭事件
  2062. socketTask.onClose((res) => {
  2063. console.log("WebSocket连接关闭:", res);
  2064. this.isSocketOpen = false;
  2065. this.isConnecting = false;
  2066. this.stopHeartBeat(); // 清除心跳定时器(复用之前的停止方法)
  2067. if (!this.isManualClose && this.reconnectCount < this.maxReconnectAttempts) {
  2068. this.handleReconnect();
  2069. } else {}
  2070. });
  2071. } catch (e) {
  2072. console.error("创建WebSocket异常:", e);
  2073. this.handleReconnect();
  2074. }
  2075. },
  2076. handleTime(time, duration) {
  2077. // 前置处理:将time转换为毫秒级时间戳
  2078. let timeStamp;
  2079. // 1. 如果time是数字且合理(毫秒级时间戳通常为13位左右的正数),视为有效时间戳
  2080. if (typeof time === 'number' && time > 0 && time < 9999999999999) { // 上限约为3000年
  2081. timeStamp = time;
  2082. }
  2083. // 2. 如果是字符串,尝试解析为日期后转为时间戳
  2084. else if (typeof time === 'string' && time.trim() !== '') {
  2085. // 处理兼容性:将"2025-09-25 17:30:00"转为ISO格式"2025-09-25T17:30:00"
  2086. const isoTime = time.replace(' ', 'T');
  2087. const date = new Date(isoTime);
  2088. // 校验日期是否有效
  2089. if (!isNaN(date.getTime())) {
  2090. timeStamp = date.getTime();
  2091. } else {
  2092. console.error('无效的日期格式:', time);
  2093. return false; // 格式错误时返回false
  2094. }
  2095. } else {
  2096. console.error('time参数必须是有效的时间戳(数字)或日期字符串');
  2097. return false;
  2098. }
  2099. // 后续逻辑保持不变(基于转换后的timeStamp计算)
  2100. const targetTimestamp = timeStamp + duration * 60 * 1000;
  2101. const currentTimestamp = new Date().getTime();
  2102. const timeDiffMs = targetTimestamp - currentTimestamp;
  2103. if (timeDiffMs <= 0) {
  2104. return false;
  2105. }
  2106. const hours = Math.floor(timeDiffMs / (1000 * 60 * 60));
  2107. const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60));
  2108. const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000);
  2109. const formatNum = (num) => num.toString().padStart(2, "0");
  2110. return {
  2111. hours: formatNum(hours),
  2112. minutes: formatNum(minutes),
  2113. seconds: formatNum(seconds)
  2114. };
  2115. },
  2116. // 处理Socket消息
  2117. async handleSocketMessage(message) {
  2118. let data = JSON.parse(message.data)
  2119. const socketMessage = data.data // 服务端返回的消息体
  2120. if (data.code == 200) {
  2121. const messageData = {
  2122. ...socketMessage,
  2123. cmd: socketMessage.cmd || '', // 确保cmd字段存在
  2124. ts: Date.now() // 时间戳
  2125. };
  2126. // 处理服务端返回的sendMsg消息,加入本地列表
  2127. if (socketMessage.cmd == 'sendMsg') {
  2128. if (!this.isSocketAvailable()) {
  2129. uni.showToast({
  2130. title: '连接已断开,正在重试...',
  2131. icon: 'none'
  2132. });
  2133. this.handleReconnect(); // 主动触发重连
  2134. return;
  2135. }
  2136. const oldList = Array.isArray(this.talklist) ? this.talklist : [];
  2137. const newList = [...oldList, messageData];
  2138. this.talklist = newList;
  2139. // 1. 将消息追加到当前直播间的talklist中(响应式更新)
  2140. this.talklist = newList;
  2141. this.scrollToBottom();
  2142. // 2. 延迟下一帧滚动到最新消息(确保DOM已更新)
  2143. // this.$nextTick(() => {
  2144. // const lastIndex = this.talklist.length - 1;
  2145. // this.scrollIntoView = `list_${lastIndex}`;
  2146. // });
  2147. } else if (socketMessage.cmd == 'red') {
  2148. this.redInfo = JSON.parse(socketMessage.data);
  2149. this.isShowRed = socketMessage.status === 1;
  2150. if (this.isShowRed) {
  2151. this.redTimer = setInterval(() => {
  2152. const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo
  2153. .duration)
  2154. if (!redCountdown) {
  2155. this.isShowRed = false
  2156. clearInterval(this.redTimer)
  2157. }
  2158. }, 1000);
  2159. }
  2160. } else if (socketMessage.cmd == 'goods') {
  2161. this.goodsCard = JSON.parse(socketMessage.data);
  2162. this.isShowGoods = socketMessage.status == 1;
  2163. } else if (socketMessage.cmd == 'coupon') {
  2164. this.couponInfo = JSON.parse(socketMessage.data);
  2165. this.isShowCoupon = socketMessage.status === 1;
  2166. if (this.isShowCoupon) {
  2167. // this.couponTimer = setInterval(() => {
  2168. // const couponCountdown = this.handleTime(this.couponInfo.updateTime, this.couponInfo.duration)
  2169. // if (!couponCountdown) {
  2170. // this.isShowCoupon = false
  2171. // clearInterval(this.couponTimer)
  2172. // }
  2173. // }, 1000);
  2174. }
  2175. } else if (socketMessage.cmd == 'lottery') {
  2176. const parsedData = JSON.parse(socketMessage.data || '{}'); // 默认为空对象
  2177. this.lotteryInfo = parsedData || {}; // 确保是对象,避免 null
  2178. this.isShowLottery = socketMessage.status === 1;
  2179. if (socketMessage.status != 1) {
  2180. this.isShowLotteryPop = false
  2181. }
  2182. // 清除已有定时器(无论状态是否为1,先清掉旧的)
  2183. clearTimeout(this.lotteryTimer);
  2184. if (this.isShowLottery) {
  2185. this.lotteryTimer = setInterval(() => {
  2186. this.countdown = this.handleTime(this.lotteryInfo.updateTime, this.lotteryInfo
  2187. .duration)
  2188. if (!this.countdown) {
  2189. console.log("倒计时", this.countdown)
  2190. this.isShowLottery = false;
  2191. this.isShowLotteryPop = false;
  2192. clearInterval(this.lotteryTimer)
  2193. }
  2194. }, 1000);
  2195. } else {
  2196. this.isShowLottery = false
  2197. }
  2198. } else if (socketMessage.cmd == 'entry') {
  2199. try {
  2200. if (!this.liveUserCalled) {
  2201. await this.getliveUser(false);
  2202. this.liveUserCalled = true;
  2203. }
  2204. const userIdToEntry = socketMessage.userId;
  2205. const existingIndex = this.liveViewersData.findIndex(item => item.userId ===
  2206. userIdToEntry);
  2207. if (existingIndex === -1) {
  2208. const liveViewers = {
  2209. userId: socketMessage.userId,
  2210. nickName: socketMessage.nickName,
  2211. avatar: socketMessage.avatar
  2212. }
  2213. this.liveViewersData.push(liveViewers);
  2214. this.liveUserTotal++;
  2215. }
  2216. // 解析用户ID(根据实际接口字段调整,此处假设data含userId)
  2217. const userData = JSON.parse(socketMessage.data || '{}');
  2218. const userId = userData.userId || socketMessage.userId; // 兼容不同字段
  2219. if (!userId) return; // 无用户ID不处理
  2220. // 仅新用户(未显示过)才触发提示
  2221. if (!this.shownEntryUsers.has(userId)) {
  2222. this.inAndOut = socketMessage;
  2223. this.showWelcomeMessage = true;
  2224. this.shownEntryUsers.add(userId); // 加入已显示集合
  2225. // 3秒后隐藏提示(可调整时长)
  2226. if (this.welcomeTimer) clearTimeout(this.welcomeTimer);
  2227. this.welcomeTimer = setTimeout(() => {
  2228. this.showWelcomeMessage = false;
  2229. }, 3000);
  2230. }
  2231. } catch (err) {
  2232. console.error("解析entry用户数据失败:", err);
  2233. }
  2234. } else if (socketMessage.cmd == 'out') {
  2235. // console.log("用户离开");
  2236. if (this.liveUserTotal > 0) {
  2237. const userIdToRemove = socketMessage.userId;
  2238. const index = this.liveViewersData.findIndex(item => item.userId === userIdToRemove);
  2239. if (index !== -1) {
  2240. this.liveViewersData.splice(index, 1);
  2241. this.liveUserTotal--; // 根据userId删除对应的用户数据
  2242. }
  2243. }
  2244. this.inAndOut = socketMessage;
  2245. this.showWelcomeMessage = true;
  2246. // 3秒后隐藏提示
  2247. if (this.welcomeTimer) clearTimeout(this.welcomeTimer);
  2248. this.welcomeTimer = setTimeout(() => {
  2249. this.showWelcomeMessage = false;
  2250. }, 3000);
  2251. } else if (socketMessage.cmd == 'live_start' || socketMessage.cmd ==
  2252. 'live_end') {
  2253. // this.getliving(this.liveId);
  2254. // 开始直播,关闭直播
  2255. if (this.liveStartTimer) {
  2256. clearInterval(this.liveStartTimer);
  2257. this.liveStartTimer = null;
  2258. }
  2259. if (this.redTimer) {
  2260. clearInterval(this.redTimer);
  2261. this.redTimer = null;
  2262. }
  2263. // 2. 请求最新直播间数据
  2264. this.getliving(this.liveId); // 注意:需用 await 确保数据更新完成
  2265. // 3. 强制触发视图更新(兜底方案,若上述步骤仍不生效)
  2266. // this.$forceUpdate();
  2267. } else if (socketMessage.cmd == 'Integral') {
  2268. this.integral = {
  2269. msg: socketMessage.msg,
  2270. status: true
  2271. }
  2272. } else if (socketMessage.cmd == 'LotteryDetail') {
  2273. try {
  2274. // 1. 兜底空数据为 "[]",避免 JSON.parse(undefined) 报错
  2275. const parseData = socketMessage.data || '[]';
  2276. // 2. 解析 JSON 并捕获异常
  2277. const prizeData = JSON.parse(parseData);
  2278. // 3. 强制转为数组
  2279. this.prizeInfo = Array.isArray(prizeData) ? prizeData : [];
  2280. } catch (err) {
  2281. console.error('解析抽奖结果失败:', err);
  2282. // 4. 异常时兜底为数组
  2283. this.prizeInfo = [];
  2284. }
  2285. this.isShowPrize = true;
  2286. this.isShowLottery = false;
  2287. this.isShowLotteryPop = false;
  2288. } else if (socketMessage.cmd == 'blockUser') {
  2289. uni.removeStorage({
  2290. key: 'AppToken',
  2291. success: () => {
  2292. uni.reLaunch({
  2293. url: '/pages/auth/login'
  2294. });
  2295. }
  2296. });
  2297. }
  2298. } else {
  2299. uni.showToast({
  2300. title: data.msg,
  2301. icon: 'none'
  2302. });
  2303. }
  2304. },
  2305. sendMsg(retries = 1) {
  2306. // 防止连续点击发送两次(短时锁定)
  2307. if (this.isSending) return;
  2308. this.isSending = true;
  2309. setTimeout(() => {
  2310. this.isSending = false;
  2311. }, 800); // 800ms 内禁止再次发送
  2312. const text = (this.value || '').trim();
  2313. if (!text) {
  2314. uni.showToast({
  2315. title: "不能发送空消息",
  2316. icon: 'none'
  2317. });
  2318. return;
  2319. }
  2320. // 1. 连接状态校验:使用定义后的 retries
  2321. if (!this.isSocketAvailable()) {
  2322. if (retries > 0) {
  2323. uni.showToast({
  2324. title: `连接不稳定,正在重试(${retries}次)...`,
  2325. icon: 'none'
  2326. });
  2327. // 延迟500ms重试,重试次数减1
  2328. setTimeout(() => this.sendMsg(retries - 1), 500);
  2329. } else {
  2330. uni.showToast({
  2331. title: '连接已断开,发送失败',
  2332. icon: 'none'
  2333. });
  2334. this.value = text; // 恢复输入框内容
  2335. }
  2336. return;
  2337. }
  2338. const liveId = this.liveId;
  2339. this.value = ''; // 立即清空输入框,提升体验
  2340. // 构造发送给服务端的消息数据
  2341. const data = {
  2342. liveId,
  2343. userId: this.userData.userId,
  2344. userType: 0,
  2345. cmd: "sendMsg",
  2346. msg: text,
  2347. nickName: this.userData.nickname || '未命名',
  2348. avatar: this.userData.avatar || '/static/images/avatar.png'
  2349. };
  2350. // 发送socket消息
  2351. try {
  2352. this.socket.send({
  2353. data: JSON.stringify(data),
  2354. success: () => {
  2355. // console.log("发送成功");
  2356. this.value = '';
  2357. },
  2358. fail: (err) => {
  2359. console.error("消息发送失败:", err);
  2360. // 2. 发送失败重试:使用定义后的 retries
  2361. if (retries > 0) {
  2362. uni.showToast({
  2363. title: `发送失败,正在重试(${retries}次)`,
  2364. icon: 'none'
  2365. });
  2366. setTimeout(() => this.sendMsg(retries - 1), 500);
  2367. } else {
  2368. uni.showToast({
  2369. title: '发送失败,请稍后再试',
  2370. icon: 'none'
  2371. });
  2372. this.value = text; // 恢复输入框内容
  2373. }
  2374. }
  2375. });
  2376. } catch (err) {
  2377. console.error("发送消息异常:", err);
  2378. if (retries > 0) {
  2379. setTimeout(() => this.sendMsg(retries - 1), 500);
  2380. } else {
  2381. uni.showToast({
  2382. title: '发送失败,请稍后再试',
  2383. icon: 'none'
  2384. });
  2385. this.value = text;
  2386. }
  2387. }
  2388. }
  2389. }
  2390. };
  2391. </script>
  2392. <style scoped lang="scss">
  2393. ::v-deep .u-icon--right {
  2394. justify-content: flex-end !important;
  2395. }
  2396. // 无头像用户文字样式
  2397. .text-white {
  2398. color: #ffffff;
  2399. }
  2400. .text-xs {
  2401. font-size: 16rpx;
  2402. }
  2403. .text-sm {
  2404. font-size: 24rpx;
  2405. }
  2406. .w52,
  2407. .w72 {
  2408. display: flex;
  2409. align-items: center;
  2410. justify-content: center;
  2411. }
  2412. .swiper-wrapper {
  2413. position: relative;
  2414. width: 100%;
  2415. height: 100vh;
  2416. overflow: hidden;
  2417. background-color: #000000;
  2418. .container {
  2419. width: 100%;
  2420. height: 100%;
  2421. position: relative;
  2422. transition: opacity 0.3s ease;
  2423. transform: translateZ(0);
  2424. will-change: opacity;
  2425. }
  2426. }
  2427. .loading-tip {
  2428. position: absolute;
  2429. top: 50%;
  2430. left: 50%;
  2431. transform: translate(-50%, -50%);
  2432. display: flex;
  2433. flex-direction: column;
  2434. align-items: center;
  2435. justify-content: center;
  2436. z-index: 10;
  2437. .loading-text {
  2438. color: #ffffff;
  2439. font-size: 28rpx;
  2440. margin-top: 20rpx;
  2441. }
  2442. }
  2443. /* button自带样式清除 */
  2444. button::after {
  2445. border: none !important;
  2446. padding: 0 !important;
  2447. margin: 0 !important;
  2448. }
  2449. button {
  2450. background-color: transparent !important;
  2451. padding: 0 !important;
  2452. line-height: inherit !important;
  2453. margin: 0 !important;
  2454. width: auto !important;
  2455. font-weight: 500 !important;
  2456. border-radius: none !important;
  2457. }
  2458. .welcome-message {
  2459. position: fixed;
  2460. width: 100%;
  2461. bottom: 38vh;
  2462. left: 50%;
  2463. transform: translateX(-50%);
  2464. color: white;
  2465. padding: 10px 20px;
  2466. border-radius: 20px;
  2467. z-index: 10;
  2468. transition: opacity 0.3s ease;
  2469. }
  2470. .send {
  2471. background-color: #fafafa;
  2472. border-radius: 28rpx;
  2473. padding: 14rpx 16rpx;
  2474. color: #181818;
  2475. font-weight: 500;
  2476. }
  2477. .talk-list {
  2478. max-width: 100%;
  2479. border-radius: 30rpx;
  2480. background-color: rgba(33, 33, 33, 0.5);
  2481. padding: 10rpx 30rpx;
  2482. }
  2483. .content {
  2484. position: relative;
  2485. z-index: 2;
  2486. height: 100%;
  2487. width: 100%;
  2488. top: 0;
  2489. left: 0;
  2490. display: flex;
  2491. flex-direction: column;
  2492. justify-content: space-between;
  2493. .activity-box {
  2494. position: fixed;
  2495. top: 188rpx;
  2496. left: 30rpx;
  2497. z-index: 5;
  2498. display: flex;
  2499. align-items: center;
  2500. .item-box {
  2501. border-radius: 16rpx;
  2502. background-color: rgba(77, 77, 77, 0.5);
  2503. width: 90rpx;
  2504. height: 100rpx;
  2505. margin-right: 20rpx;
  2506. position: relative;
  2507. z-index: 999;
  2508. .tip {
  2509. position: absolute;
  2510. width: 100%;
  2511. bottom: 0;
  2512. color: #fafcff;
  2513. font-size: 26rpx;
  2514. background-color: rgba(15, 15, 15, 0.8);
  2515. border-radius: 16rpx;
  2516. text-align: center;
  2517. }
  2518. .item {
  2519. margin: 0 auto;
  2520. padding: 10rpx 0;
  2521. .img {
  2522. height: 100%;
  2523. }
  2524. }
  2525. }
  2526. }
  2527. .side-group {
  2528. position: absolute;
  2529. top: 65%;
  2530. right: 30rpx;
  2531. z-index: 1000;
  2532. display: flex;
  2533. flex-direction: column;
  2534. align-items: center;
  2535. .side-item {
  2536. font-weight: 500;
  2537. font-size: 24rpx;
  2538. color: #FFFFFF;
  2539. margin-bottom: 32rpx;
  2540. text-align: center;
  2541. .image {
  2542. width: 72rpx;
  2543. height: 72rpx;
  2544. }
  2545. }
  2546. }
  2547. .content-top {
  2548. width: 100%;
  2549. margin-top: 48rpx;
  2550. display: flex;
  2551. justify-content: space-between;
  2552. padding: 0 24rpx;
  2553. box-sizing: border-box;
  2554. .sum {
  2555. width: 80rpx;
  2556. height: 52rpx;
  2557. background: rgba(0, 0, 0, 0.5);
  2558. border-radius: 26rpx 26rpx 26rpx 26rpx;
  2559. font-size: 24rpx;
  2560. color: #FFFFFF;
  2561. text-align: center;
  2562. line-height: 52rpx;
  2563. }
  2564. }
  2565. .follow-btn {
  2566. padding: 8rpx 16rpx;
  2567. background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
  2568. border-radius: 26rpx;
  2569. font-weight: 500;
  2570. font-size: 26rpx;
  2571. color: #FFFFFF;
  2572. }
  2573. }
  2574. .trailer-box {
  2575. position: relative;
  2576. top: 15%;
  2577. display: flex;
  2578. flex-direction: column;
  2579. align-items: center;
  2580. color: #ffffff;
  2581. padding: 20rpx;
  2582. .button {
  2583. margin-top: 20rpx;
  2584. background: #6d7bd4;
  2585. color: #fff;
  2586. border-radius: 20rpx;
  2587. padding: 20rpx 30rpx;
  2588. position: relative;
  2589. z-index: 99999;
  2590. }
  2591. .ash {
  2592. background: #636363;
  2593. }
  2594. .countdown-item {
  2595. display: flex;
  2596. flex-direction: column;
  2597. align-items: center;
  2598. .white {
  2599. width: 60rpx;
  2600. height: 60rpx;
  2601. text-align: center;
  2602. overflow: hidden;
  2603. background: #FFFFFF;
  2604. border-radius: 8rpx;
  2605. margin: 30rpx 10rpx 0;
  2606. font-weight: 600;
  2607. font-size: 24rpx;
  2608. color: #000000;
  2609. line-height: 60rpx;
  2610. }
  2611. }
  2612. .item {
  2613. width: 100%;
  2614. height: 400rpx;
  2615. }
  2616. .name {
  2617. font-size: 34rpx;
  2618. }
  2619. .img {
  2620. margin-bottom: 40rpx;
  2621. width: 240rpx;
  2622. height: 240rpx;
  2623. }
  2624. .title {
  2625. margin-top: 30rpx;
  2626. font-size: 42rpx;
  2627. font-weight: 500;
  2628. }
  2629. }
  2630. .videolist {
  2631. position: relative;
  2632. height: 100vh;
  2633. width: 100%;
  2634. .video {
  2635. height: 100vh;
  2636. width: 100%;
  2637. background-color: rgba(57, 57, 57, 0.4);
  2638. .item {
  2639. width: 100%;
  2640. height: 100%;
  2641. }
  2642. .time {
  2643. color: #ffffff;
  2644. font-size: 20rpx;
  2645. margin-left: 10rpx;
  2646. }
  2647. .lable {
  2648. position: absolute;
  2649. top: 50rpx;
  2650. right: 16rpx;
  2651. background-color: rgba(57, 57, 57, 0.6);
  2652. padding: 4rpx 10rpx;
  2653. color: #fff;
  2654. border-radius: 15rpx;
  2655. }
  2656. }
  2657. .video_row {
  2658. position: absolute;
  2659. top: 20%;
  2660. max-height: 450rpx;
  2661. z-index: 99;
  2662. }
  2663. }
  2664. .prize-card {
  2665. width: 504rpx;
  2666. padding: 40rpx 40rpx 30rpx;
  2667. box-sizing: border-box;
  2668. display: flex;
  2669. flex-direction: column;
  2670. border-radius: 20rpx;
  2671. align-items: center;
  2672. background: linear-gradient(180deg, #f7823f 0%, #ffd4be 27%, #ffffff 100%);
  2673. position: relative;
  2674. .nav-img {
  2675. width: 311rpx;
  2676. position: absolute;
  2677. top: -122rpx;
  2678. left: 50%;
  2679. transform: translateX(-50%);
  2680. }
  2681. .title {
  2682. color: #C32008;
  2683. font-size: 34rpx;
  2684. font-weight: 600;
  2685. margin: 20rpx 0 40rpx;
  2686. }
  2687. .prize-content {
  2688. width: 100%;
  2689. display: flex;
  2690. justify-content: space-between;
  2691. align-items: center;
  2692. font-size: 28rpx;
  2693. margin: 10rpx 0;
  2694. .txt {
  2695. font-weight: 600;
  2696. }
  2697. }
  2698. .tip {
  2699. font-size: 28rpx;
  2700. color: #414141;
  2701. margin: 40rpx 0;
  2702. }
  2703. .button {
  2704. width: 200rpx;
  2705. height: 70rpx;
  2706. line-height: 70rpx;
  2707. background: linear-gradient(180deg, #ff7c30 0%, #FF3A1E 100%);
  2708. border-radius: 28rpx;
  2709. font-weight: 500;
  2710. font-size: 32rpx;
  2711. color: #ffffff;
  2712. text-align: center;
  2713. }
  2714. }
  2715. .no-prize-card {
  2716. width: 504rpx;
  2717. padding: 40rpx 40rpx 30rpx;
  2718. box-sizing: border-box;
  2719. display: flex;
  2720. flex-direction: column;
  2721. border-radius: 20rpx;
  2722. align-items: center;
  2723. position: relative;
  2724. .img {
  2725. margin-top: 40rpx;
  2726. width: 300rpx;
  2727. height: 300rpx;
  2728. }
  2729. .tip {
  2730. font-size: 36rpx;
  2731. color: #414141;
  2732. margin: 40rpx 0;
  2733. }
  2734. .button {
  2735. width: 220rpx;
  2736. height: 80rpx;
  2737. line-height: 80rpx;
  2738. background: linear-gradient(180deg, #fdfbb8 0%, #b79243 100%);
  2739. border-radius: 28rpx;
  2740. font-weight: 500;
  2741. font-size: 32rpx;
  2742. color: #ffffff;
  2743. text-align: center;
  2744. }
  2745. }
  2746. .red-card {
  2747. width: 550rpx;
  2748. height: 636rpx;
  2749. position: relative;
  2750. .img {
  2751. position: absolute;
  2752. width: 100%;
  2753. height: 100%;
  2754. }
  2755. .red-content {
  2756. position: relative;
  2757. z-index: 5;
  2758. display: flex;
  2759. flex-direction: column;
  2760. align-items: center;
  2761. .title {
  2762. font-size: 36rpx;
  2763. color: #FF3A1E;
  2764. margin: 180rpx 0 90rpx;
  2765. }
  2766. .txt {
  2767. font-size: 28rpx;
  2768. color: #FFECC3;
  2769. margin: 80rpx 0 40rpx;
  2770. }
  2771. .button {
  2772. width: 392rpx;
  2773. height: 96rpx;
  2774. line-height: 96rpx;
  2775. background: linear-gradient(180deg, #FFF4D5 0%, #FFE5B1 100%);
  2776. border-radius: 48rpx 48rpx 48rpx 48rpx;
  2777. font-weight: 600;
  2778. font-size: 36rpx;
  2779. color: #C32008;
  2780. text-align: center;
  2781. }
  2782. }
  2783. }
  2784. .integral-box {
  2785. min-width: 400rpx;
  2786. max-width: 600rpx;
  2787. display: flex;
  2788. flex-direction: column;
  2789. align-items: center;
  2790. border-radius: 20rpx;
  2791. overflow: hidden;
  2792. .top {
  2793. width: 100%;
  2794. position: relative;
  2795. .title {
  2796. width: 100%;
  2797. font-weight: 600;
  2798. font-size: 40rpx;
  2799. color: #FFFFFF;
  2800. text-shadow: 0px 4px 8px rgba(255, 89, 2, 0.8);
  2801. position: absolute;
  2802. top: 50rpx;
  2803. text-align: center;
  2804. }
  2805. .photo {
  2806. width: 100%;
  2807. }
  2808. }
  2809. .item {
  2810. padding: 20rpx;
  2811. .title {
  2812. font-weight: 500;
  2813. font-size: 32rpx;
  2814. text-align: center;
  2815. }
  2816. .button {
  2817. font-size: 32rpx;
  2818. margin-top: 20rpx;
  2819. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  2820. color: #fff;
  2821. text-align: center;
  2822. padding: 18rpx 60rpx;
  2823. border-radius: 10rpx;
  2824. font-weight: 500;
  2825. }
  2826. }
  2827. }
  2828. .goods {
  2829. position: fixed;
  2830. bottom: 140rpx;
  2831. right: 104rpx;
  2832. z-index: 5;
  2833. background-color: #fff;
  2834. border-radius: 20rpx;
  2835. overflow: hidden;
  2836. width: 280rpx;
  2837. padding: 4rpx;
  2838. .top {
  2839. position: absolute;
  2840. top: 4rpx;
  2841. display: flex;
  2842. justify-content: space-between;
  2843. align-items: center;
  2844. color: #fff;
  2845. width: 100%;
  2846. padding-right: 10rpx;
  2847. box-sizing: border-box;
  2848. .left {
  2849. background-color: rgba(0, 0, 0, 0.8);
  2850. padding: 12rpx;
  2851. font-size: 22rpx;
  2852. display: flex;
  2853. justify-content: space-between;
  2854. align-items: center;
  2855. border-radius: 10rpx;
  2856. }
  2857. }
  2858. .photo {
  2859. width: 100%;
  2860. height: 180rpx;
  2861. border-radius: 16rpx 16rpx 0 0;
  2862. overflow: hidden;
  2863. }
  2864. .item {
  2865. padding: 4rpx;
  2866. .price {
  2867. font-size: 30rpx;
  2868. .red {
  2869. color: #FF5701;
  2870. font-weight: 600;
  2871. margin-right: 10rpx;
  2872. }
  2873. .del {
  2874. color: #828282;
  2875. font-weight: 500;
  2876. font-size: 28rpx;
  2877. text-decoration: line-through
  2878. }
  2879. }
  2880. .title {
  2881. font-weight: 500;
  2882. font-size: 30rpx;
  2883. margin: 10rpx 0 12rpx;
  2884. }
  2885. .button {
  2886. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  2887. color: #fff;
  2888. text-align: center;
  2889. padding: 16rpx 0;
  2890. border-radius: 10rpx;
  2891. font-weight: 500;
  2892. font-size: 30rpx;
  2893. }
  2894. }
  2895. }
  2896. .coupon-pop {
  2897. position: fixed;
  2898. bottom: 140rpx;
  2899. right: 100rpx;
  2900. z-index: 5;
  2901. border-radius: 20rpx;
  2902. width: 320rpx;
  2903. .coupon-block {
  2904. width: 100%;
  2905. position: relative;
  2906. .item {
  2907. width: 100%;
  2908. position: absolute;
  2909. top: 20rpx;
  2910. display: flex;
  2911. flex-direction: column;
  2912. align-items: center;
  2913. color: #fff;
  2914. .title {
  2915. font-weight: 500;
  2916. font-size: 30rpx;
  2917. margin: 16rpx 0 12rpx;
  2918. }
  2919. .price {
  2920. font-size: 40rpx;
  2921. .bold {
  2922. font-size: 56rpx;
  2923. font-weight: 600;
  2924. }
  2925. }
  2926. .txt {
  2927. font-weight: 500;
  2928. font-size: 30rpx;
  2929. margin: 5rpx 0;
  2930. }
  2931. .button {
  2932. background: linear-gradient(270deg, #fffce1 0%, #ffeaaf 100%);
  2933. color: #ff0004;
  2934. text-align: center;
  2935. padding: 16rpx 0;
  2936. border-radius: 40rpx;
  2937. font-weight: 500;
  2938. font-size: 30rpx;
  2939. width: 70%;
  2940. margin-top: 26rpx;
  2941. }
  2942. }
  2943. .bg {
  2944. height: 432rpx;
  2945. width: 100%;
  2946. }
  2947. .nav {
  2948. position: absolute;
  2949. height: 120rpx;
  2950. top: -120rpx;
  2951. left: 0;
  2952. width: 100%;
  2953. z-index: 6;
  2954. }
  2955. .close {
  2956. position: absolute;
  2957. right: 10rpx;
  2958. top: 10rpx;
  2959. }
  2960. }
  2961. }
  2962. .icon-bg {
  2963. background-color: rgba(57, 57, 57, 0.8);
  2964. border-radius: 50%;
  2965. width: 88rpx;
  2966. height: 88rpx;
  2967. display: flex;
  2968. justify-content: center;
  2969. align-items: center;
  2970. transition: transform 0.2s ease;
  2971. }
  2972. .list {
  2973. width: 80%;
  2974. margin-bottom: 20rpx;
  2975. animation: xxxawdawd .2s;
  2976. }
  2977. @keyframes xxxawdawd {
  2978. from {
  2979. margin-top: 0rpx;
  2980. opacity: 0;
  2981. }
  2982. to {
  2983. // margin-top: 20rpx;
  2984. opacity: 1;
  2985. }
  2986. }
  2987. .shop-prompt {
  2988. position: absolute;
  2989. bottom: 750rpx;
  2990. left: 24rpx;
  2991. padding: 6rpx 20rpx;
  2992. background: rgba(230, 154, 34, 0.7);
  2993. border-radius: 24rpx;
  2994. z-index: 9;
  2995. font-weight: 500;
  2996. color: #FFFFFF;
  2997. transition: opacity 0.3s ease;
  2998. }
  2999. .red-box {
  3000. .button {
  3001. margin: 0 auto;
  3002. width: 80%;
  3003. line-height: 88rpx;
  3004. height: 88rpx;
  3005. background: linear-gradient(90deg, #FF5701 0%, #FFB501 100%);
  3006. box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(238, 124, 80, 0.2);
  3007. border-radius: 44rpx 44rpx 44rpx 44rpx;
  3008. font-weight: 600;
  3009. font-size: 32rpx;
  3010. color: #FFFFFF;
  3011. text-align: center;
  3012. }
  3013. }
  3014. .view-box {
  3015. position: relative;
  3016. height: 40vh;
  3017. /* 设置弹出层高度为视窗高度的70% */
  3018. padding: 40rpx 0rpx 120rpx;
  3019. box-sizing: border-box;
  3020. display: flex;
  3021. flex-direction: column;
  3022. .scroll-content {
  3023. flex: 1;
  3024. overflow-y: auto;
  3025. padding: 0 40rpx;
  3026. }
  3027. .bottom {
  3028. padding: 20rpx 40rpx;
  3029. position: absolute;
  3030. bottom: 0;
  3031. width: 100%;
  3032. box-shadow: 0rpx -4rpx 10rpx 0rpx rgba(195, 195, 195, 0.3);
  3033. background: #fff;
  3034. }
  3035. }
  3036. // 抽奖
  3037. .prize-box {
  3038. position: relative;
  3039. .nav-img {
  3040. width: 311rpx;
  3041. position: absolute;
  3042. top: -122rpx;
  3043. left: 50%;
  3044. transform: translateX(-50%);
  3045. }
  3046. .bg-img {
  3047. position: absolute;
  3048. top: 0;
  3049. left: 0;
  3050. width: 100%;
  3051. height: 100%;
  3052. z-index: 1;
  3053. }
  3054. .prize-content {
  3055. position: relative;
  3056. z-index: 2;
  3057. padding: 24rpx 0 68rpx;
  3058. .white-item {
  3059. width: 40rpx;
  3060. height: 40rpx;
  3061. text-align: center;
  3062. overflow: hidden;
  3063. background: #FFFFFF;
  3064. box-shadow: inset 0rpx 2rpx 8rpx 0rpx #FFEBB2;
  3065. border-radius: 8rpx;
  3066. margin: 4rpx;
  3067. font-weight: 600;
  3068. font-size: 24rpx;
  3069. color: #F85D22;
  3070. line-height: 40rpx;
  3071. }
  3072. .item-group {
  3073. width: 100%;
  3074. }
  3075. .point-group {
  3076. margin: 20rpx 0 50rpx;
  3077. display: flex;
  3078. gap: 6rpx;
  3079. .item {
  3080. width: 20rpx;
  3081. height: 8rpx;
  3082. background: rgba(255, 255, 255, 0.5);
  3083. border-radius: 4rpx 4rpx 4rpx 4rpx;
  3084. }
  3085. .selected {
  3086. background: #FFEB66;
  3087. }
  3088. }
  3089. .button {
  3090. margin-top: 30rpx;
  3091. width: 520rpx;
  3092. height: 88rpx;
  3093. line-height: 88rpx;
  3094. background: linear-gradient(180deg, #FFF4D6 0%, #FFEB66 100%);
  3095. box-shadow: 0rpx 10rpx 8rpx 4rpx rgba(246, 82, 25, 0.5);
  3096. border-radius: 44rpx;
  3097. font-weight: 500;
  3098. font-size: 36rpx;
  3099. color: #F4410B;
  3100. text-align: center;
  3101. }
  3102. }
  3103. }
  3104. .shoppop {
  3105. padding: 22rpx 16rpx;
  3106. .shoppop-top {
  3107. display: flex;
  3108. justify-content: space-between;
  3109. align-items: center;
  3110. padding: 0 16rpx 22rpx;
  3111. .search-input {
  3112. width: 414rpx;
  3113. height: 76rpx;
  3114. background: #FFFFFF;
  3115. border-radius: 36rpx;
  3116. margin-left: 20rpx;
  3117. padding: 0 32rpx;
  3118. box-sizing: border-box;
  3119. font-size: 24rpx;
  3120. margin-right: 24rpx;
  3121. }
  3122. .search-top {
  3123. font-size: 20rpx;
  3124. color: #222222;
  3125. }
  3126. }
  3127. .shop-list {
  3128. overflow: hidden;
  3129. .list-item {
  3130. display: flex;
  3131. align-items: center;
  3132. padding: 20rpx 16rpx;
  3133. background: #FFFFFF;
  3134. border-radius: 16rpx;
  3135. margin-bottom: 16rpx;
  3136. .goods-img {
  3137. width: 200rpx;
  3138. height: 200rpx;
  3139. border-radius: 16rpx;
  3140. overflow: hidden;
  3141. position: relative;
  3142. margin-right: 24rpx;
  3143. .img {
  3144. width: 100%;
  3145. height: 100%;
  3146. }
  3147. .goods-label {
  3148. position: absolute;
  3149. top: 0;
  3150. width: 64rpx;
  3151. height: 40rpx;
  3152. background: rgba(0, 0, 0, 0.5);
  3153. border-radius: 16rpx 0rpx 16rpx 0rpx;
  3154. text-align: center;
  3155. font-weight: 500;
  3156. font-size: 28rpx;
  3157. color: #FFFFFF;
  3158. }
  3159. }
  3160. .goods-right {
  3161. flex: 1;
  3162. .goods-title {
  3163. font-weight: 500;
  3164. font-size: 30rpx;
  3165. color: #000000;
  3166. margin-bottom: 10rpx;
  3167. }
  3168. .goods-details {
  3169. font-size: 24rpx;
  3170. color: #999999;
  3171. margin: 10rpx 0 20rpx;
  3172. }
  3173. .goods-people {
  3174. font-size: 22rpx;
  3175. color: #E69A22;
  3176. height: 56rpx;
  3177. }
  3178. .goods-shop {
  3179. display: flex;
  3180. justify-content: space-between;
  3181. .nummber {
  3182. color: #FF5C03;
  3183. font-size: 22rpx;
  3184. font-weight: 500;
  3185. }
  3186. .btn-group {
  3187. text-align: center;
  3188. line-height: 56rpx;
  3189. .collect-btn {
  3190. width: 72rpx;
  3191. height: 100%;
  3192. background: #F5F7FA;
  3193. border-radius: 8rpx 0rpx 0rpx 8rpx;
  3194. }
  3195. .shop-btn {
  3196. width: 152rpx;
  3197. background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
  3198. border-radius: 0rpx 8rpx 8rpx 0rpx;
  3199. font-weight: 500;
  3200. font-size: 30rpx;
  3201. color: #FFFFFF;
  3202. }
  3203. }
  3204. }
  3205. }
  3206. }
  3207. }
  3208. }
  3209. </style>