living.vue 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448
  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" src="/static/images/return3.png" />
  8. <view class="align-center" style="padding: 6rpx 8rpx; height: 64rpx; background: rgba(0, 0, 0, 0.5); border-radius: 32rpx">
  9. <u-avatar :src="liveItem.liveImgUrl || '/static/images/avatar.png'" :size="32"></u-avatar>
  10. <view class="colorf ml10 mr6">
  11. <view>{{ liveItem.liveName ? truncateString(liveItem.liveName, 8) : '未命名' }}</view>
  12. </view>
  13. </view>
  14. </view>
  15. <view v-if="Array.isArray(filteredViewers)" class="align-center" @click="toggleViewerList" style="margin-top: 120rpx">
  16. <view v-for="(item, viewerIndex) in filteredViewers" :key="viewerIndex">
  17. <image v-if="item.avatar" class="w52 h52 mr4" style="border-radius: 26rpx" :src="item.avatar" />
  18. <view v-else class="w52 h52 mr4" :style="{ backgroundColor: getUserRandomColor(item.userId), borderRadius: '50%' }">
  19. <text class="text-white text-xs">{{ getNicknameInitial(item.nickName) }}</text>
  20. </view>
  21. </view>
  22. <view class="sum">{{ liveUserTotal || 0 }}</view>
  23. </view>
  24. </view>
  25. <!-- 右边的side -->
  26. <view class="side-group">
  27. <view class="side-item" @click="onLike">
  28. <LikeButton :initialCount="100" :heartsPerClick="5" @like="onLike" />
  29. <view>{{ (liveViewData && liveViewData.like) || 0 }}</view>
  30. </view>
  31. <view class="side-item">
  32. <button open-type="share" class="button button-reset">
  33. <image class="image" src="/static/images/weixin.png" mode="widthFix" />
  34. </button>
  35. <view>分享</view>
  36. </view>
  37. </view>
  38. <view class="activity-box">
  39. <view class="item-box" @click="onRed()" v-if="isShowRed">
  40. <view class="x-f">
  41. <view class="tip">领红包</view>
  42. <view class="item">
  43. <image class="w70 img" src="/static/images/redbag.png" mode="widthFix" />
  44. </view>
  45. </view>
  46. </view>
  47. <view class="item-box" @click="onLottery()" v-if="isShowLottery && countdown">
  48. <view class="x-f">
  49. <view class="tip">抽奖</view>
  50. <view class="item">
  51. <image class="w60" src="/static/images/lottery.png" mode="widthFix" />
  52. </view>
  53. </view>
  54. </view>
  55. </view>
  56. <view class="shop-prompt f30 x-f" v-if="showPurchasePrompt && orderUser && orderUser.count && liveItem.status == 2">
  57. <image class="w32 h32 mr8" src="/static/images/shopping.png" />
  58. <text>{{ orderUser.count || 0 }}人正在去购买</text>
  59. </view>
  60. <view class="videolist" v-if="liveItem.status == 2">
  61. <view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
  62. <!-- 直播 -->
  63. <live-player
  64. v-if="liveItem.livingUrl && liveItem.liveType == 1"
  65. :id="'myLivePlayer_' + liveId"
  66. :src="liveItem.livingUrl"
  67. autoplay
  68. mode="live"
  69. object-fit="contain"
  70. :muted="false"
  71. orientation="vertical"
  72. :enable-play-gesture="false"
  73. min-cache="1"
  74. max-cache="3"
  75. @statechange="onLiveStateChange($event, liveItem)"
  76. @error="onLiveError($event, liveItem)"
  77. class="item"
  78. ></live-player>
  79. <!-- 录播 -->
  80. <video
  81. v-if="liveItem.videoUrl && liveItem.liveType == 2"
  82. :id="`myVideo_${liveId}`"
  83. :autoplay="true"
  84. class="item"
  85. :src="liveItem.videoUrl"
  86. :controls="false"
  87. object-fit="contain"
  88. :custom-cache="false"
  89. :enable-progress-gesture="false"
  90. vslide-gesture-in-fullscreen="false"
  91. :show-center-play-btn="false"
  92. :http-cache="false"
  93. loop
  94. @error="videoError"
  95. @timeupdate="onVideoTimeUpdate"
  96. @loadedmetadata="onVideoMetaLoaded"
  97. @pause="onVideoPause"
  98. @play="onVideoPlay"
  99. @waiting="onVideoWaiting"
  100. :enable-play-gesture="false"
  101. :play-strategy="1"
  102. @dblclick="preventDoubleClick"
  103. preload="auto"
  104. :enable-stash-buffer="false"
  105. :stash-initial-size="0"
  106. :stash-max-size="0"
  107. :stash-time="0"
  108. type="application/x-mpegURL"
  109. ></video>
  110. <view v-if="liveItem.videoUrl && liveItem.liveType == 2" class="time">{{ diffTotalTime }}</view>
  111. </view>
  112. </view>
  113. <view class="videolist" v-if="liveItem.status == 3">
  114. <view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
  115. <view class="end">直播已结束</view>
  116. </view>
  117. </view>
  118. <view class="videolist" v-if="liveItem.status == 4">
  119. <view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
  120. <!-- 直播回放 -->
  121. <video
  122. v-if="liveItem.videoUrl && liveItem.liveType == 3"
  123. :id="`myVideo_${liveId}`"
  124. class="item"
  125. :src="liveItem.videoUrl"
  126. :autoplay="true"
  127. :controls="true"
  128. object-fit="contain"
  129. :custom-cache="false"
  130. :enable-progress-gesture="liveItem.isSpeedAllowed"
  131. vslide-gesture-in-fullscreen="true"
  132. :show-center-play-btn="true"
  133. :http-cache="false"
  134. loop
  135. @error="videoError"
  136. @timeupdate="onVideoTimeUpdate"
  137. @loadedmetadata="onVideoMetaLoaded"
  138. @pause="onVideoPause"
  139. @play="onVideoPlay"
  140. :enable-play-gesture="true"
  141. preload="auto"
  142. @waiting="onVideoWaiting"
  143. type="application/x-mpegURL"
  144. ></video>
  145. <view v-if="liveItem.videoUrl && liveItem.liveType == 3" class="lable">直播回放</view>
  146. </view>
  147. </view>
  148. <view class="trailer-box" v-if="liveItem.status == 1">
  149. <video
  150. v-if="liveItem.previewUrl"
  151. :id="`myVideo_${liveId}`"
  152. class="item"
  153. :src="liveItem.previewUrl"
  154. :autoplay="true"
  155. :loop="false"
  156. :controls="false"
  157. object-fit="contain"
  158. :custom-cache="false"
  159. :enable-progress-gesture="false"
  160. vslide-gesture-in-fullscreen="false"
  161. :show-center-play-btn="false"
  162. :http-cache="false"
  163. @error="videoError"
  164. @loadedmetadata="onVideoMetaLoaded"
  165. @pause="onVideoPause"
  166. @play="onVideoPlay"
  167. :disable-progress="true"
  168. :enable-play-gesture="true"
  169. @waiting="onVideoWaiting"
  170. preload="auto"
  171. type="application/x-mpegURL"
  172. ></video>
  173. <image v-if="liveItem.status == 1 && !liveItem.previewUrl" class="img" src="/static/images/no_live.png"></image>
  174. <view class="countdown-item mt30 mb30" v-if="liveItem.status == 1 && liveCountdown">
  175. 开播倒计时
  176. <view class="x-f">
  177. <view class="white">
  178. {{ liveCountdown.hours || '00' }}
  179. </view>
  180. <view class="white">
  181. {{ liveCountdown.minutes || '00' }}
  182. </view>
  183. <view class="white">
  184. {{ liveCountdown.seconds || '00' }}
  185. </view>
  186. </view>
  187. </view>
  188. <view class="name">{{ liveItem.liveName }}</view>
  189. <view class="title" v-if="liveCountdown">暂未开播</view>
  190. <view class="button" v-if="!isAgreement" @click="handleAgreement">预约直播</view>
  191. <view class="button ash" v-if="isAgreement">已预约</view>
  192. <view class="title" v-if="!liveCountdown">主播还在来的路上</view>
  193. </view>
  194. <view class="trailer-box" v-if="!liveItem">
  195. <image class="img" src="/static/images/no_live.png"></image>
  196. <view class="title">暂无直播</view>
  197. </view>
  198. <!-- 底部聊天区域 -->
  199. <view :style="{
  200. position: 'fixed',
  201. width: '100%',
  202. bottom: (isFocus && isKeyboardShow) ? keyboardHeight + 'rpx' : '0',
  203. zIndex: 999,
  204. backgroundColor: 'transparent'
  205. }">
  206. <view class="mt20" :style="{ height: isFocus ? '64rpx' : '30vh' }">
  207. <scroll-view
  208. id="msgScroll"
  209. v-if="Array.isArray(talklist)"
  210. enable-flex
  211. scroll-y="true"
  212. :enhanced="true"
  213. :bounces="false"
  214. :show-scrollbar="false"
  215. :fast-deceleration="false"
  216. :enable-back-to-top="false"
  217. class="pl20 scrolly flex-1 column"
  218. style="width: calc(100% - 20rpx); height: 100%; -webkit-overflow-scrolling: touch"
  219. :scroll-top="scrollTop"
  220. ref="scrollView">
  221. <view
  222. class="list justify-start"
  223. v-for="(item, talkIndex) in talklist || []"
  224. :key="talkIndex"
  225. :id="`list_${talkIndex}`"
  226. v-show="item.cmd != 'red' && item.cmd != 'out' && item.cmd != 'entry'">
  227. <view class="talk-list justify-start">
  228. <view class="fs30" style="max-width: 100%">
  229. <text style="color: #ffda73">{{ item.nickName || '未命名' }}:</text>
  230. <text class="colorf">{{ item.msg }}</text>
  231. </view>
  232. </view>
  233. </view>
  234. <view v-if="showWelcomeMessage" class="welcome-message" style="max-width: 100%">
  235. <view class="list justify-start" v-show="inAndOut.cmd == 'entry' || inAndOut.cmd == 'out'">
  236. <view class="talk-list justify-start">
  237. <view class="fs30">
  238. <text style="color: #ff89d6">{{ inAndOut.nickName || '未命名' }}</text>
  239. <text class="colorf">{{ inAndOut.msg }}直播间</text>
  240. </view>
  241. </view>
  242. </view>
  243. </view>
  244. </scroll-view>
  245. </view>
  246. <!-- 底部输入框和操作按钮 -->
  247. <view class="justify-between p24" :style="{
  248. backgroundColor: 'rgba(0, 0, 0, 0.8)',
  249. paddingBottom: isFocus && isKeyboardShow ? '24rpx' : '24rpx'
  250. }">
  251. <view
  252. class="x-f justify-between"
  253. :style="{
  254. background: '#393939',
  255. padding: '10rpx 14rpx 10rpx 32rpx',
  256. boxSizing: 'border-box',
  257. borderRadius: '36rpx',
  258. width: isFocus ? '100%' : '580rpx'
  259. }">
  260. <input
  261. id="txtMsg"
  262. :placeholder="placeholderText"
  263. v-model="value"
  264. placeholder-style="color:#e7e7e7;"
  265. placeholder-class="placeholder-style"
  266. class="ml20 input-native"
  267. @focus="inputFocus"
  268. @blur="inputBlur"
  269. style="border: none; font-size: 32rpx; color: #ffffff; background: transparent; width: 70%"
  270. cursor-spacing="100"
  271. :adjust-position="false"/>
  272. <view class="send" @click="sendMsg()">发送</view>
  273. </view>
  274. <view class="justify-between mr15 align-center" v-if="!isFocus">
  275. <view class="icon-bg ml20" @tap="openCart()">
  276. <image src="/static/images/shopping.png" class="w58 h58" />
  277. </view>
  278. </view>
  279. </view>
  280. </view>
  281. </view>
  282. <view class="goods" v-if="isShowGoods">
  283. <view class="top">
  284. <view class="left">
  285. <image class="w30 h30 mr8" src="/static/images/signal.png" />
  286. 讲解中
  287. </view>
  288. <image @click="isShowGoods = false" class="w40 h40" src="/static/images/del_black.png" />
  289. </view>
  290. <image class="photo" :src="goodsCard.imgUrl" />
  291. <view class="item" @click="goShop(goodsCard.productId, goodsCard.goodsId)">
  292. <view class="price">
  293. <text class="red">¥{{ goodsCard.price }}</text>
  294. <text class="del">¥{{ goodsCard.otPrice }}</text>
  295. </view>
  296. <view class="title oneline-hide">{{ goodsCard.productName }}</view>
  297. <view class="button" @click="goShop(goodsCard.productId, goodsCard.goodsId)">立即抢购</view>
  298. </view>
  299. </view>
  300. <u-popup :show="isShowLotteryPop && countdown" round="40rpx">
  301. <view class="prize-box" style="border-radius: 40rpx; height: fit-content">
  302. <image class="nav-img" src="/static/images/red_head.png" mode="widthFix" />
  303. <image class="bg-img" src="/static/images/red_bg.png" />
  304. <view class="prize-content">
  305. <view class="mr20" style="display: flex; justify-content: flex-end">
  306. <view style="width: 80rpx; height: 80rpx; display: flex; justify-content: center; align-items: center" @click="isShowLotteryPop = false">
  307. <u-icon class="x-end" name="close" color="#fff" size="20"></u-icon>
  308. </view>
  309. </view>
  310. <view class="column align-center">
  311. <image class="w446 h80" src="/static/images/red_title.png" />
  312. <view class="fs24 colorf x-f mt30 mb30">
  313. 开奖倒计时
  314. <view class="x-f">
  315. <view class="white-item">
  316. {{ countdown.hours || '00' }}
  317. </view>
  318. <view class="white-item">
  319. {{ countdown.minutes || '00' }}
  320. </view>
  321. <view class="white-item">
  322. {{ countdown.seconds || '00' }}
  323. </view>
  324. </view>
  325. </view>
  326. <view class="item-group">
  327. <ThreeItemSwiper :products="lotteryProducts"></ThreeItemSwiper>
  328. </view>
  329. <view class="point-group" v-for="(item, index) in lotteryProducts" :key="index"></view>
  330. <view class="colorf fs28">观看直播参与抽奖</view>
  331. <view class="button" @click="onClaim">参与抽奖</view>
  332. </view>
  333. </view>
  334. </view>
  335. </u-popup>
  336. <u-popup :show="!!integral.status" round="20rpx" mode="center" bgColor="#ffffff" zIndex="10076">
  337. <view class="integral-box">
  338. <view class="top">
  339. <view class="title">观看视频领芳华币</view>
  340. <image class="photo" src="/static/images/integral_bg.png" mode="widthFix" />
  341. </view>
  342. <view class="item">
  343. <view class="title">{{ integral.msg }}</view>
  344. <view class="button" @click="integral.status = false">确认</view>
  345. </view>
  346. </view>
  347. </u-popup>
  348. <u-popup :show="isShowRedCard" round="20rpx" mode="center" bgColor="transparent" zIndex="10076">
  349. <view class="red-card">
  350. <image class="img" src="/static/images/red_card.png" />
  351. <view class="red-content">
  352. <view class="title">{{ redCard.msg }}</view>
  353. <view class="txt">直播惊喜芳华币</view>
  354. <view class="button" @click="isShowRedCard = false">确认</view>
  355. </view>
  356. </view>
  357. </u-popup>
  358. <!-- 中奖和未中奖 -->
  359. <u-popup :show="isShowPrize && havePrize" round="20rpx" mode="center" bgColor="#fff" zIndex="10076">
  360. <view class="prize-card" v-if="isCurrentUserWon">
  361. <image class="nav-img" src="/static/images/red_head.png" mode="widthFix" />
  362. <view class="title">恭喜您 中奖啦!</view>
  363. <view class="prize-content" v-for="(item, index) in prizeInfo || []" :key="index">
  364. <view class="item">{{ item.userName }}</view>
  365. <view class="item">{{ item.userId }}</view>
  366. <view class="txt item">{{ item.prizeLevel }}等奖</view>
  367. </view>
  368. <view class="tip">请截图联系客服领取奖品</view>
  369. <view class="button" @click="confirm">确认</view>
  370. </view>
  371. <view class="no-prize-card" v-else>
  372. <image class="img" src="/static/images/no-prize.png" mode="widthFix" />
  373. <view class="tip">很遗憾 您未中奖</view>
  374. <view class="button" @click="confirm">确认</view>
  375. </view>
  376. </u-popup>
  377. <!-- 中奖记录 -->
  378. <!-- winning -->
  379. <u-popup :show="winning" @close="closeWin" round="20rpx" bgColor="#f3f5f9" zIndex="10076">
  380. <view class="winning_record">
  381. <image class="head_bg" src="/static/images/red_head.png" mode="widthFix"></image>
  382. <image class="bg" src="/static/images/red_bg.png"></image>
  383. <view class="winning_content">
  384. <view class="title">我的中奖记录</view>
  385. <view class="row mb40">
  386. <view class="head">时间</view>
  387. <view class="head">奖品</view>
  388. </view>
  389. <scroll-view enable-flex scroll-y v-if="prizeAll" style="height: 500rpx">
  390. <view class="row fs30 mb20" v-for="(item, index) in prizeAll" :key="index">
  391. <view class="start">{{ item.createTime }}</view>
  392. <view class="end">{{ item.productName ? truncateString(item.productName, 8) : '' }}</view>
  393. </view>
  394. </scroll-view>
  395. <view v-else class="f36 mt150" style="text-align: center">暂无中奖信息</view>
  396. </view>
  397. </view>
  398. </u-popup>
  399. <!-- 观众列表弹窗 -->
  400. <u-popup :show="showadd" @close="close" @open="openViews" round="20rpx" bgColor="#ffffff" zIndex="10077">
  401. <view class="view-box">
  402. <view class="fs32" style="text-align: center">在线观众</view>
  403. <scroll-view v-if="Array.isArray(liveViewers)" scroll-y class="scroll-content" :style="{ height: scrollHeight + 'px' }" @scrolltolower="handleScrollToLower">
  404. <view class="fs28 x-f mb20 mt20" v-for="(item, index) in liveViewers || []" :key="index">
  405. <view
  406. :style="{
  407. color: index === 0 ? '#FF3B30' : index === 1 ? '#FF9500' : index === 2 ? '#FFCC00' : '#8E8E93',
  408. fontWeight: index < 3 ? 'bold' : 'normal',
  409. width: '50rpx'
  410. }"
  411. class="mr10"
  412. >
  413. {{ index + 1 }}
  414. </view>
  415. <u-avatar v-if="item.avatar" :src="item.avatar" :size="36"></u-avatar>
  416. <view v-else class="w72 h72" :style="{ backgroundColor: getUserRandomColor(item.userId), borderRadius: '50%' }">
  417. <text class="text-white text-sm">{{ getNicknameInitial(item.nickName) }}</text>
  418. </view>
  419. <text class="ml16 f30">{{ item.nickName || '未命名' }}</text>
  420. </view>
  421. </scroll-view>
  422. </view>
  423. </u-popup>
  424. <!-- 更多弹窗 -->
  425. <u-popup :show="isMore" @close="closeMore" round="20rpx" bgColor="#f3f5f9" zIndex="10076">
  426. <view class="more-block">
  427. <view class="item" @click="navgetTo('/pages_shopping/live/integral'), (isMore = false)">
  428. <image class="w48 h48" src="/static/images/order.png" />
  429. <view style="text-align: center">芳华币</view>
  430. </view>
  431. <view class="item" @click="navgetTo('/pages_shopping/live/storeOrderRefundList?liveId=' + liveId), (isMore = false)">
  432. <image class="w48 h48" src="/static/images/after_sales.png" />
  433. <view style="text-align: center">售后订单</view>
  434. </view>
  435. <view class="item" @click="goMiniProgram(), (isMore = false)">
  436. <image class="w48 h48" src="/static/images/points.png" />
  437. <view style="text-align: center">兑换好礼</view>
  438. </view>
  439. <view class="item" @click="getMyLottery(), (isMore = false), (winning = true)">
  440. <image class="w48 h48" src="/static/images/health_sel.png" />
  441. <view style="text-align: center">中奖记录</view>
  442. </view>
  443. </view>
  444. </u-popup>
  445. <!-- 商品弹窗 -->
  446. <!-- show="true" -->
  447. <u-popup :show="shopping" @close="closeShop" round="20rpx" bgColor="#f3f5f9" zIndex="10075">
  448. <view class="shoppop">
  449. <view class="shoppop-top">
  450. <view class="search-input x-f">
  451. <image class="w24 mr16" src="/static/images/search.png" mode="widthFix" />
  452. <input placeholder="请搜索商品" v-model="inputInfo" @input="handleSearchInput" />
  453. </view>
  454. <view class="search-top" @click="navgetTo('/pages_shopping/live/order')">
  455. <image class="w48 h48" src="/static/images/carts.png" />
  456. <view style="text-align: center">订单</view>
  457. </view>
  458. <view class="search-top" @click="(isMore = true), (shopping = false)">
  459. <image class="w48 h48" src="/static/images/search2.png" />
  460. <view style="text-align: center">更多</view>
  461. </view>
  462. </view>
  463. <!-- <scroll-view enable-flex scroll-y class="shop-list" :style="{ height: boxHeight + 'px' }">
  464. <view class="list-item" v-for="(item,index) in products" :key="index">
  465. <view class="goods-img">
  466. <image class="img" :src="item.imgUrl" mode="widthFix" />
  467. <view class="goods-label">{{index+1}}</view>
  468. </view>
  469. <view class="goods-right">
  470. <view class="goods-title">{{item.productName}}</view>
  471. <view class="goods-people">{{item.sales}} 人已购</view>
  472. <view class="goods-shop">
  473. <text class="nummber"><text style="font-size: 20rpx;font-weight: 600;">¥</text><text
  474. style="font-size: 36rpx;font-weight: bold;">{{Math.trunc(item.price)}}</text>.{{getPureDecimal(item.price)?getPureDecimal(item.price):'00'}}</text>
  475. <view class="btn-group x-f">
  476. <view class="collect-btn">
  477. <image v-if="item.isFavorite" @click="onGoodsCollect(item)" class="w36 h36"
  478. style="vertical-align: middle;"
  479. src="/static/images/collect_select.png" />
  480. <image v-else @click="onGoodsCollect(item)" class="w36 h36"
  481. style="vertical-align: middle;" src="/static/images/collect.png" />
  482. </view>
  483. <view v-if="item.status==1" class="shop-btn"
  484. @click="goShop(item.productId,item.goodsId)">去购买 </view>
  485. <view v-else-if="item.status==0" class="shop-btn">
  486. 已下架</view>
  487. </view>
  488. </view>
  489. </view>
  490. </view>
  491. </scroll-view> -->
  492. <scroll-view enable-flex scroll-y class="shop-list" :style="{ height: boxHeight + 'px' }">
  493. <!-- 骨架屏 -->
  494. <view v-if="loadingProducts && products.length === 0" class="skeleton-list">
  495. <view v-for="n in 6" :key="n" class="skeleton-item">
  496. <view class="skeleton-img"></view>
  497. <view class="skeleton-content">
  498. <view class="skeleton-line short"></view>
  499. <view class="skeleton-line medium"></view>
  500. <view class="skeleton-line long"></view>
  501. </view>
  502. </view>
  503. </view>
  504. <!-- 实际商品列表 -->
  505. <template v-else>
  506. <view v-for="(item, index) in products" :key="index" class="list-item">
  507. <view class="goods-img">
  508. <image class="img" :src="item.imgUrl" mode="widthFix" />
  509. <view class="goods-label">{{ index + 1 }}</view>
  510. </view>
  511. <view class="goods-right">
  512. <view class="goods-title">{{ item.productName }}</view>
  513. <view class="goods-people">{{ item.sales }} 人已购</view>
  514. <view class="goods-shop">
  515. <text class="nummber">
  516. <text style="font-size: 20rpx; font-weight: 600">¥</text>
  517. <text style="font-size: 36rpx; font-weight: bold">{{ Math.trunc(item.price) }}</text>
  518. .{{ getPureDecimal(item.price) ? getPureDecimal(item.price) : '00' }}
  519. </text>
  520. <view class="btn-group x-f">
  521. <view class="collect-btn">
  522. <image
  523. v-if="item.isFavorite"
  524. @click="onGoodsCollect(item)"
  525. class="w36 h36"
  526. style="vertical-align: middle"
  527. src="/static/images/collect_select.png"
  528. />
  529. <image v-else @click="onGoodsCollect(item)" class="w36 h36" style="vertical-align: middle" src="/static/images/collect.png" />
  530. </view>
  531. <view v-if="item.status == 1" class="shop-btn" @click="goShop(item.productId, item.goodsId)">去购买</view>
  532. <view v-else-if="item.status == 0" class="shop-btn">已下架</view>
  533. </view>
  534. </view>
  535. </view>
  536. </view>
  537. </template>
  538. </scroll-view>
  539. </view>
  540. </u-popup>
  541. <!-- 优惠券弹窗 -->
  542. <view class="coupon-pop" v-if="isShowCoupon">
  543. <view class="coupon-block">
  544. <image class="bg" src="/static/images/coupon_bg.png" />
  545. <image class="nav" src="/static/images/coupon_top.png" />
  546. <image @click="isShowCoupon = false" class="w40 h40 close" style="z-index: 99" src="/static/images/close1.png" />
  547. <view class="item">
  548. <view class="title">{{ couponInfo.couponName }}</view>
  549. <view class="price">
  550. <text class="bold">{{ couponInfo.couponPrice }}</text>
  551. </view>
  552. <view class="txt">满{{ couponInfo.useMinPrice }}元可用</view>
  553. <view class="txt" style="margin-top: 26rpx">指定商品可用</view>
  554. <view class="txt">自领取起{{ couponInfo.couponTime }}天内有效</view>
  555. <view class="button" @click="onCoupon()">立即领券</view>
  556. </view>
  557. </view>
  558. </view>
  559. </view>
  560. </view>
  561. </template>
  562. <script>
  563. import LikeButton from '@/pages_course/components/like.vue';
  564. import ThreeItemSwiper from '@/pages_course/components/ThreeItemSwiper.vue';
  565. import CryptoJS from 'crypto-js';
  566. import {
  567. myLottery, // 我的中奖明细
  568. coupon, //领取优惠券
  569. liveLottery, // 抽奖查询
  570. claim, //抽奖
  571. liveRed, // 点击领红包
  572. liveDataLike, // 点赞
  573. collectStore, // 店铺收藏/取消收藏
  574. collectGoods, // 商品收藏/取消收藏
  575. watchUserList, //获取直播间用户(展示在线用户)
  576. liveMsg, //获取最近聊天记录
  577. // 小黄车
  578. liveStore, //店铺展示,
  579. liveOrderUser, //正在购买
  580. getLiveInfo, //获取直播间信息接口
  581. getLiveViewData, //直播间点赞、关注、在线人数数据
  582. currentActivities, //红包 卡片 抽奖
  583. getlive,
  584. subNotifyLive,
  585. internetTraffic, // 流量(缓冲百分比),
  586. liveInternetTraffic // 直播流量(缓冲百分比),
  587. } from '@/api/living.js';
  588. import { getUserInfo } from '@/api/user';
  589. import { generateRandomString } from '@/utils/common.js';
  590. import dayjs from 'dayjs';
  591. import { nextTick } from 'vue';
  592. var isSocketOpen = false;
  593. var socket = null;
  594. export default {
  595. components: {
  596. ThreeItemSwiper,
  597. LikeButton
  598. },
  599. data() {
  600. return {
  601. uuId: '',
  602. totalTraffic: 0, // 总流量(字节)
  603. bitrate: 800, // 录播默认码率 0.16Mbps
  604. bitrateLive: 1600, // 直播默认码率 0.16Mbps
  605. //定时器
  606. trafficTimer: null,
  607. pingTimeoutTimer: null, // 心跳超时定时器
  608. heartBeatTimer: null, // 心跳定时器
  609. liveViewDataTimer: null,
  610. reconnectTimer: null, // 重连定时器
  611. scrollTimer: null, // 滚动防抖定时器
  612. searchTimer: null, //搜索
  613. purchasePromptTimer: null, //购买提示
  614. welcomeTimer: null, //进入离开直播间定时器
  615. redTimer: null,
  616. liveStartTimer: null,
  617. lotteryTimer: null,
  618. memoryMonitorTimer: null, // 内存监控定时器
  619. networkStatusTimer: null, // 网络状态检测定时器
  620. lastHeartBeatTime: 0, // 上次心跳时间
  621. // 性能监控
  622. connectionStartTime: 0, // 连接开始时间
  623. connectionLatency: 0, // 连接延迟
  624. messageCount: 0, // 消息计数
  625. errorCount: 0, // 错误计数
  626. lastPerformanceCheck: 0, // 上次性能检查时间
  627. stayTime: 0,
  628. startTime: 0,
  629. scrollTop: 0,
  630. scrollPending: false, // 滚动操作是否正在等待执行
  631. isOnload: false,
  632. isConnecting: false, // 是否正在连接中
  633. hasInitialized: false,
  634. liveViewersData: [],
  635. liveUserCalled: false, //调用过watchUserList没
  636. userRandomColors: Object.create(null), // 缓存用户ID -> 随机色的映射
  637. heartBeatRetryCount: 0, // 心跳发送重试次数(避免一次失败就重连)
  638. maxHeartBeatRetries: 3, // 心跳最大重试次数(增加到3次)
  639. pingTimeout: 25000, // 心跳超时时间(25秒,适应移动网络)
  640. shownEntryUsers: new Set(), // 存储已显示过「进入提示」的用户ID
  641. socket: null, // WebSocket 实例
  642. isSocketOpen: false, // 连接是否已打开
  643. heartBeatInterval: 15000, // 心跳发送间隔(15秒)
  644. adaptiveHeartBeatInterval: 15000, // 自适应心跳间隔
  645. reconnectCount: 0, // 当前重连次数
  646. maxReconnectAttempts: 5, // 最大重连次数(增加到5次)
  647. isManualClose: false, // 是否手动关闭(用于区分主动关闭和异常断开)
  648. networkType: 'unknown', // 当前网络类型
  649. isNetworkAvailable: true, // 网络是否可用
  650. templateId: 'fxYJu817lxHNKXl0hJypb-y-lLm8CNmGbcwpQmasCVg',
  651. isAgreement: false,
  652. wsNewUrl: 'wss://api.fhhx.runtzh.com/ws/app/webSocket',
  653. // wsNewUrl: 'ws://192.168.10.166:7114/ws/app/webSocket',
  654. qrFrom: null,
  655. scene: '',
  656. liveCountdown: {}, //直播倒计时
  657. countdown: {}, //抽奖倒计时
  658. liveViewData: {},
  659. keyboardHeight: 0,
  660. isKeyboardShow: false, // 键盘显示状态
  661. videoCurrentTime: 0, // 当前视频播放时间
  662. videoProgressKey: '', // 存储进度的key
  663. inAndOut: {},
  664. winning: false,
  665. isShowPrize: false,
  666. isShowCoupon: false,
  667. prizeInfo: [],
  668. havePrize: uni.getStorageSync('havePrize') || false, //是否参与抽奖
  669. countDownKey: 0,
  670. lotteryProducts: [],
  671. lotteryList: [],
  672. talklist: [],
  673. isShowLotteryPop: false,
  674. liveItem: {},
  675. isSending: false,
  676. isMore: false,
  677. value: '',
  678. placeholderText: '说点什么...',
  679. prizeAll: [],
  680. isShowLottery: false,
  681. isShowRedCard: false,
  682. redCard: null, //点击红包出现弹窗
  683. integral: {},
  684. lotteryInfo: {},
  685. goodsCard: {},
  686. couponInfo: {},
  687. redInfo: {},
  688. storeId: null,
  689. isFocus: false,
  690. shopping: false,
  691. inputInfo: '',
  692. showWelcomeMessage: false,
  693. scrollIntoView: '',
  694. isShowGoods: false,
  695. isShowRed: false,
  696. lastClickTime: 0,
  697. videoRetryCounts: Object.create(null), // 记录每个直播间的视频重试次数,格式: { liveId: 次数 }
  698. clickDelay: 300, // 300ms内只响应一次点击
  699. liveUserTotal: 0,
  700. viewPageSize: 10, // 每页数量
  701. viewPageNum: 1, // 当前页码
  702. viewLoading: false, // 是否正在加载
  703. scrollHeight: 0,
  704. showPurchasePrompt: false,
  705. prevOrderCount: 0, // 用于记录上一次的购买人数
  706. videoUrl: null,
  707. showType: 1, //横屏1 竖屏2
  708. boxHeight: 300, //小黄车高度
  709. liveViewers: [], //观众
  710. livingUrl: '',
  711. products: [],
  712. loadingProducts: false, // 商品加载状态
  713. orderUser: {}, //正在购买
  714. userType: 0,
  715. timestamp: '',
  716. showadd: false,
  717. liveId: null,
  718. userinfo: '', //用户信息
  719. userData: {},
  720. diffTotalTime: ''
  721. };
  722. },
  723. async onLoad(options) {
  724. if (options.liveId) {
  725. this.liveId = options.liveId;
  726. }
  727. // 扫码传来的参数
  728. if (options.scene) {
  729. this.scene = options.scene;
  730. const decodedScene = decodeURIComponent(this.scene);
  731. const params = {};
  732. decodedScene.split('&').forEach((item) => {
  733. const [key, value] = item.split('=');
  734. params[key] = value;
  735. this.liveId = params.a;
  736. });
  737. if (params.b && params.c) {
  738. this.qrFrom = `&companyId=${params.b}&companyUserId=${params.c}`;
  739. }
  740. }
  741. if (options.companyId && options.companyUserId) {
  742. this.qrFrom = `&companyId=${options.companyId}&companyUserId=${options.companyUserId}`;
  743. }
  744. this.userinfo = uni.getStorageSync('userInfo');
  745. this.userData = uni.getStorageSync('userData');
  746. console.log('全部参数', options);
  747. try {
  748. const isLogin = await this.utils.isLogin();
  749. if (isLogin) {
  750. await this.getUserInfo();
  751. this.initTime();
  752. if (this.liveId) {
  753. // 先获取直播间信息
  754. await this.getliving(this.liveId);
  755. this.isOnload = true;
  756. // 然后获取聊天记录
  757. await this.getLiveMsg(this.liveId);
  758. await this.getliveViewData(this.liveItem);
  759. }
  760. }
  761. } catch (error) {
  762. console.error('初始化失败:', error);
  763. }
  764. //获取键盘高度 - 兼容安卓/苹果设备
  765. this.initKeyboardListener();
  766. // 初始化网络状态监听
  767. this.initNetworkStatusListener();
  768. },
  769. onPullDownRefresh() {
  770. this.getLiveMsg(this.liveId);
  771. this.getliveUser();
  772. setTimeout(() => {
  773. uni.stopPullDownRefresh();
  774. }, 1000);
  775. },
  776. async onShow() {
  777. if (this.liveId) {
  778. await this.getLiveMsg(this.liveItem);
  779. }
  780. if (!this.liveViewData) {
  781. this.getliveViewData(this.liveItem);
  782. }
  783. if (!this.userData) {
  784. await this.getUserInfo();
  785. }
  786. this.uuId = generateRandomString(16);
  787. const isLiveLogin = uni.getStorageSync('isLiveLogin');
  788. this.share = uni.getStorageSync('share');
  789. this.scene = uni.getStorageSync('scene');
  790. if (this.share && this.share.length > 0) {
  791. this.liveId = this.share.liveId;
  792. this.qrFrom = `&companyId=${this.share.companyId}&companyUserId=${this.share.companyUserId}`;
  793. uni.removeStorageSync('share');
  794. }
  795. if (this.scene) {
  796. const decodedScene = decodeURIComponent(this.scene);
  797. const params = {};
  798. decodedScene.split('&').forEach((item) => {
  799. const [key, value] = item.split('=');
  800. params[key] = value;
  801. this.liveId = params.a;
  802. });
  803. if (params.b && params.c) {
  804. this.qrFrom = `&companyId=${params.b}&companyUserId=${params.c}`;
  805. }
  806. uni.removeStorageSync('scene');
  807. }
  808. if (isLiveLogin) {
  809. if (this.liveId) {
  810. await this.getliving(this.liveId);
  811. this.getCurrentActivities();
  812. this.getliveOrder();
  813. this.initSocket();
  814. }
  815. this.hasInitialized = true;
  816. uni.removeStorageSync('isLiveLogin');
  817. }
  818. // 恢复播放和连接
  819. await this.resumePageActivity();
  820. this.userinfo = JSON.parse(uni.getStorageSync('userInfo'));
  821. this.isAgreement = uni.getStorageSync('isAgreement');
  822. this.$nextTick(() => {
  823. this.setVideoProgress();
  824. });
  825. if (this.lookTimer) {
  826. clearInterval(this.lookTimer);
  827. this.lookTimer = null;
  828. this.stayTime = 0;
  829. this.startTime = 0;
  830. }
  831. // 启动内存监控,定期清理
  832. this.startMemoryMonitor();
  833. if (this.trafficTimer) {
  834. clearInterval(this.trafficTimer);
  835. this.trafficTimer = null;
  836. this.startTime = 0;
  837. this.totalTraffic = 0;
  838. }
  839. this.startTimer();
  840. },
  841. //分享给好友
  842. onShareAppMessage() {
  843. return {
  844. title: '邀请你来观看直播:' + this.liveItem.liveName,
  845. path: '/pages_course/living?companyId=-2&companyUserId=' + this.userData.userId + '&liveId=' + this.liveId,
  846. imageUrl: '/static/images/logo.png',
  847. success(res) {
  848. console.log('分享成功', res);
  849. },
  850. fail(err) {
  851. console.error('分享失败', err);
  852. }
  853. };
  854. },
  855. computed: {
  856. filteredViewers() {
  857. const safeLiveViewers = Array.isArray(this.liveViewersData) ? this.liveViewersData : [];
  858. // 截取前3项
  859. return safeLiveViewers.slice(0, 3);
  860. },
  861. isCurrentUserWon() {
  862. if (!Array.isArray(this.prizeInfo) || !this.userData?.userId) {
  863. return false;
  864. }
  865. return this.prizeInfo.some((item) => {
  866. return String(item.userId) === String(this.userData.userId);
  867. });
  868. }
  869. },
  870. onHide() {
  871. // 清除所有定时器
  872. this.clearAllTimers();
  873. this.stopHeartBeat();
  874. // 页面隐藏时清理部分数据,减少内存占用
  875. if (this.talklist && this.talklist.length > 20) {
  876. // 只保留最新的20条消息
  877. this.talklist = this.talklist.slice(-20);
  878. }
  879. },
  880. onUnload() {
  881. console.log('页面卸载,开始清理所有资源');
  882. // 保存视频进度
  883. this.saveVideoProgress();
  884. // 清理直播相关定时器
  885. if (this.liveItem) {
  886. this.pauseVideo();
  887. // 清除直播间的时间定时器
  888. if (this.liveItem.timeTimer) {
  889. clearInterval(this.liveItem.timeTimer);
  890. this.liveItem.timeTimer = null;
  891. }
  892. }
  893. // 关闭WebSocket连接(会自动清理相关资源)
  894. this.closeWebSocket(true);
  895. // 清除所有定时器
  896. this.clearAllTimers();
  897. // 暂停视频
  898. const videoId = `myVideo_${this.liveId}`;
  899. const videoContext = uni.createVideoContext(videoId, this);
  900. if (videoContext) {
  901. videoContext.pause();
  902. }
  903. // 移除网络状态监听
  904. try {
  905. uni.offNetworkStatusChange();
  906. } catch (err) {
  907. console.warn('移除网络状态监听失败:', err);
  908. }
  909. // 移除键盘高度监听
  910. try {
  911. uni.offKeyboardHeightChange();
  912. } catch (err) {
  913. console.warn('移除键盘高度监听失败:', err);
  914. }
  915. // 清理大数据和状态
  916. this.clearBigData();
  917. this.resetAllStates();
  918. console.log('页面资源清理完成');
  919. },
  920. mounted() {
  921. this.getCurrentActivities();
  922. this.getliveOrder();
  923. },
  924. watch: {
  925. // 监听liveItem.status的变化
  926. 'liveItem.status': {
  927. handler(newStatus, oldStatus) {
  928. if (newStatus === undefined || oldStatus === undefined) return;
  929. if (newStatus === oldStatus) return;
  930. if (!this.liveId) {
  931. console.warn('liveId不存在,无法触发getliving请求');
  932. return;
  933. }
  934. // 状态变化时,调用getliving更新直播间数据
  935. // console.log(`liveItem.status从${oldStatus}变为${newStatus},触发getliving请求`);
  936. this.getliving(this.liveId);
  937. },
  938. deep: true
  939. },
  940. // 监听orderUser.count的变化
  941. 'orderUser.count': {
  942. handler(newVal, oldVal) {
  943. if (newVal !== this.prevOrderCount) {
  944. this.prevOrderCount = newVal;
  945. this.showPurchaseMessage();
  946. }
  947. },
  948. immediate: true
  949. }
  950. },
  951. methods: {
  952. // 重置所有状态
  953. resetAllStates() {
  954. this.liveUserCalled = false;
  955. this.talklist = [];
  956. this.liveViewersData = [];
  957. this.liveViewers = [];
  958. this.products = [];
  959. this.liveItem = [];
  960. // 重置WebSocket相关状态
  961. this.isSocketOpen = false;
  962. this.isConnecting = false;
  963. this.isManualClose = true;
  964. this.reconnectCount = 0;
  965. this.heartBeatRetryCount = 0;
  966. this.lastHeartBeatTime = 0;
  967. this.adaptiveHeartBeatInterval = this.heartBeatInterval;
  968. this.isNetworkAvailable = true;
  969. this.networkType = 'unknown';
  970. // 重置性能监控数据
  971. this.connectionStartTime = 0;
  972. this.connectionLatency = 0;
  973. this.messageCount = 0;
  974. this.errorCount = 0;
  975. this.lastPerformanceCheck = 0;
  976. },
  977. // 获取WebSocket性能统计
  978. getWebSocketPerformanceStats() {
  979. const now = Date.now();
  980. const uptime = this.connectionStartTime > 0 ? now - this.connectionStartTime : 0;
  981. return {
  982. connectionLatency: this.connectionLatency,
  983. uptime: uptime,
  984. messageCount: this.messageCount,
  985. errorCount: this.errorCount,
  986. errorRate: this.messageCount > 0 ? (this.errorCount / this.messageCount * 100).toFixed(2) : 0,
  987. messagesPerSecond: uptime > 0 ? (this.messageCount / (uptime / 1000)).toFixed(2) : 0,
  988. networkType: this.networkType,
  989. isConnected: this.isSocketAvailable(),
  990. reconnectCount: this.reconnectCount
  991. };
  992. },
  993. // 定期检查性能并输出统计信息
  994. performanceCheck() {
  995. const now = Date.now();
  996. // 每5分钟输出一次性能统计
  997. if (now - this.lastPerformanceCheck > 300000) { // 5分钟
  998. const stats = this.getWebSocketPerformanceStats();
  999. console.log('WebSocket性能统计:', stats);
  1000. this.lastPerformanceCheck = now;
  1001. // 如果错误率过高,记录警告
  1002. if (stats.errorRate > 10) {
  1003. console.warn(`WebSocket错误率过高: ${stats.errorRate}%`);
  1004. }
  1005. // 如果连接延迟过高,记录警告
  1006. if (stats.connectionLatency > 5000) {
  1007. console.warn(`WebSocket连接延迟过高: ${stats.connectionLatency}ms`);
  1008. }
  1009. }
  1010. },
  1011. // 定期清理视频缓存
  1012. startVideoCacheCleanup() {
  1013. if (this.videoCleanupTimer) {
  1014. clearInterval(this.videoCleanupTimer);
  1015. }
  1016. // 每30秒清理一次视频缓存
  1017. this.videoCleanupTimer = setInterval(() => {
  1018. this.cleanupVideoCache();
  1019. }, 30000);
  1020. },
  1021. // 清理视频缓存
  1022. cleanupVideoCache() {
  1023. if (!this.liveItem || !this.liveId) return;
  1024. // 只对录播视频进行清理
  1025. if (this.liveItem.liveType === 2 && this.liveItem.videoUrl) {
  1026. this.reloadVideoPlayer();
  1027. }
  1028. },
  1029. // 重新加载视频播放器
  1030. reloadVideoPlayer() {
  1031. const videoId = `myVideo_${this.liveId}`;
  1032. const videoContext = uni.createVideoContext(videoId, this);
  1033. if (videoContext) {
  1034. const currentTime = this.videoCurrentTime;
  1035. // 暂停视频
  1036. videoContext.pause();
  1037. // 延迟重新加载
  1038. setTimeout(() => {
  1039. // 重新设置视频源,强制清理缓存
  1040. this.$set(this.liveItem, 'videoUrl', this.liveItem.videoUrl + '&t=' + Date.now());
  1041. // 恢复播放位置
  1042. setTimeout(() => {
  1043. if (videoContext.seek) {
  1044. videoContext.seek(currentTime);
  1045. }
  1046. videoContext.play();
  1047. }, 500);
  1048. }, 100);
  1049. }
  1050. },
  1051. // 启动内存监控
  1052. startMemoryMonitoring() {
  1053. if (this.memoryMonitorTimer) {
  1054. clearInterval(this.memoryMonitorTimer);
  1055. }
  1056. this.memoryMonitorTimer = setInterval(() => {
  1057. this.checkMemoryUsage();
  1058. }, 15000); // 每15秒检查一次
  1059. },
  1060. // 检查内存使用情况
  1061. checkMemoryUsage() {
  1062. // 在微信小程序中,可以通过性能监控API检查内存
  1063. if (wx && wx.getPerformance) {
  1064. try {
  1065. const performance = wx.getPerformance();
  1066. const memory = performance.memory;
  1067. if (memory && memory.usedJSHeapSize > 50 * 1024 * 1024) {
  1068. // 超过50MB
  1069. console.warn('内存使用过高,触发清理:', memory.usedJSHeapSize);
  1070. this.forceMemoryCleanup();
  1071. }
  1072. } catch (e) {
  1073. console.log('无法获取内存信息');
  1074. }
  1075. }
  1076. },
  1077. // 强制内存清理
  1078. forceMemoryCleanup() {
  1079. console.log('执行强制内存清理');
  1080. // 1. 清理视频播放器
  1081. this.cleanupVideoPlayer();
  1082. // 2. 清理大数据
  1083. this.clearBigData();
  1084. // 3. 强制垃圾回收(在支持的环境下)
  1085. this.triggerGarbageCollection();
  1086. },
  1087. // 清理视频播放器
  1088. cleanupVideoPlayer() {
  1089. const videoId = `myVideo_${this.liveId}`;
  1090. const videoContext = uni.createVideoContext(videoId, this);
  1091. if (videoContext) {
  1092. // 停止播放
  1093. videoContext.stop();
  1094. // 重置视频源
  1095. setTimeout(() => {
  1096. this.$set(this.liveItem, 'videoUrl', '');
  1097. setTimeout(() => {
  1098. this.$set(this.liveItem, 'videoUrl', this.getFreshVideoUrl());
  1099. this.playVideo();
  1100. }, 500);
  1101. }, 100);
  1102. }
  1103. },
  1104. // 获取带时间戳的新视频URL
  1105. getFreshVideoUrl() {
  1106. if (!this.liveItem.originalVideoUrl) {
  1107. this.liveItem.originalVideoUrl = this.liveItem.videoUrl;
  1108. }
  1109. // 添加时间戳参数,避免缓存
  1110. const separator = this.liveItem.originalVideoUrl.includes('?') ? '&' : '?';
  1111. return this.liveItem.originalVideoUrl + separator + 't=' + Date.now();
  1112. },
  1113. // 清理大数据
  1114. clearBigData() {
  1115. // 清理聊天记录,只保留最近50条
  1116. if (this.talklist.length > 50) {
  1117. this.talklist = this.talklist.slice(-50);
  1118. }
  1119. // 清理观众数据
  1120. if (this.liveViewersData.length > 100) {
  1121. this.liveViewersData = this.liveViewersData.slice(-100);
  1122. }
  1123. // 清理虚拟数据
  1124. if (this.liveViewers.length > 100) {
  1125. this.liveViewers = this.liveViewers.slice(-100);
  1126. }
  1127. // 清理商品数据
  1128. if (this.products.length > 50) {
  1129. this.products = this.products.slice(0, 50);
  1130. }
  1131. // 强制垃圾回收(如果支持)
  1132. if (typeof gc === 'function') {
  1133. gc();
  1134. }
  1135. },
  1136. // 触发垃圾回收(在支持的环境下)
  1137. triggerGarbageCollection() {
  1138. if (wx && wx.triggerGC) {
  1139. wx.triggerGC();
  1140. }
  1141. },
  1142. goMiniProgram() {
  1143. // uni.navigateToMiniProgram({
  1144. // appId: 'wx45cf09091aead547',
  1145. // path: '/pages/home/index',
  1146. // success: function(res) {
  1147. // console.log('跳转成功', res);
  1148. // },
  1149. // fail: function(err) {
  1150. // console.error('跳转失败', err);
  1151. // }
  1152. // });
  1153. uni.showToast({
  1154. title: '系统升级中,兑换请联系伴学助手!',
  1155. icon: 'none'
  1156. });
  1157. },
  1158. // 阻止双击事件
  1159. preventDoubleClick(e) {
  1160. e.preventDefault();
  1161. e.stopPropagation();
  1162. return false;
  1163. },
  1164. // 清理所有定时器和内存
  1165. clearAllTimers() {
  1166. // 清理所有定时器
  1167. const timers = [
  1168. 'scrollTimer',
  1169. 'liveViewDataTimer',
  1170. 'redTimer',
  1171. 'liveStartTimer',
  1172. 'lotteryTimer',
  1173. 'welcomeTimer',
  1174. 'trafficInterval',
  1175. 'lookTimer',
  1176. 'trafficTimer',
  1177. 'intervalId',
  1178. 'reconnectTimer',
  1179. 'searchTimer',
  1180. 'purchasePromptTimer',
  1181. 'heartBeatTimer',
  1182. 'pingTimeoutTimer'
  1183. ];
  1184. timers.forEach((timer) => {
  1185. if (this[timer]) {
  1186. if (timer.includes('Interval') || timer.includes('Timer')) {
  1187. clearInterval(this[timer]);
  1188. } else {
  1189. clearTimeout(this[timer]);
  1190. }
  1191. this[timer] = null;
  1192. }
  1193. });
  1194. // 重置相关状态
  1195. this.stayTime = 0;
  1196. this.startTime = 0;
  1197. this.totalTraffic = 0;
  1198. this.scrollPending = false;
  1199. this.reconnectCount = 0;
  1200. this.heartBeatRetryCount = 0;
  1201. },
  1202. //直播计算流量
  1203. startTrafficCalculation(bitrate) {
  1204. if (this.trafficTimer) {
  1205. clearInterval(this.trafficTimer);
  1206. this.trafficTimer = null;
  1207. }
  1208. this.startTime = Date.now();
  1209. var that = this;
  1210. this.trafficTimer = setInterval(() => {
  1211. that.calculateTraffic(bitrate);
  1212. }, 10000); // 每10秒计算一次
  1213. },
  1214. // 计算流量
  1215. calculateTraffic(bitrate) {
  1216. const currentTime = Date.now();
  1217. const duration = (currentTime - this.startTime) / 1000; // 持续时间(秒)
  1218. // 流量 = 码率 × 时间
  1219. // 码率单位: bps, 时间单位: 秒, 流量单位: 比特
  1220. const trafficBits = bitrate * duration;
  1221. // 转换为字节
  1222. this.totalTraffic = trafficBits / 8;
  1223. this.getLiveInternetTraffic();
  1224. },
  1225. startTimer() {
  1226. this.startTime = Date.now();
  1227. this.lookTimer = setInterval(() => {
  1228. this.stayTime = Math.floor((Date.now() - this.startTime) / 1000);
  1229. }, 1000);
  1230. },
  1231. //直播、录播缓冲
  1232. getLiveInternetTraffic() {
  1233. if (!this.liveId) return;
  1234. const currentTime = (this.stayTime / this.liveItem.duration) * 100;
  1235. const param = {
  1236. userId: this.userData.userId || '',
  1237. liveId: this.liveId || '',
  1238. uuId: dayjs().format('YYYYMMDD') + this.uuId,
  1239. internetTraffic: this.totalTraffic
  1240. };
  1241. liveInternetTraffic(param);
  1242. },
  1243. // 回放、预告缓冲
  1244. getInternetTraffic() {
  1245. if (!this.liveId || !this.liveId || !this.userData.userId || !this.uuId) return;
  1246. const currentTime = (this.stayTime / this.liveItem.duration) * 100;
  1247. const param = {
  1248. videoType: this.liveItem.videoType,
  1249. videoId: this.liveItem.videoId,
  1250. userId: this.userData.userId,
  1251. liveId: this.liveId,
  1252. uuId: dayjs().format('YYYYMMDD') + this.uuId,
  1253. duration: this.liveItem.duration,
  1254. bufferRate: currentTime
  1255. };
  1256. if (this.liveItem.status == 1) {
  1257. param.videoType = this.liveItem.previewVideoType || '';
  1258. param.videoId = this.liveItem.previewVideoId || '';
  1259. }
  1260. if (this.liveItem.liveType == 1) {
  1261. param.bufferRate = this.totalTraffic;
  1262. }
  1263. internetTraffic(param);
  1264. },
  1265. scrollToBottom() {
  1266. if (this.scrollTimer) {
  1267. clearTimeout(this.scrollTimer);
  1268. }
  1269. this.scrollTimer = setTimeout(() => {
  1270. this.$nextTick(() => {
  1271. const query = uni.createSelectorQuery().in(this);
  1272. query.select('.scrolly').boundingClientRect(scrollRect => {
  1273. if (!scrollRect) return;
  1274. query.select('.scrolly').scrollOffset(scrollOffset => {
  1275. const newScrollTop = scrollOffset.scrollHeight - scrollRect.height;
  1276. this.scrollTop = newScrollTop;
  1277. }).exec();
  1278. }).exec();
  1279. });
  1280. }, 0);
  1281. },
  1282. // 启动内存监控
  1283. startMemoryMonitor() {
  1284. // 清理之前的监控
  1285. if (this.memoryMonitorTimer) {
  1286. clearInterval(this.memoryMonitorTimer);
  1287. }
  1288. // 每5分钟检查一次内存使用情况
  1289. this.memoryMonitorTimer = setInterval(() => {
  1290. this.checkAndCleanMemory();
  1291. }, 5 * 60 * 1000); // 5分钟
  1292. },
  1293. // 检查并清理内存
  1294. checkAndCleanMemory() {
  1295. try {
  1296. // 清理过多的聊天消息
  1297. if (this.talklist && this.talklist.length > 25) {
  1298. const keepCount = 20;
  1299. this.talklist.splice(0, this.talklist.length - keepCount);
  1300. }
  1301. // 清理用户颜色缓存(保留最近的50个)
  1302. if (this.userRandomColors && Object.keys(this.userRandomColors).length > 50) {
  1303. const entries = Object.entries(this.userRandomColors);
  1304. const keepEntries = entries.slice(-50);
  1305. this.userRandomColors = Object.fromEntries(keepEntries);
  1306. }
  1307. // 清理已显示用户集合(保留最近的100个)
  1308. if (this.shownEntryUsers && this.shownEntryUsers.size > 100) {
  1309. const array = Array.from(this.shownEntryUsers);
  1310. this.shownEntryUsers.clear();
  1311. array.slice(-100).forEach((id) => this.shownEntryUsers.add(id));
  1312. }
  1313. console.log('内存清理完成');
  1314. } catch (error) {
  1315. console.error('内存清理失败:', error);
  1316. }
  1317. },
  1318. // 恢复页面活动
  1319. async resumePageActivity() {
  1320. if (this.liveItem) {
  1321. await this.getliving(this.liveId);
  1322. this.startTimeTimer(this.liveItem);
  1323. }
  1324. if (!this.isSocketAvailable()) {
  1325. this.initSocket();
  1326. }
  1327. },
  1328. // 获取用户专属随机色(缓存机制:同一用户始终用同一颜色)
  1329. getUserRandomColor(userId) {
  1330. if (!userId) {
  1331. return '#8978e2'; // 默认颜色
  1332. }
  1333. //如果缓存中已有该用户的颜色,直接返回
  1334. if (this.userRandomColors[userId]) {
  1335. return this.userRandomColors[userId];
  1336. }
  1337. //为新用户生成固定颜色(基于用户ID生成,不是完全随机)
  1338. const color = this.generateStableColor(userId);
  1339. this.userRandomColors[userId] = color;
  1340. // 存储到本地缓存,确保页面刷新后颜色不变
  1341. this.saveUserColorsToStorage();
  1342. return color;
  1343. }, // 基于用户ID生成稳定颜色(不是完全随机)
  1344. generateStableColor(userId) {
  1345. // 将用户ID转换为数字种子
  1346. let seed = 0;
  1347. for (let i = 0; i < userId.length; i++) {
  1348. seed = (seed * 31 + userId.charCodeAt(i)) % 1000000;
  1349. }
  1350. const colorPool = [
  1351. '#FF6B6B',
  1352. '#4ECDC4',
  1353. '#45B7D1',
  1354. '#96CEB4',
  1355. '#FFEAA7',
  1356. '#DDA0DD',
  1357. '#98D8C8',
  1358. '#F7DC6F',
  1359. '#BB8FCE',
  1360. '#85C1E9',
  1361. '#F8C471',
  1362. '#82E0AA',
  1363. '#F1948A',
  1364. '#85C1E9',
  1365. '#D7BDE2'
  1366. ];
  1367. return colorPool[seed % colorPool.length];
  1368. },
  1369. // 保存颜色映射到本地存储
  1370. saveUserColorsToStorage() {
  1371. try {
  1372. uni.setStorageSync('userRandomColors', this.userRandomColors);
  1373. } catch (e) {
  1374. console.warn('保存用户颜色缓存失败:', e);
  1375. }
  1376. },
  1377. // 从本地存储加载颜色映射
  1378. loadUserColorsFromStorage() {
  1379. try {
  1380. const cached = uni.getStorageSync('userRandomColors');
  1381. if (cached) {
  1382. this.userRandomColors = cached;
  1383. }
  1384. } catch (e) {
  1385. console.warn('加载用户颜色缓存失败:', e);
  1386. }
  1387. },
  1388. //头像名字
  1389. getNicknameInitial(nickName) {
  1390. if (!nickName || typeof nickName !== 'string') return '未';
  1391. if (/^[\u4e00-\u9fa5]/.test(nickName[0])) {
  1392. return nickName[0];
  1393. }
  1394. return nickName[0].toUpperCase();
  1395. },
  1396. async getUserInfo() {
  1397. await getUserInfo().then(
  1398. (res) => {
  1399. if (res.code == 200) {
  1400. this.userData = res.user;
  1401. } else {
  1402. uni.showToast({
  1403. icon: 'none',
  1404. title: '请求失败'
  1405. });
  1406. }
  1407. },
  1408. (rej) => {}
  1409. );
  1410. },
  1411. //订阅消息
  1412. handleAgreement() {
  1413. const templateId = this.templateId;
  1414. uni.requestSubscribeMessage({
  1415. tmplIds: [templateId],
  1416. success: (res) => {
  1417. // console.log("模板订阅状态", res[templateId]);
  1418. if (res[templateId] === 'accept') {
  1419. uni.showToast({
  1420. title: '订阅成功,开播将提醒您',
  1421. icon: 'success'
  1422. });
  1423. this.callSendMessageApi();
  1424. } else if (res[templateId] === 'reject') {
  1425. uni.showToast({
  1426. title: '您已拒绝订阅,将无法收到提醒',
  1427. icon: 'none'
  1428. });
  1429. } else if (res[templateId] === 'ban') {
  1430. uni.showToast({
  1431. title: '您已关闭所有订阅权限,请在设置中开启',
  1432. icon: 'none'
  1433. });
  1434. }
  1435. },
  1436. fail: (err) => {
  1437. console.error('订阅消息失败', err);
  1438. uni.showToast({
  1439. title: '订阅失败,请重试',
  1440. icon: 'none'
  1441. });
  1442. }
  1443. });
  1444. },
  1445. async callSendMessageApi() {
  1446. if (!this.userData.userId) return;
  1447. const templateData = {
  1448. taskName: this.liveId,
  1449. userId: this.userData.userId,
  1450. templateId: this.templateId, // 模板ID
  1451. data: {
  1452. thing6: this.liveItem.liveName,
  1453. date7: this.liveItem.startTime
  1454. }
  1455. };
  1456. subNotifyLive(templateData).then(
  1457. (res) => {
  1458. if (res.code == 200) {
  1459. this.isAgreement = true;
  1460. uni.setStorageSync('isAgreement', true);
  1461. } else {
  1462. uni.showToast({
  1463. title: res.msg,
  1464. icon: 'none'
  1465. });
  1466. }
  1467. },
  1468. (rej) => {}
  1469. );
  1470. },
  1471. //发送心跳
  1472. sendHeartBeat() {
  1473. if (!this.isSocketAvailable() || !this.isNetworkAvailable) {
  1474. console.warn('网络不可用或Socket连接异常,跳过心跳发送');
  1475. return;
  1476. }
  1477. this.lastHeartBeatTime = Date.now();
  1478. try {
  1479. const heartBeatMsg = JSON.stringify({
  1480. cmd: 'heartbeat',
  1481. msg: 'ping',
  1482. userId: this.userData.userId || '',
  1483. liveId: this.liveId,
  1484. timestamp: this.lastHeartBeatTime,
  1485. networkType: this.networkType
  1486. });
  1487. console.log("qxj sendHeartBeat");
  1488. this.socket.send({
  1489. data: heartBeatMsg,
  1490. success: () => {
  1491. this.heartBeatRetryCount = 0; // 成功后重置重试次数
  1492. this.adjustHeartBeatInterval(true); // 网络良好,可适当延长间隔
  1493. this.startPingTimeout(); // 启动超时检测
  1494. },
  1495. fail: (err) => {
  1496. console.error('心跳包发送失败:', err);
  1497. this.heartBeatRetryCount++;
  1498. this.adjustHeartBeatInterval(false); // 网络不稳定,缩短间隔
  1499. // 根据网络类型调整重试策略
  1500. const retryDelay = this.getRetryDelay();
  1501. if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
  1502. setTimeout(() => this.sendHeartBeat(), retryDelay);
  1503. } else {
  1504. this.heartBeatRetryCount = 0;
  1505. this.handleReconnect(); // 重试用完才重连
  1506. }
  1507. }
  1508. });
  1509. } catch (err) {
  1510. console.error('心跳发送异常:', err);
  1511. this.heartBeatRetryCount++;
  1512. const retryDelay = this.getRetryDelay();
  1513. if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
  1514. setTimeout(() => this.sendHeartBeat(), retryDelay);
  1515. } else {
  1516. this.heartBeatRetryCount = 0;
  1517. this.handleReconnect();
  1518. }
  1519. }
  1520. },
  1521. // 根据网络状态获取重试延迟
  1522. getRetryDelay() {
  1523. const baseDelay = 2000;
  1524. const retryMultiplier = Math.pow(1.5, this.heartBeatRetryCount); // 指数退避
  1525. // 根据网络类型调整延迟
  1526. let networkMultiplier = 1;
  1527. switch (this.networkType) {
  1528. case '2g':
  1529. networkMultiplier = 3;
  1530. break;
  1531. case '3g':
  1532. networkMultiplier = 2;
  1533. break;
  1534. case '4g':
  1535. case '5g':
  1536. networkMultiplier = 1;
  1537. break;
  1538. case 'wifi':
  1539. networkMultiplier = 0.8;
  1540. break;
  1541. default:
  1542. networkMultiplier = 1.5;
  1543. }
  1544. return Math.min(baseDelay * retryMultiplier * networkMultiplier, 10000); // 最大10秒
  1545. },
  1546. // 自适应调整心跳间隔
  1547. adjustHeartBeatInterval(isSuccess) {
  1548. if (isSuccess) {
  1549. // 连接稳定,可适当延长间隔(最大30秒)
  1550. this.adaptiveHeartBeatInterval = Math.min(this.adaptiveHeartBeatInterval * 1.1, 30000);
  1551. } else {
  1552. // 连接不稳定,缩短间隔(最小10秒)
  1553. this.adaptiveHeartBeatInterval = Math.max(this.adaptiveHeartBeatInterval * 0.9, 10000);
  1554. }
  1555. },
  1556. // 启动心跳超时检测
  1557. startPingTimeout() {
  1558. // 清除之前的超时定时器
  1559. if (this.pingTimeoutTimer) {
  1560. clearTimeout(this.pingTimeoutTimer);
  1561. this.pingTimeoutTimer = null;
  1562. }
  1563. // 超时后触发重连
  1564. this.pingTimeoutTimer = setTimeout(() => {
  1565. // console.error("心跳响应超时,连接异常");
  1566. this.handleReconnect();
  1567. }, this.pingTimeout);
  1568. },
  1569. stopHeartBeat() {
  1570. if (this.heartBeatTimer) {
  1571. clearInterval(this.heartBeatTimer);
  1572. this.heartBeatTimer = null;
  1573. }
  1574. if (this.pingTimeoutTimer) {
  1575. clearTimeout(this.pingTimeoutTimer);
  1576. this.pingTimeoutTimer = null;
  1577. }
  1578. }, // 封装通用的连接状态校验方法
  1579. isSocketAvailable() {
  1580. // WebSocket readyState:0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED
  1581. return this.socket && this.isSocketOpen && this.socket.readyState === 1;
  1582. },
  1583. // 处理重连逻辑
  1584. handleReconnect() {
  1585. if (this.isManualClose) {
  1586. console.log('手动关闭连接,不进行重连');
  1587. return;
  1588. }
  1589. this.stopHeartBeat();
  1590. // 检查网络状态
  1591. if (!this.isNetworkAvailable) {
  1592. console.warn('网络不可用,延迟重连');
  1593. setTimeout(() => this.handleReconnect(), 5000);
  1594. return;
  1595. }
  1596. if (this.reconnectCount < this.maxReconnectAttempts) {
  1597. this.reconnectCount++;
  1598. // 指数退避算法:基础延迟 * 2^(重连次数-1) + 随机抖动
  1599. const baseDelay = 1000;
  1600. const exponentialDelay = baseDelay * Math.pow(2, this.reconnectCount - 1);
  1601. const jitter = Math.random() * 1000; // 随机抖动,避免同时重连
  1602. const totalDelay = Math.min(exponentialDelay + jitter, 30000); // 最大30秒
  1603. console.log(`第${this.reconnectCount}次重连,延迟${Math.round(totalDelay)}ms,网络类型:${this.networkType}`);
  1604. this.reconnectTimer = setTimeout(() => {
  1605. // 重连前再次检查网络状态
  1606. if (this.isNetworkAvailable && !this.isManualClose) {
  1607. this.initSocket();
  1608. } else {
  1609. console.warn('重连时网络不可用或已手动关闭');
  1610. this.handleReconnect(); // 递归重试
  1611. }
  1612. }, totalDelay);
  1613. } else {
  1614. console.log(`已达最大重连次数(${this.maxReconnectAttempts}),停止重连`);
  1615. this.showReconnectFailedMessage();
  1616. }
  1617. },
  1618. // 显示重连失败提示
  1619. showReconnectFailedMessage() {
  1620. uni.showToast({
  1621. title: '网络连接异常,请检查网络后重新进入',
  1622. icon: 'none',
  1623. duration: 3000
  1624. });
  1625. },
  1626. // 统一处理连接错误
  1627. handleConnectionError(errorType, error) {
  1628. console.error(`WebSocket ${errorType}:`, error);
  1629. // 根据错误类型进行不同处理
  1630. if (errorType === '连接请求失败') {
  1631. // 连接请求失败,可能是网络问题或服务器问题
  1632. if (!this.isNetworkAvailable) {
  1633. console.warn('网络不可用,等待网络恢复后重连');
  1634. return;
  1635. }
  1636. }
  1637. // 触发重连
  1638. this.handleReconnect();
  1639. },
  1640. // 重置重连状态
  1641. resetReconnectState() {
  1642. this.reconnectCount = 0;
  1643. this.heartBeatRetryCount = 0;
  1644. // 清理重连定时器
  1645. if (this.reconnectTimer) {
  1646. clearTimeout(this.reconnectTimer);
  1647. this.reconnectTimer = null;
  1648. }
  1649. // 重置自适应心跳间隔
  1650. this.adaptiveHeartBeatInterval = this.heartBeatInterval;
  1651. },
  1652. // 初始化网络状态监听
  1653. initNetworkStatusListener() {
  1654. // 获取当前网络状态
  1655. uni.getNetworkType({
  1656. success: (res) => {
  1657. this.networkType = res.networkType;
  1658. this.isNetworkAvailable = res.networkType !== 'none';
  1659. console.log('当前网络类型:', res.networkType);
  1660. }
  1661. });
  1662. // 监听网络状态变化
  1663. uni.onNetworkStatusChange((res) => {
  1664. const oldNetworkType = this.networkType;
  1665. const oldNetworkAvailable = this.isNetworkAvailable;
  1666. this.networkType = res.networkType;
  1667. this.isNetworkAvailable = res.isConnected;
  1668. console.log(`网络状态变化: ${oldNetworkType} -> ${res.networkType}, 连接状态: ${res.isConnected}`);
  1669. // 网络从不可用变为可用时,尝试重连
  1670. if (!oldNetworkAvailable && res.isConnected) {
  1671. console.log('网络恢复,尝试重连WebSocket');
  1672. this.resetReconnectState();
  1673. setTimeout(() => {
  1674. if (!this.isSocketAvailable()) {
  1675. this.initSocket();
  1676. }
  1677. }, 1000);
  1678. }
  1679. // 网络类型变化时,调整心跳策略
  1680. if (oldNetworkType !== res.networkType && res.isConnected) {
  1681. this.adjustHeartBeatForNetworkType(res.networkType);
  1682. }
  1683. // 网络断开时停止心跳
  1684. if (!res.isConnected) {
  1685. console.warn('网络断开,停止心跳');
  1686. this.stopHeartBeat();
  1687. }
  1688. });
  1689. },
  1690. // 根据网络类型调整心跳策略
  1691. adjustHeartBeatForNetworkType(networkType) {
  1692. let newInterval = this.heartBeatInterval;
  1693. switch (networkType) {
  1694. case '2g':
  1695. newInterval = 30000; // 2G网络,30秒间隔
  1696. break;
  1697. case '3g':
  1698. newInterval = 20000; // 3G网络,20秒间隔
  1699. break;
  1700. case '4g':
  1701. case '5g':
  1702. newInterval = 15000; // 4G/5G网络,15秒间隔
  1703. break;
  1704. case 'wifi':
  1705. newInterval = 10000; // WiFi网络,10秒间隔
  1706. break;
  1707. default:
  1708. newInterval = 15000; // 默认15秒
  1709. }
  1710. if (newInterval !== this.adaptiveHeartBeatInterval) {
  1711. this.adaptiveHeartBeatInterval = newInterval;
  1712. console.log(`根据网络类型(${networkType})调整心跳间隔为${newInterval}ms`);
  1713. // 如果当前有心跳在运行,重启心跳以应用新间隔
  1714. if (this.heartBeatTimer && this.isSocketAvailable()) {
  1715. this.startHeartBeat();
  1716. }
  1717. }
  1718. },
  1719. //输入框
  1720. inputFocus() {
  1721. // 立即更新状态,确保UI快速响应
  1722. this.isFocus = true;
  1723. this.isKeyboardShow = true;
  1724. console.log('输入框获得焦点,等待键盘监听器更新高度');
  1725. },
  1726. inputBlur() {
  1727. // this.chatHeight = 0;
  1728. this.isFocus = false;
  1729. // 减少延迟,快速响应键盘隐藏
  1730. setTimeout(() => {
  1731. if (!this.isFocus) {
  1732. this.isKeyboardShow = false;
  1733. // 重置键盘高度,确保下次点击时能正确计算
  1734. this.keyboardHeight = 0;
  1735. }
  1736. }, 50);
  1737. },
  1738. // 初始化键盘监听器 - 兼容安卓/苹果
  1739. initKeyboardListener() {
  1740. const systemInfo = uni.getSystemInfoSync();
  1741. const isIOS = systemInfo.platform === 'ios';
  1742. const isAndroid = systemInfo.platform === 'android';
  1743. uni.onKeyboardHeightChange((res) => {
  1744. // 立即更新键盘显示状态和高度,确保快速响应
  1745. this.isKeyboardShow = res.height > 0;
  1746. console.log('键盘高度变化:', res);
  1747. console.log('设备信息:', {
  1748. platform: systemInfo.platform,
  1749. model: systemInfo.model,
  1750. safeAreaInsets: systemInfo.safeAreaInsets,
  1751. screenHeight: systemInfo.screenHeight,
  1752. windowHeight: systemInfo.windowHeight
  1753. });
  1754. // 立即处理键盘高度计算,不使用防抖
  1755. // 根据不同平台进行兼容性处理
  1756. if (isIOS) {
  1757. // iOS设备处理 - 需要考虑底部安全区域
  1758. this.keyboardHeight = res.height * 2; // iOS需要乘以2转换为rpx
  1759. // iOS设备需要减去底部安全区域,确保输入框紧贴键盘
  1760. const safeAreaBottom = systemInfo.safeAreaInsets ? systemInfo.safeAreaInsets.bottom : 0;
  1761. if (safeAreaBottom > 0 && res.height > 0) {
  1762. // iOS的键盘高度已经包含了安全区域,所以需要减去避免重复计算
  1763. this.keyboardHeight = this.keyboardHeight - (safeAreaBottom * 2);
  1764. }
  1765. // 对于有刘海屏的iOS设备,可能需要额外调整
  1766. if (systemInfo.model && (systemInfo.model.includes('iPhone X') ||
  1767. systemInfo.model.includes('iPhone 11') ||
  1768. systemInfo.model.includes('iPhone 12') ||
  1769. systemInfo.model.includes('iPhone 13') ||
  1770. systemInfo.model.includes('iPhone 14') ||
  1771. systemInfo.model.includes('iPhone 15') ||
  1772. systemInfo.model.includes('iPhone 16') ||
  1773. systemInfo.model.includes('iPhone 17'))
  1774. ) {
  1775. // 刘海屏设备额外减少一些间距,确保完全紧贴
  1776. this.keyboardHeight = Math.max(0, this.keyboardHeight - 10);
  1777. }
  1778. // iOS设备的最终微调 - 减少可能存在的系统间距
  1779. if (res.height > 0) {
  1780. this.keyboardHeight = Math.max(0, this.keyboardHeight - 5);
  1781. }
  1782. } else if (isAndroid) {
  1783. // Android设备处理
  1784. this.keyboardHeight = res.height * 2; // Android也需要转换为rpx
  1785. // Android设备需要减去底部安全区域,确保输入框紧贴键盘
  1786. const safeAreaBottom = systemInfo.safeAreaInsets ? systemInfo.safeAreaInsets.bottom : 0;
  1787. if (safeAreaBottom > 0 && res.height > 0) {
  1788. // Android的键盘高度也需要减去安全区域,避免重复计算
  1789. this.keyboardHeight = this.keyboardHeight - (safeAreaBottom * 2);
  1790. }
  1791. if (res.height > 0) {
  1792. this.keyboardHeight = Math.max(0, this.keyboardHeight - 10);
  1793. }
  1794. } else {
  1795. // 其他平台的默认处理
  1796. this.keyboardHeight = res.height * 2;
  1797. }
  1798. // 确保键盘高度不为负数
  1799. this.keyboardHeight = Math.max(0, this.keyboardHeight);
  1800. console.log('处理后的键盘高度:', this.keyboardHeight, '键盘显示状态:', this.isKeyboardShow);
  1801. });
  1802. },
  1803. getTimeDifferenceInSeconds(createTimeStr) {
  1804. const createTime = new Date(createTimeStr.replace(/-/g, '/'));
  1805. const now = new Date();
  1806. const timeDiffMs = now - createTime;
  1807. const timeDiffSeconds = Math.floor(timeDiffMs / 1000);
  1808. return Math.max(0, timeDiffSeconds);
  1809. },
  1810. // 录播时间点
  1811. onVideoMetaLoaded(e) {
  1812. this.videoProgressKey = `videoProgress_${this.liveId}`;
  1813. this.setVideoProgress();
  1814. },
  1815. setVideoProgress() {
  1816. // 只有录播和回放需要设置进度
  1817. if (this.liveItem.liveType !== 2 && this.liveItem.liveType !== 3) {
  1818. return;
  1819. }
  1820. let currentTime = 0;
  1821. if (this.liveItem.liveType === 2) {
  1822. // 录播:计算当前时间与开始时间的差值,对视频总时长取模
  1823. const diff = this.getTimeDifferenceInSeconds(this.liveItem.startTime);
  1824. if (diff > this.liveItem.duration) {
  1825. const storedProgress = uni.getStorageSync(this.videoProgressKey);
  1826. currentTime = storedProgress >= this.liveItem.duration ? 0 : storedProgress || 0;
  1827. } else {
  1828. currentTime = diff % this.liveItem.duration;
  1829. }
  1830. // currentTime = diff % this.liveItem.duration;
  1831. } else if (this.liveItem.liveType === 3) {
  1832. // 回放:从存储中获取进度
  1833. const storedProgress = uni.getStorageSync(this.videoProgressKey);
  1834. currentTime = storedProgress || 0;
  1835. }
  1836. const videoId = `myVideo_${this.liveId}`;
  1837. const videoContext = uni.createVideoContext(videoId, this);
  1838. if (videoContext) {
  1839. videoContext.seek(currentTime);
  1840. }
  1841. },
  1842. onVideoWaiting(e) {
  1843. // console.log('视频等待加载', e);
  1844. //流量
  1845. if (this.liveItem.liveType == 2) {
  1846. this.startTrafficCalculation(this.bitrate);
  1847. } else {
  1848. let that = this;
  1849. if (this.trafficInterval) {
  1850. clearInterval(this.trafficInterval);
  1851. this.trafficInterval = null;
  1852. }
  1853. this.trafficInterval = setInterval(function () {
  1854. that.getInternetTraffic();
  1855. }, 10000);
  1856. }
  1857. },
  1858. // 视频时间更新
  1859. onVideoTimeUpdate(e) {
  1860. // 获取当前播放时间
  1861. this.videoCurrentTime = e.detail.currentTime;
  1862. // 每隔10秒保存一次进度(避免频繁存储)
  1863. if (Math.floor(this.videoCurrentTime) % 10 === 0) {
  1864. this.saveVideoProgress();
  1865. }
  1866. // this.setVideoProgress();
  1867. },
  1868. // 视频暂停
  1869. onVideoPause(e) {
  1870. if (this.liveItem.liveType === 2) {
  1871. const videoId = `myVideo_${this.liveId}`;
  1872. const videoContext = uni.createVideoContext(videoId, this);
  1873. setTimeout(() => {
  1874. videoContext.play();
  1875. }, 100);
  1876. }
  1877. // 暂停时保存进度
  1878. this.saveVideoProgress();
  1879. },
  1880. // 视频播放
  1881. onVideoPlay(e) {},
  1882. // 设置视频当前时间
  1883. // setVideoCurrentTime(time) {
  1884. // if (!time) return;
  1885. // const videoId = `myVideo_${this.liveId}`;
  1886. // const videoContext = uni.createVideoContext(videoId, this);
  1887. // if (videoContext) {
  1888. // videoContext.seek(time);
  1889. // console.log(`设置视频播放位置: ${time}秒`);
  1890. // }
  1891. // },
  1892. // 保存视频进度
  1893. saveVideoProgress() {
  1894. if (this.videoProgressKey) {
  1895. uni.setStorage({
  1896. key: this.videoProgressKey,
  1897. data: this.videoCurrentTime,
  1898. success: () => {},
  1899. fail: (err) => {
  1900. console.error('保存视频进度失败:', err);
  1901. }
  1902. });
  1903. }
  1904. },
  1905. // 点击红包
  1906. onRed() {
  1907. if (!this.liveId) return;
  1908. if (!this.redInfo?.redId) return;
  1909. if (this.redTimer) {
  1910. clearInterval(this.redTimer);
  1911. this.redTimer = null;
  1912. }
  1913. let data = {
  1914. liveId: this.liveId,
  1915. userId: this.userData.userId,
  1916. redId: this.redInfo.redId
  1917. };
  1918. liveRed(data).then(
  1919. (res) => {
  1920. this.isShowRed = false;
  1921. this.redCard = res;
  1922. this.isShowRedCard = true;
  1923. },
  1924. (rej) => {}
  1925. );
  1926. },
  1927. //领取优惠券
  1928. onCoupon() {
  1929. if (!this.couponInfo.couponIssueId) return;
  1930. let data = {
  1931. goodsId: this.couponInfo.goodsId,
  1932. couponIssueId: this.couponInfo.couponIssueId,
  1933. liveId: this.liveId
  1934. };
  1935. coupon(data)
  1936. .then((res) => {
  1937. this.isShowCoupon = false;
  1938. if (res.code == 200) {
  1939. uni.showToast({
  1940. title: res.msg,
  1941. icon: 'none'
  1942. });
  1943. } else {
  1944. uni.showToast({
  1945. title: res.msg,
  1946. icon: 'none'
  1947. });
  1948. }
  1949. })
  1950. .catch((rej) => {});
  1951. },
  1952. // 我的中奖名单
  1953. getMyLottery() {
  1954. this.winning = true;
  1955. myLottery()
  1956. .then((res) => {
  1957. if (res.code == 200) {
  1958. // console.log("我的中奖名单", res)
  1959. this.prizeAll = res.data.list || {};
  1960. } else {
  1961. }
  1962. })
  1963. .catch((rej) => {});
  1964. },
  1965. // 抽奖
  1966. onLottery() {
  1967. if (!this.lotteryInfo) return;
  1968. let data = {
  1969. lotteryId: this.lotteryInfo.lotteryId
  1970. };
  1971. liveLottery(data)
  1972. .then((res) => {
  1973. if (res.code == 200) {
  1974. const resData = res.data || {};
  1975. this.lotteryList = Array.isArray(resData) ? resData : [];
  1976. this.lotteryProducts = Array.isArray(resData.products) ? resData.products : [];
  1977. if (resData.duration) {
  1978. this.isShowLotteryPop = true;
  1979. }
  1980. } else {
  1981. uni.showToast({
  1982. title: res.msg,
  1983. icon: 'none'
  1984. });
  1985. this.lotteryList = [];
  1986. this.lotteryProducts = [];
  1987. }
  1988. })
  1989. .catch((rej) => {
  1990. uni.showToast({
  1991. title: '获取抽奖信息失败',
  1992. icon: 'none'
  1993. });
  1994. // 失败时强制重置为数组
  1995. this.lotteryList = [];
  1996. this.lotteryProducts = [];
  1997. });
  1998. },
  1999. // 参与抽奖
  2000. onClaim() {
  2001. let data = {
  2002. liveId: this.liveId,
  2003. lotteryId: this.lotteryInfo.lotteryId
  2004. };
  2005. claim(data).then(
  2006. (res) => {
  2007. if (res.code == 200) {
  2008. uni.showToast({
  2009. title: res.msg,
  2010. icon: 'none'
  2011. });
  2012. this.isShowLotteryPop = false;
  2013. this.havePrize = true;
  2014. uni.setStorageSync('havePrize', this.havePrize);
  2015. } else {
  2016. uni.showToast({
  2017. title: res.msg,
  2018. icon: 'none'
  2019. });
  2020. }
  2021. },
  2022. (rej) => {}
  2023. );
  2024. },
  2025. confirm() {
  2026. this.isShowPrize = false;
  2027. this.havePrize = false;
  2028. uni.setStorageSync('havePrize', this.havePrize);
  2029. },
  2030. // 商品收藏
  2031. onGoodsCollect(item) {
  2032. if (!item || item.length === 0 || !item.goodsId) {
  2033. return;
  2034. }
  2035. collectGoods(item.goodsId).then(
  2036. (res) => {
  2037. if (res.code == 200) {
  2038. uni.showToast({
  2039. title: res.msg,
  2040. icon: 'none'
  2041. });
  2042. item.isFavorite = !item.isFavorite;
  2043. } else {
  2044. uni.showToast({
  2045. title: res.msg,
  2046. icon: 'none'
  2047. });
  2048. }
  2049. },
  2050. (rej) => {}
  2051. );
  2052. },
  2053. //正在购买
  2054. getliveOrder(item) {
  2055. if (!this.liveId) {
  2056. return;
  2057. }
  2058. liveOrderUser(this.liveId).then(
  2059. (res) => {
  2060. if (res.code == 200) {
  2061. this.orderUser = res;
  2062. } else {
  2063. console.log('获取正在购买用户失败');
  2064. }
  2065. },
  2066. (rej) => {}
  2067. );
  2068. },
  2069. onLiveStateChange(e, liveItem) {
  2070. // 可以根据状态码处理不同的直播状态
  2071. const stateCode = e.detail.code;
  2072. if (e.detail.code == -2301 || e.detail.code == -2302) {
  2073. this.playVideo();
  2074. } else if (e.detail.code == 2004) {
  2075. this.calculateTimeDiff(this.liveItem);
  2076. this.startTrafficCalculation(this.bitrateLive);
  2077. }
  2078. // 2001: 已经连接服务器
  2079. // 2002: 已经连接服务器,开始拉流
  2080. // 2003: 网络接收到首个视频数据包(IDR)
  2081. // 2004: 视频播放开始
  2082. // 2005: 视频播放进度
  2083. // 2006: 视频播放结束
  2084. // 2007: 视频播放Loading
  2085. // 2008: 解码器启动
  2086. // -2301: 网络断连,且经多次重连抢救无效,更多重试请自行重启播放
  2087. // -2302: 获取加速拉流地址失败
  2088. }, // 直播错误事件
  2089. onLiveError(e, liveItem) {
  2090. this.videoError(e, liveItem);
  2091. console.log('错误');
  2092. },
  2093. // 红包 卡片 抽奖
  2094. getCurrentActivities() {
  2095. if (!this.liveId) return;
  2096. currentActivities(this.liveId).then(
  2097. (res) => {
  2098. if (res.code === 200) {
  2099. // 提取数据(默认空数组/对象避免报错)
  2100. this.redInfo = (Array.isArray(res.red) ? res.red : [])[0] || {};
  2101. this.lotteryInfo = (Array.isArray(res.lottery) ? res.lottery : [])[0] || {};
  2102. this.goodsCard = res.goods || {};
  2103. this.isShowGoods = this.goodsCard && this.goodsCard.status == 1;
  2104. this.isShowRed = this.redInfo && this.redInfo.redStatus == 1;
  2105. this.isShowLottery = this.lotteryInfo && this.lotteryInfo.lotteryStatus == 1;
  2106. if (this.isShowRed) {
  2107. this.redTimer = setInterval(() => {
  2108. const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo.duration);
  2109. if (!redCountdown) {
  2110. this.isShowRed = false;
  2111. clearInterval(this.redTimer);
  2112. }
  2113. }, 1000);
  2114. }
  2115. // 处理抽奖定时器
  2116. if (this.isShowLottery) {
  2117. this.lotteryTimer = setInterval(() => {
  2118. this.countdown = this.handleTime(this.lotteryInfo.updateTime, this.lotteryInfo.duration);
  2119. }, 1000);
  2120. }
  2121. } else {
  2122. uni.showToast({
  2123. title: res.msg,
  2124. icon: 'none'
  2125. });
  2126. }
  2127. },
  2128. (rej) => {}
  2129. );
  2130. },
  2131. // 计算当前时间与 liveItem.startTime 的差值,并更新 totalTime
  2132. calculateTimeDiff(item) {
  2133. if (!item.startTime) return;
  2134. // 提取对应场景的时间字符串(直播用startTime,抽奖用updateTime)
  2135. let timeStr = item.startTime;
  2136. // 转换时间格式(适配iOS,将 "-" 替换为 "/")
  2137. const time = new Date(timeStr.replace(/-/g, '/'));
  2138. if (isNaN(time.getTime())) {
  2139. return;
  2140. }
  2141. const now = new Date();
  2142. let diffMs = Math.max(0, now.getTime() - time.getTime());
  2143. // 转换为 时:分:秒(补零处理)
  2144. const totalSeconds = Math.floor(diffMs / 1000);
  2145. const hours = this.padZero(Math.floor(totalSeconds / 3600));
  2146. const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
  2147. const seconds = this.padZero(totalSeconds % 60);
  2148. this.diffTotalTime = `${hours}:${minutes}:${seconds}`;
  2149. // this.$set(this.liveItem, "diffMs", diffMs);
  2150. // this.$set(this.liveItem, "totalSeconds", totalSeconds);
  2151. },
  2152. padZero(num) {
  2153. return num < 10 ? `0${num}` : num;
  2154. },
  2155. // 启动当前直播间的时间差值定时器
  2156. startTimeTimer(item) {
  2157. if (!item) return;
  2158. // 立即计算一次(避免等待1秒才显示)
  2159. const totalTime = this.calculateTimeDiff(item);
  2160. item.timeTimer = setInterval(() => {
  2161. const totalTime = this.calculateTimeDiff(item);
  2162. }, 1000);
  2163. },
  2164. toggleViewerList() {
  2165. const now = Date.now();
  2166. if (now - this.lastClickTime > this.clickDelay) {
  2167. this.showadd = !this.showadd;
  2168. if (this.showadd) {
  2169. this.getliveUser(false); // 加载第一页观众
  2170. }
  2171. this.lastClickTime = now;
  2172. }
  2173. },
  2174. // 播放视频
  2175. playVideo() {
  2176. if (!this.liveItem) {
  2177. console.log('liveItem 为空,无法播放视频');
  2178. return;
  2179. }
  2180. try {
  2181. // 直播流使用live-player
  2182. if (this.liveItem.liveType === 1 && this.liveItem.livingUrl && this.liveItem.status == 2) {
  2183. const livePlayerId = `myLivePlayer_${this.liveId}`;
  2184. const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  2185. // console.log("直播")
  2186. if (livePlayerContext) {
  2187. livePlayerContext.play();
  2188. }
  2189. } else if (this.liveItem.status == 1 && this.liveItem.previewUrl) {
  2190. const videoId = `myVideo_${this.liveId}`;
  2191. const videoContext = uni.createVideoContext(videoId, this);
  2192. if (videoContext) {
  2193. videoContext.play();
  2194. }
  2195. } else if (this.liveItem.liveType === 2 && this.liveItem.videoUrl && this.liveItem.status == 2) {
  2196. const videoId = `myVideo_${this.liveId}`;
  2197. const videoContext = uni.createVideoContext(videoId, this);
  2198. // console.log("录播")
  2199. if (videoContext) {
  2200. videoContext.play();
  2201. }
  2202. } // 回放视频使用video
  2203. else if (this.liveItem.liveType === 3 && this.liveItem.videoUrl && this.liveItem.status == 4) {
  2204. const videoId = `myVideo_${this.liveId}`;
  2205. const videoContext = uni.createVideoContext(videoId, this);
  2206. // console.log("回放")
  2207. if (videoContext) {
  2208. videoContext.play();
  2209. }
  2210. }
  2211. } catch (error) {
  2212. console.error('播放视频失败:', error);
  2213. }
  2214. },
  2215. pauseVideo() {
  2216. if (!this.liveItem) return;
  2217. try {
  2218. // 直播流使用live-player
  2219. if (this.liveItem.status == 1) {
  2220. const videoId = `myVideo_${this.liveId}`;
  2221. const videoContext = uni.createVideoContext(videoId, this);
  2222. if (videoContext) {
  2223. videoContext.pause();
  2224. }
  2225. } else if (this.liveItem.status == 2) {
  2226. if (this.liveItem.liveType === 1) {
  2227. const livePlayerId = `myLivePlayer_${this.liveId}`;
  2228. const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  2229. if (livePlayerContext) {
  2230. livePlayerContext.pause();
  2231. }
  2232. } else if (this.liveItem.liveType === 2) {
  2233. const videoId = `myVideo_${this.liveId}`;
  2234. const videoContext = uni.createVideoContext(videoId, this);
  2235. if (videoContext) {
  2236. videoContext.pause();
  2237. }
  2238. }
  2239. }
  2240. } catch (error) {
  2241. console.error('暂停视频失败:', error);
  2242. }
  2243. },
  2244. // 视频错误处理
  2245. videoError(e, liveItem) {
  2246. if (!liveItem || !this.liveId) return;
  2247. // 初始化重试计数
  2248. if (this.videoRetryCounts[liveItem.liveId] === undefined) {
  2249. this.videoRetryCounts[liveItem.liveId] = 0;
  2250. }
  2251. // 限制重试次数
  2252. if (this.videoRetryCounts[liveItem.liveId] >= 3) {
  2253. console.error(`直播间 ${this.liveId} 视频加载失败,停止重试`);
  2254. // 显示错误提示
  2255. uni.showToast({
  2256. title: '视频加载失败,请检查网络',
  2257. icon: 'none',
  2258. duration: 2000
  2259. });
  2260. return;
  2261. }
  2262. this.videoRetryCounts[this.liveId]++;
  2263. // 延迟重试
  2264. setTimeout(() => {
  2265. if (this.liveId === this.liveId) {
  2266. console.log(`第${this.videoRetryCounts[this.liveId]}次重试播放视频`);
  2267. this.playVideo();
  2268. }
  2269. }, 2000);
  2270. },
  2271. openViews() {
  2272. // 计算scroll-view高度
  2273. this.$nextTick(() => {
  2274. const query = uni.createSelectorQuery().in(this);
  2275. query
  2276. .select('.view-box')
  2277. .boundingClientRect((data) => {
  2278. if (data) {
  2279. this.scrollHeight = data.height - 80; // 80是标题高度,120是底部高度
  2280. }
  2281. })
  2282. .exec();
  2283. });
  2284. },
  2285. // 滚动到底部触发
  2286. handleScrollToLower() {
  2287. // 清除上一次未执行的定时器,避免重复请求
  2288. if (this.scrollTimer) {
  2289. clearTimeout(this.scrollTimer);
  2290. }
  2291. // 延迟0.5秒(500毫秒)执行接口请求
  2292. this.scrollTimer = setTimeout(() => {
  2293. this.getliveUser(true);
  2294. }, 1000);
  2295. },
  2296. async getLiveMsg(liveItem) {
  2297. if (!liveItem || !this.liveId) {
  2298. console.error('getLiveMsg 错误:无效的 liveItem');
  2299. return;
  2300. }
  2301. try {
  2302. const res = await liveMsg(this.liveId, 30, 1);
  2303. if (res.code == 200) {
  2304. const rows = Array.isArray(res.rows) ? res.rows : [];
  2305. const reversedTalkList = [...rows].reverse();
  2306. this.talklist = Array.isArray(reversedTalkList) ? reversedTalkList : [];
  2307. // 获取历史消息后也滚动到底部
  2308. this.$nextTick(() => {
  2309. this.scrollToBottom();
  2310. });
  2311. } else {
  2312. this.talklist = [];
  2313. }
  2314. } catch (error) {
  2315. this.talklist = [];
  2316. console.error('获取聊天记录失败:', error);
  2317. }
  2318. },
  2319. generateRandomChineseName() {
  2320. const prefixes = [
  2321. '幸福',
  2322. '快乐',
  2323. '安康',
  2324. '吉祥',
  2325. '如意',
  2326. '平安',
  2327. '健康',
  2328. '长寿',
  2329. '福气',
  2330. '美满',
  2331. '和谐',
  2332. '团圆',
  2333. '富贵',
  2334. '荣华',
  2335. '宁静',
  2336. '淡泊',
  2337. '知足',
  2338. '常乐',
  2339. '悠然',
  2340. '自在',
  2341. '夕阳',
  2342. '晚霞',
  2343. '金秋',
  2344. '银发',
  2345. '老顽童',
  2346. '开心',
  2347. '笑口常开',
  2348. '岁月静好',
  2349. '云淡风轻',
  2350. '海阔天空'
  2351. ];
  2352. const suffixes = [
  2353. '老人',
  2354. '大爷',
  2355. '大妈',
  2356. '爷爷',
  2357. '奶奶',
  2358. '伯伯',
  2359. '阿姨',
  2360. '前辈',
  2361. '先生',
  2362. '女士',
  2363. '长者',
  2364. '翁',
  2365. '婆',
  2366. '哥',
  2367. '姐',
  2368. '友',
  2369. '客',
  2370. '迷',
  2371. '粉丝',
  2372. '达人',
  2373. '爱好者',
  2374. '之家',
  2375. '之人',
  2376. '之心',
  2377. '之情',
  2378. '之乐',
  2379. '之旅',
  2380. '之梦',
  2381. '之歌',
  2382. '之韵'
  2383. ];
  2384. const specialNames = [
  2385. '老有所乐',
  2386. '知足常乐',
  2387. '笑看人生',
  2388. '云淡风轻',
  2389. '岁月如歌',
  2390. '夕阳红',
  2391. '金色年华',
  2392. '老当益壮',
  2393. '鹤发童颜',
  2394. '老骥伏枥',
  2395. '闲云野鹤',
  2396. '淡泊明志',
  2397. '宁静致远',
  2398. '随遇而安',
  2399. '顺其自然',
  2400. '老来俏',
  2401. '开心果',
  2402. '老宝贝',
  2403. '不老松',
  2404. '常青树'
  2405. ];
  2406. // 30%概率使用特殊网名,70%使用前缀+后缀组合
  2407. if (Math.random() < 0.3) {
  2408. return specialNames[Math.floor(Math.random() * specialNames.length)];
  2409. } else {
  2410. const prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
  2411. const suffix = suffixes[Math.floor(Math.random() * suffixes.length)];
  2412. return prefix + suffix;
  2413. }
  2414. },
  2415. // 获取直播间用户
  2416. async getliveUser(isLoadMore = false) {
  2417. this.viewLoading = true;
  2418. try {
  2419. const res = await watchUserList(this.liveId, this.viewPageSize, this.viewPageNum, false);
  2420. if (res.code === 200) {
  2421. const userRows = Array.isArray(res.rows) ? res.rows : [];
  2422. let array = userRows.map((item) => ({
  2423. avatar: item.avatar || '',
  2424. userId: item.userId || '',
  2425. nickName: item.nickName || '未命名'
  2426. }));
  2427. // 虚拟数据
  2428. let virtualData = [];
  2429. let virtualTotal = res.total * 2 + 50;
  2430. this.liveUserTotal = virtualTotal;
  2431. for (let i = 0; i < virtualTotal; i++) {
  2432. let data = {
  2433. avatar: '',
  2434. userId: '8565' + i,
  2435. nickName: this.generateRandomChineseName()
  2436. };
  2437. virtualData.push(data);
  2438. }
  2439. this.liveViewersData = [...array, ...virtualData];
  2440. const newRows = Array.isArray(res.rows) ? res.rows : [];
  2441. const currentViewers = Array.isArray(this.liveViewers) ? this.liveViewers : [];
  2442. let viewlist = isLoadMore ? [...currentViewers, ...newRows] : newRows;
  2443. this.liveViewers = [...viewlist, ...virtualData];
  2444. this.viewPageNum++;
  2445. }
  2446. } catch (error) {
  2447. console.error('获取观众列表失败:', error);
  2448. } finally {
  2449. this.viewLoading = false;
  2450. }
  2451. },
  2452. //小黄车搜索商品
  2453. handleSearchInput() {
  2454. // 使用防抖优化性能,避免频繁请求
  2455. clearTimeout(this.searchTimer);
  2456. this.searchTimer = setTimeout(() => {
  2457. this.queryCollect();
  2458. }, 500); // 500毫秒延迟
  2459. },
  2460. // 显示购买提示信息
  2461. showPurchaseMessage() {
  2462. // 清除之前的定时器
  2463. if (this.purchasePromptTimer) {
  2464. clearTimeout(this.purchasePromptTimer);
  2465. }
  2466. // 显示提示
  2467. this.showPurchasePrompt = true;
  2468. // 2秒后自动隐藏
  2469. this.purchasePromptTimer = setTimeout(() => {
  2470. this.showPurchasePrompt = false;
  2471. }, 2000);
  2472. },
  2473. //名字超过省略
  2474. truncateString(str, maxLength) {
  2475. if (typeof str !== 'string' || str.length <= maxLength) {
  2476. return str;
  2477. }
  2478. return str.slice(0, maxLength) + '...'; // 截断后加省略号
  2479. },
  2480. // 跳转页面
  2481. navgetTo(url) {
  2482. uni.navigateTo({
  2483. url: url
  2484. });
  2485. },
  2486. // 修改获取直播信息方法
  2487. async getliving(liveId) {
  2488. if (!liveId) return;
  2489. const param = {
  2490. id: liveId
  2491. };
  2492. try {
  2493. const res = await getlive(param);
  2494. if (res.code !== 200) {
  2495. uni.showToast({
  2496. title: res.msg,
  2497. icon: 'none'
  2498. });
  2499. return;
  2500. }
  2501. this.liveItem = Object.assign({}, this.liveItem, res.data);
  2502. // this.talklist = Array.isArray((res.data || {}).talklist) ? res.data.talklist : [];
  2503. this.startTimeTimer(this.liveItem);
  2504. // 清除旧定时器(如预告倒计时)
  2505. if (this.liveStartTimer) {
  2506. clearInterval(this.liveStartTimer);
  2507. this.liveStartTimer = null;
  2508. }
  2509. if (res.data.status == 1) {
  2510. // 直播预告
  2511. this.liveStartTimer = setInterval(async () => {
  2512. this.liveCountdown = this.handleTime(res.data.startTime, 0);
  2513. if (!this.liveCountdown) {
  2514. uni.removeStorageSync('isAgreement');
  2515. await this.getliving(this.liveId);
  2516. clearInterval(this.liveStartTimer);
  2517. }
  2518. }, 1000);
  2519. this.$set(this.liveItem, 'previewUrl', res.data.previewUrl);
  2520. this.$set(this.liveItem, 'livingUrl', ''); // 清空直播流
  2521. this.$set(this.liveItem, 'videoUrl', ''); // 清空回放视频
  2522. } else if (res.data.status == 2) {
  2523. if (res.data.liveType == 1) {
  2524. // 直播流
  2525. let cTime = Math.floor(Math.random() * 10000) + 1;
  2526. let livingUrl = res.data.flvHlsUrl + '&t=' + cTime;
  2527. console.log('地址在', this.liveItem.livingUrl);
  2528. this.$set(this.liveItem, 'livingUrl', livingUrl);
  2529. this.$set(this.liveItem, 'videoUrl', ''); // 清空回放视频
  2530. } else if (res.data.liveType === 2) {
  2531. // 回放视频 2录播 3直播回放
  2532. // let urlStr = 'https://fs-1319721001.cos.ap-chongqing.myqcloud.com/10%E6%9C%8820%E6%97%A5%20%281%29.m3u8'
  2533. // this.$set(this.liveItem, 'videoUrl', urlStr);
  2534. this.$set(this.liveItem, 'videoUrl', res.data.videoUrl);
  2535. this.$set(this.liveItem, 'livingUrl', '');
  2536. }
  2537. } else if (res.data.status == 4 && res.data.liveType == 3) {
  2538. this.$set(this.liveItem, 'videoUrl', res.data.videoUrl);
  2539. this.$set(this.liveItem, 'livingUrl', '');
  2540. } else {
  2541. // 未开播
  2542. this.$set(this.liveItem, 'livingUrl', '');
  2543. this.$set(this.liveItem, 'videoUrl', '');
  2544. }
  2545. this.$set(this.liveItem, 'autoplay', res.data.liveType !== 0);
  2546. this.$set(this.liveItem, 'showType', res.data.showType);
  2547. this.storeId = res.storeId;
  2548. // 启动“30秒刷新直播间数据”的定时器
  2549. this.startLiveViewDataTimer();
  2550. this.playVideo();
  2551. } catch (err) {
  2552. console.error('获取直播信息失败:', err);
  2553. uni.showToast({
  2554. title: '获取直播信息失败',
  2555. icon: 'none'
  2556. });
  2557. }
  2558. },
  2559. getPureDecimal(num, precision = 6) {
  2560. const decimalPart = Math.abs(num).toFixed(precision).split('.')[1];
  2561. return decimalPart?.replace(/0+$/, '') || ''; // 移除末尾多余的0
  2562. },
  2563. goBack() {
  2564. // 暂停当前视频
  2565. if (this.liveItem) {
  2566. this.pauseVideo();
  2567. }
  2568. // 关闭WebSocket连接
  2569. this.closeWebSocket(true);
  2570. // 导航返回
  2571. const pages = getCurrentPages();
  2572. if (pages.length > 1) {
  2573. uni.navigateBack();
  2574. } else {
  2575. uni.reLaunch({
  2576. url: '/pages_course/livingList'
  2577. });
  2578. }
  2579. },
  2580. // 点赞
  2581. async onLike() {
  2582. if (!this.liveId) return;
  2583. try {
  2584. const res = await liveDataLike(this.liveId);
  2585. if (res?.like) {
  2586. this.liveViewData.like++; // 只更新当前直播间的点赞数
  2587. } else {
  2588. uni.showToast({
  2589. title: res.msg,
  2590. icon: 'none'
  2591. });
  2592. }
  2593. } catch (error) {
  2594. console.error('点赞失败:', error);
  2595. }
  2596. },
  2597. //直播间点赞、关注、在线人数数据
  2598. getliveViewData(liveItem) {
  2599. if (!liveItem || !this.liveId) return;
  2600. getLiveViewData(this.liveId)
  2601. .then((res) => {
  2602. if (res.code == 200) {
  2603. // 强制响应式更新,确保数据实时显示
  2604. this.liveViewData = res;
  2605. }
  2606. })
  2607. .catch((error) => {
  2608. console.error('获取直播间数据失败:', error);
  2609. // 失败时兜底,避免显示异常
  2610. this.liveViewData = {
  2611. like: 0,
  2612. watchCount: 0
  2613. };
  2614. });
  2615. },
  2616. // 30秒刷新一下直播间点赞数
  2617. startLiveViewDataTimer() {
  2618. // 先清除旧定时器(防止重复创建)
  2619. if (this.liveViewDataTimer) {
  2620. clearInterval(this.liveViewDataTimer);
  2621. this.liveViewDataTimer = null;
  2622. }
  2623. // 启动新定时器,每3秒执行一次
  2624. this.liveViewDataTimer = setInterval(() => {
  2625. // 安全校验:确保liveItem和liveId存在(避免无效请求)
  2626. if (this.liveItem && this.liveId) {
  2627. this.getliveViewData(this.liveItem);
  2628. }
  2629. }, 30000);
  2630. },
  2631. // 去购买,跳商品详情
  2632. goShop(productId, goodsId) {
  2633. if (!this.liveId) return;
  2634. uni.navigateTo({
  2635. url: '/pages_shopping/live/goods?productId=' + productId + '&liveId=' + this.liveId + '&goodsId=' + goodsId + '&storeId=' + this.storeId
  2636. });
  2637. },
  2638. // 查询店铺
  2639. async queryCollect() {
  2640. this.loadingProducts = true;
  2641. if (!this.liveId) return;
  2642. if (this.inputInfo == null) this.inputInfo = '';
  2643. uni.showLoading({
  2644. title: '加载中'
  2645. });
  2646. try {
  2647. const res = await liveStore(this.liveId, this.inputInfo);
  2648. uni.hideLoading();
  2649. this.shopping = true;
  2650. if (res.code === 200) {
  2651. // 数据绑定到当前 liveItem,避免全局污染
  2652. this.products = Array.isArray(res.data) ? res.data : [];
  2653. }
  2654. } catch (error) {
  2655. console.error('获取小黄车商品失败:', error);
  2656. } finally {
  2657. this.loadingProducts = false;
  2658. }
  2659. },
  2660. // 时间戳
  2661. initTime() {
  2662. const now = new Date();
  2663. this.timestamp = now.getTime();
  2664. },
  2665. openCart() {
  2666. this.queryCollect();
  2667. },
  2668. close() {
  2669. this.showadd = false;
  2670. },
  2671. // 关闭小黄车
  2672. closeShop() {
  2673. this.shopping = false;
  2674. },
  2675. closeMore() {
  2676. this.isMore = false;
  2677. },
  2678. closeWin() {
  2679. this.winning = false;
  2680. },
  2681. // 关闭WebSocket连接(isManual:是否手动关闭)
  2682. closeWebSocket(isManual = true) {
  2683. if (!this.socket || !this.isSocketOpen) {
  2684. console.warn('WebSocket 任务不存在或未打开,无需关闭');
  2685. return;
  2686. }
  2687. console.log(`WebSocket连接关闭 - ${isManual ? '手动' : '自动'}`);
  2688. this.isManualClose = isManual;
  2689. // 清理所有定时器和状态
  2690. this.cleanupAllResources();
  2691. try {
  2692. // 先保存引用,避免在关闭过程中被置为null
  2693. const socketToClose = this.socket;
  2694. this.socket = null;
  2695. this.isSocketOpen = false;
  2696. this.isConnecting = false;
  2697. socketToClose.close({
  2698. code: 1000,
  2699. reason: isManual ? '主动关闭' : '异常关闭'
  2700. });
  2701. console.log('WebSocket连接已发起关闭');
  2702. } catch (err) {
  2703. console.error('关闭WebSocket失败:', err);
  2704. // 即使关闭失败,也要重置状态
  2705. this.socket = null;
  2706. this.isSocketOpen = false;
  2707. this.isConnecting = false;
  2708. }
  2709. },
  2710. // 清理所有资源
  2711. cleanupAllResources() {
  2712. // 停止心跳相关
  2713. this.stopHeartBeat();
  2714. // 清理ping超时定时器
  2715. if (this.pingTimeoutTimer) {
  2716. clearTimeout(this.pingTimeoutTimer);
  2717. this.pingTimeoutTimer = null;
  2718. }
  2719. // 清理网络状态定时器
  2720. if (this.networkStatusTimer) {
  2721. clearTimeout(this.networkStatusTimer);
  2722. this.networkStatusTimer = null;
  2723. }
  2724. // 重置重连状态
  2725. this.resetReconnectState();
  2726. // 重置心跳相关状态
  2727. this.heartBeatRetryCount = 0;
  2728. this.lastHeartBeatTime = 0;
  2729. this.adaptiveHeartBeatInterval = this.heartBeatInterval;
  2730. },
  2731. startHeartBeat() {
  2732. this.stopHeartBeat(); // 先停止现有心跳,防止重复
  2733. this.sendHeartBeat(); // 立即发送一次心跳
  2734. // 使用自适应间隔循环发送心跳
  2735. this.heartBeatTimer = setInterval(() => {
  2736. this.sendHeartBeat();
  2737. }, this.adaptiveHeartBeatInterval);
  2738. },
  2739. initSocket() {
  2740. // 检查是否正在连接中
  2741. if (this.isConnecting) {
  2742. console.log('WebSocket正在连接中,跳过重复连接');
  2743. return;
  2744. }
  2745. // 检查网络状态
  2746. if (!this.isNetworkAvailable) {
  2747. console.warn('网络不可用,延迟WebSocket连接');
  2748. setTimeout(() => this.initSocket(), 3000);
  2749. return;
  2750. }
  2751. // 如果已经存在连接且状态为open,则退出
  2752. if (this.socket && this.socket.readyState === 1) {
  2753. console.log('WebSocket连接已存在且正常,无需重新连接');
  2754. return;
  2755. }
  2756. // 关闭现有连接
  2757. if (this.socket && (this.socket.readyState === 0 || this.socket.readyState === 1)) {
  2758. console.log('关闭现有WebSocket连接,创建新连接');
  2759. this.closeWebSocket(false); // 非手动关闭
  2760. }
  2761. // 校验必要参数
  2762. if (!this.liveId) {
  2763. console.error('缺失直播间ID,无法初始化WebSocket');
  2764. return;
  2765. }
  2766. if (!this.userData || !this.userData.userId) {
  2767. console.error('用户信息缺失,无法初始化WebSocket');
  2768. return;
  2769. }
  2770. // 设置连接状态
  2771. this.isConnecting = true;
  2772. this.isSocketOpen = false;
  2773. // 记录连接开始时间(性能监控)
  2774. this.connectionStartTime = Date.now();
  2775. // 清除之前的重连定时器
  2776. this.resetReconnectState();
  2777. const now = new Date();
  2778. this.timestamp = now.getTime(); // 生成签名
  2779. const signature = CryptoJS.HmacSHA256(`${this.liveId}${this.userData.userId}${this.userType}${this.timestamp}`, this.timestamp.toString()).toString(CryptoJS.enc.Hex);
  2780. try {
  2781. const baseWsUrl = 'wss://im.fhhx.runtzh.com/ws/app/webSocket';
  2782. //const baseWsUrl = 'wss://api.fhhx.runtzh.com/ws/app/webSocket';
  2783. // const baseWsUrl = 'ws://192.168.10.166:7114/ws/app/webSocket';
  2784. let wsUrl = `${baseWsUrl}?userId=${this.userData.userId}&liveId=${this.liveId}&userType=${this.userType}&timestamp=${this.timestamp}&signature=${signature}`;
  2785. if (this.qrFrom) {
  2786. wsUrl += this.qrFrom;
  2787. }
  2788. console.log(`尝试连接WebSocket: ${wsUrl.replace(/signature=[^&]+/, 'signature=***')}`);
  2789. const socketTask = uni.connectSocket({
  2790. url: wsUrl,
  2791. success: () => {
  2792. console.log("WebSocket连接请求发送成功");
  2793. },
  2794. fail: (err) => {
  2795. console.error('WebSocket连接请求失败:', err);
  2796. this.isConnecting = false;
  2797. this.handleConnectionError('连接请求失败', err);
  2798. }
  2799. });
  2800. this.socket = socketTask;
  2801. // 连接打开事件
  2802. socketTask.onOpen((res) => {
  2803. console.log("WebSocket连接已打开");
  2804. this.isConnecting = false;
  2805. this.isSocketOpen = true;
  2806. // 计算连接延迟(性能监控)
  2807. if (this.connectionStartTime > 0) {
  2808. this.connectionLatency = Date.now() - this.connectionStartTime;
  2809. console.log(`WebSocket连接延迟: ${this.connectionLatency}ms`);
  2810. }
  2811. this.reconnectCount = 0;
  2812. this.resetReconnectState();
  2813. this.heartBeatRetryCount = 0; // 重置心跳重试次数
  2814. this.shownEntryUsers.clear(); // 重连后重置进入提示记录
  2815. // 连接成功后显示提示(仅首次连接)
  2816. if (this.reconnectCount === 0) {
  2817. console.log('WebSocket连接建立成功');
  2818. } else {
  2819. console.log(`WebSocket重连成功(第${this.reconnectCount}次尝试)`);
  2820. }
  2821. this.startHeartBeat();
  2822. });
  2823. // 消息接收事件
  2824. socketTask.onMessage((res) => {
  2825. // 消息计数(性能监控)
  2826. this.messageCount++;
  2827. try {
  2828. const data = JSON.parse(res.data);
  2829. // 处理服务端心跳响应
  2830. if (data.cmd === 'heartBeatAck') {
  2831. this.stopHeartBeat(); // 清除当前超时检测
  2832. this.startHeartBeat(); // 重新启动心跳周期
  2833. return;
  2834. }
  2835. this.handleSocketMessage(res);
  2836. } catch (err) {
  2837. console.error('消息解析异常:', err);
  2838. this.errorCount++; // 错误计数
  2839. }
  2840. });
  2841. // 连接错误事件
  2842. socketTask.onError((err) => {
  2843. console.error('WebSocket连接错误:', err);
  2844. this.errorCount++; // 错误计数
  2845. this.isSocketOpen = false;
  2846. this.isConnecting = false;
  2847. this.stopHeartBeat();
  2848. this.handleConnectionError('连接错误', err);
  2849. });
  2850. // 连接关闭事件
  2851. socketTask.onClose((res) => {
  2852. console.log('WebSocket连接关闭:', res);
  2853. this.isSocketOpen = false;
  2854. this.isConnecting = false;
  2855. this.stopHeartBeat(); // 清除心跳定时器
  2856. // 根据关闭原因决定是否重连
  2857. if (!this.isManualClose) {
  2858. if (res.code === 1000) {
  2859. console.log('WebSocket正常关闭,不进行重连');
  2860. } else {
  2861. console.warn(`WebSocket异常关闭 (code: ${res.code}, reason: ${res.reason})`);
  2862. this.handleReconnect();
  2863. }
  2864. } else {
  2865. console.log('WebSocket手动关闭,不进行重连');
  2866. }
  2867. });
  2868. } catch (e) {
  2869. console.error('创建WebSocket异常:', e);
  2870. this.handleReconnect();
  2871. }
  2872. },
  2873. handleTime(time, duration) {
  2874. // 将time转换为毫秒级时间戳
  2875. let timeStamp;
  2876. // 如果time是数字且合理(毫秒级时间戳通常为13位左右的正数),视为有效时间戳
  2877. if (typeof time === 'number' && time > 0 && time < 9999999999999) {
  2878. timeStamp = time;
  2879. }
  2880. //如果是字符串,尝试解析为日期后转为时间戳
  2881. else if (typeof time === 'string' && time.trim() !== '') {
  2882. // 处理兼容性:将"2025-09-25 17:30:00"转为ISO格式"2025-09-25T17:30:00"
  2883. const isoTime = time.replace(' ', 'T');
  2884. const date = new Date(isoTime);
  2885. // 校验日期是否有效
  2886. if (!isNaN(date.getTime())) {
  2887. timeStamp = date.getTime();
  2888. } else {
  2889. console.error('无效的日期格式:', time);
  2890. return false; // 格式错误时返回false
  2891. }
  2892. } else {
  2893. console.error('time参数必须是有效的时间戳(数字)或日期字符串');
  2894. return false;
  2895. }
  2896. // 后续逻辑保持不变(基于转换后的timeStamp计算)
  2897. const targetTimestamp = timeStamp + duration * 60 * 1000;
  2898. const currentTimestamp = new Date().getTime();
  2899. const timeDiffMs = targetTimestamp - currentTimestamp;
  2900. if (timeDiffMs <= 0) {
  2901. return false;
  2902. }
  2903. const hours = Math.floor(timeDiffMs / (1000 * 60 * 60));
  2904. const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60));
  2905. const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000);
  2906. const formatNum = (num) => num.toString().padStart(2, '0');
  2907. return {
  2908. hours: formatNum(hours),
  2909. minutes: formatNum(minutes),
  2910. seconds: formatNum(seconds)
  2911. };
  2912. },
  2913. // 限制聊天消息数量,防止内存泄漏
  2914. addToTalkList(message) {
  2915. // 减少最大消息数量,提升iPhone性能
  2916. const MAX_TALK_ITEMS = 30;
  2917. // 直接操作数组,避免创建新数组
  2918. if (!Array.isArray(this.talklist)) {
  2919. this.talklist = [];
  2920. }
  2921. this.talklist.push(message);
  2922. // 当消息超过限制时,批量删除旧消息
  2923. if (this.talklist.length > MAX_TALK_ITEMS) {
  2924. const removeCount = this.talklist.length - MAX_TALK_ITEMS;
  2925. this.talklist.splice(0, removeCount);
  2926. }
  2927. // 优化滚动调用频率
  2928. if (!this.scrollPending) {
  2929. this.scrollPending = true;
  2930. this.$nextTick(() => {
  2931. this.scrollToBottom();
  2932. this.scrollPending = false;
  2933. });
  2934. }
  2935. },
  2936. // 处理Socket消息
  2937. async handleSocketMessage(message) {
  2938. try {
  2939. let data = JSON.parse(message.data);
  2940. const socketMessage = data.data; // 服务端返回的消息体
  2941. if (data.code == 200) {
  2942. const messageData = {
  2943. ...socketMessage,
  2944. cmd: socketMessage.cmd || '', // 确保cmd字段存在
  2945. ts: Date.now() // 时间戳
  2946. };
  2947. // 处理服务端返回的sendMsg消息,加入本地列表
  2948. if (socketMessage.cmd == 'sendMsg') {
  2949. if (!this.isSocketAvailable()) {
  2950. uni.showToast({
  2951. title: '连接已断开,正在重试...',
  2952. icon: 'none'
  2953. });
  2954. this.handleReconnect();
  2955. return;
  2956. }
  2957. this.addToTalkList(messageData);
  2958. } else if (socketMessage.cmd == 'red') {
  2959. const redData = socketMessage.data ? JSON.parse(socketMessage.data) : {};
  2960. this.redInfo = redData || {};
  2961. this.isShowRed = socketMessage.status === 1;
  2962. if (this.isShowRed) {
  2963. this.redTimer = setInterval(() => {
  2964. const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo.duration);
  2965. if (!redCountdown) {
  2966. this.isShowRed = false;
  2967. clearInterval(this.redTimer);
  2968. }
  2969. }, 1000);
  2970. }
  2971. } else if (socketMessage.cmd == 'goods') {
  2972. const goodsData = socketMessage.data ? JSON.parse(socketMessage.data) : {};
  2973. this.goodsCard = goodsData || {};
  2974. this.isShowGoods = socketMessage.status == 1;
  2975. } else if (socketMessage.cmd == 'coupon') {
  2976. const couponData = socketMessage.data ? JSON.parse(socketMessage.data) : {};
  2977. this.couponInfo = couponData || {};
  2978. this.isShowCoupon = socketMessage.status === 1;
  2979. if (this.isShowCoupon) {}
  2980. } else if (socketMessage.cmd == 'lottery') {
  2981. const lotteryData = socketMessage.data ? JSON.parse(socketMessage.data) : {};
  2982. this.lotteryInfo = lotteryData || {};
  2983. this.isShowLottery = socketMessage.status === 1;
  2984. if (socketMessage.status != 1) {
  2985. this.isShowLotteryPop = false;
  2986. }
  2987. // 清除已有定时器(无论状态是否为1,先清掉旧的)
  2988. clearTimeout(this.lotteryTimer);
  2989. if (this.isShowLottery) {
  2990. this.lotteryTimer = setInterval(() => {
  2991. this.countdown = this.handleTime(this.lotteryInfo.updateTime, this.lotteryInfo.duration);
  2992. if (!this.countdown) {
  2993. console.log('倒计时', this.countdown);
  2994. this.isShowLottery = false;
  2995. this.isShowLotteryPop = false;
  2996. clearInterval(this.lotteryTimer);
  2997. }
  2998. }, 1000);
  2999. } else {
  3000. this.isShowLottery = false;
  3001. }
  3002. } else if (socketMessage.cmd == 'entry') {
  3003. try {
  3004. if (!this.liveUserCalled) {
  3005. await this.getliveUser(false);
  3006. this.liveUserCalled = true;
  3007. }
  3008. const userIdToEntry = socketMessage.userId;
  3009. const existingIndex = this.liveViewersData.findIndex((item) => item.userId === userIdToEntry);
  3010. if (existingIndex === -1) {
  3011. const liveViewers = {
  3012. userId: socketMessage.userId,
  3013. nickName: socketMessage.nickName,
  3014. avatar: socketMessage.avatar
  3015. };
  3016. this.liveViewersData.push(liveViewers);
  3017. this.liveUserTotal++;
  3018. }
  3019. // 解析用户ID(根据实际接口字段调整,此处假设data含userId)
  3020. const userData = JSON.parse(socketMessage.data || '{}');
  3021. const userId = userData.userId || socketMessage.userId; // 兼容不同字段
  3022. if (!userId) return; // 无用户ID不处理
  3023. // 仅新用户(未显示过)才触发提示
  3024. if (!this.shownEntryUsers.has(userId)) {
  3025. this.inAndOut = socketMessage;
  3026. this.showWelcomeMessage = true;
  3027. this.shownEntryUsers.add(userId); // 加入已显示集合
  3028. // 3秒后隐藏提示(可调整时长)
  3029. if (this.welcomeTimer) clearTimeout(this.welcomeTimer);
  3030. this.welcomeTimer = setTimeout(() => {
  3031. this.showWelcomeMessage = false;
  3032. }, 3000);
  3033. }
  3034. } catch (err) {
  3035. console.error('解析entry用户数据失败:', err);
  3036. }
  3037. } else if (socketMessage.cmd == 'out') {
  3038. if (this.liveUserTotal > 0) {
  3039. const userIdToRemove = socketMessage.userId;
  3040. const index = this.liveViewersData.findIndex((item) => item.userId === userIdToRemove);
  3041. if (index !== -1) {
  3042. this.liveViewersData.splice(index, 1);
  3043. this.liveUserTotal--; // 根据userId删除对应的用户数据
  3044. }
  3045. }
  3046. this.inAndOut = socketMessage;
  3047. this.showWelcomeMessage = true;
  3048. // 3秒后隐藏提示
  3049. if (this.welcomeTimer) clearTimeout(this.welcomeTimer);
  3050. this.welcomeTimer = setTimeout(() => {
  3051. this.showWelcomeMessage = false;
  3052. }, 3000);
  3053. } else if (socketMessage.cmd == 'live_start' || socketMessage.cmd == 'live_end') {
  3054. // 开始直播,关闭直播
  3055. if (this.liveStartTimer) {
  3056. clearInterval(this.liveStartTimer);
  3057. this.liveStartTimer = null;
  3058. }
  3059. if (this.redTimer) {
  3060. clearInterval(this.redTimer);
  3061. this.redTimer = null;
  3062. }
  3063. // 请求最新直播间数据
  3064. await this.getliving(this.liveId);
  3065. } else if (socketMessage.cmd == 'Integral') {
  3066. this.integral = {
  3067. msg: socketMessage.msg,
  3068. status: true
  3069. };
  3070. } else if (socketMessage.cmd == 'LotteryDetail') {
  3071. try {
  3072. this.prizeInfo = Array.isArray(JSON.parse(socketMessage.data || '[]')) ? JSON.parse(socketMessage.data || '[]') : [];
  3073. } catch (err) {
  3074. console.error('解析抽奖结果失败:', err);
  3075. this.prizeInfo = [];
  3076. }
  3077. this.isShowPrize = true;
  3078. this.isShowLottery = false;
  3079. this.isShowLotteryPop = false;
  3080. } else if (socketMessage.cmd == 'blockUser') {
  3081. uni.removeStorage({
  3082. key: 'AppToken',
  3083. success: () => {
  3084. uni.reLaunch({
  3085. url: '/pages/auth/login'
  3086. });
  3087. }
  3088. });
  3089. }
  3090. }
  3091. else {
  3092. uni.showToast({
  3093. title: data.msg,
  3094. icon: 'none'
  3095. });
  3096. }
  3097. } catch (error) {
  3098. console.error('Socket消息处理失败:', error);
  3099. }
  3100. },
  3101. sendMsg(retries = 1) {
  3102. // 防止连续点击发送两次(800ms短时锁定)
  3103. if (this.isSending) return;
  3104. this.isSending = true;
  3105. setTimeout(() => {
  3106. this.isSending = false;
  3107. }, 800);
  3108. const text = (this.value || '').trim();
  3109. if (!text) {
  3110. uni.showToast({
  3111. title: '不能发送空消息',
  3112. icon: 'none'
  3113. });
  3114. return;
  3115. }
  3116. if (!this.isSocketAvailable()) {
  3117. if (retries > 0) {
  3118. uni.showToast({
  3119. title: `连接不稳定,正在重试(${retries}次)...`,
  3120. icon: 'none'
  3121. });
  3122. // 延迟500ms重试,重试次数减1
  3123. setTimeout(() => this.sendMsg(retries - 1), 500);
  3124. } else {
  3125. uni.showToast({
  3126. title: '连接已断开,发送失败',
  3127. icon: 'none'
  3128. });
  3129. this.value = text; // 恢复输入框内容
  3130. }
  3131. return;
  3132. }
  3133. const liveId = this.liveId;
  3134. this.value = ''; // 立即清空输入框
  3135. // 构造发送给服务端的消息数据
  3136. const data = {
  3137. liveId,
  3138. userId: this.userData.userId,
  3139. userType: 0,
  3140. cmd: 'sendMsg',
  3141. msg: text,
  3142. nickName: this.userData.nickname || '未命名',
  3143. avatar: this.userData.avatar || '/static/images/avatar.png'
  3144. };
  3145. // 发送socket消息
  3146. try {
  3147. this.socket.send({
  3148. data: JSON.stringify(data),
  3149. success: () => {
  3150. this.value = '';
  3151. // 发送成功后滚动到底部
  3152. this.$nextTick(() => {
  3153. this.scrollToBottom();
  3154. });
  3155. },
  3156. fail: (err) => {
  3157. console.error('消息发送失败:', err);
  3158. if (retries > 0) {
  3159. uni.showToast({
  3160. title: `发送失败,正在重试(${retries}次)`,
  3161. icon: 'none'
  3162. });
  3163. setTimeout(() => this.sendMsg(retries - 1), 500);
  3164. } else {
  3165. uni.showToast({
  3166. title: '发送失败,请稍后再试',
  3167. icon: 'none'
  3168. });
  3169. this.value = text; // 恢复输入框内容
  3170. }
  3171. }
  3172. });
  3173. } catch (err) {
  3174. console.error('发送消息异常:', err);
  3175. if (retries > 0) {
  3176. setTimeout(() => this.sendMsg(retries - 1), 500);
  3177. } else {
  3178. uni.showToast({
  3179. title: '发送失败,请稍后再试',
  3180. icon: 'none'
  3181. });
  3182. this.value = text;
  3183. }
  3184. }
  3185. }
  3186. },
  3187. };
  3188. </script>
  3189. <style scoped lang="scss">
  3190. .skeleton-item {
  3191. display: flex;
  3192. padding: 20rpx;
  3193. background: #fff;
  3194. margin-bottom: 16rpx;
  3195. border-radius: 16rpx;
  3196. }
  3197. .skeleton-img {
  3198. width: 200rpx;
  3199. height: 200rpx;
  3200. background: #f0f0f0;
  3201. border-radius: 8rpx;
  3202. margin-right: 24rpx;
  3203. animation: pulse 1.5s ease-in-out infinite;
  3204. }
  3205. .skeleton-content {
  3206. flex: 1;
  3207. }
  3208. .skeleton-line {
  3209. height: 20rpx;
  3210. background: #f0f0f0;
  3211. margin-bottom: 16rpx;
  3212. border-radius: 4rpx;
  3213. animation: pulse 1.5s ease-in-out infinite;
  3214. }
  3215. .skeleton-line.short {
  3216. width: 60%;
  3217. }
  3218. .skeleton-line.medium {
  3219. width: 80%;
  3220. }
  3221. .skeleton-line.long {
  3222. width: 95%;
  3223. }
  3224. @keyframes pulse {
  3225. 0% {
  3226. opacity: 1;
  3227. }
  3228. 50% {
  3229. opacity: 0.5;
  3230. }
  3231. 100% {
  3232. opacity: 1;
  3233. }
  3234. }
  3235. ::v-deep .u-icon--right {
  3236. justify-content: flex-end !important;
  3237. }
  3238. // 无头像用户文字样式
  3239. .text-white {
  3240. color: #ffffff;
  3241. }
  3242. .text-xs {
  3243. font-size: 18rpx;
  3244. }
  3245. .text-sm {
  3246. font-size: 24rpx;
  3247. }
  3248. .w52,
  3249. .w72 {
  3250. display: flex;
  3251. align-items: center;
  3252. justify-content: center;
  3253. }
  3254. .swiper-wrapper {
  3255. position: relative;
  3256. width: 100%;
  3257. height: 100vh;
  3258. overflow: hidden;
  3259. background-color: #000000;
  3260. .container {
  3261. width: 100%;
  3262. height: 100%;
  3263. position: relative;
  3264. transition: opacity 0.3s ease;
  3265. transform: translateZ(0);
  3266. will-change: opacity;
  3267. }
  3268. }
  3269. .welcome-message {
  3270. position: fixed;
  3271. width: 100%;
  3272. bottom: 38vh;
  3273. left: 50%;
  3274. transform: translateX(-50%);
  3275. color: white;
  3276. padding: 10px 20px;
  3277. border-radius: 20px;
  3278. z-index: 10;
  3279. transition: opacity 0.3s ease;
  3280. }
  3281. .send {
  3282. background-color: #fafafa;
  3283. border-radius: 28rpx;
  3284. padding: 14rpx 16rpx;
  3285. color: #181818;
  3286. font-weight: 500;
  3287. }
  3288. /* 减少重绘和重排 */
  3289. .talk-list,
  3290. .viewer-item,
  3291. .message-item {
  3292. will-change: transform;
  3293. contain: layout style paint;
  3294. backface-visibility: hidden;
  3295. transform: translateZ(0);
  3296. }
  3297. .talk-list {
  3298. will-change: transform; // 提示浏览器优化
  3299. contain: layout style paint; // 限制渲染范围
  3300. max-width: 100%;
  3301. border-radius: 30rpx;
  3302. background-color: rgba(33, 33, 33, 0.5);
  3303. padding: 10rpx 30rpx;
  3304. }
  3305. .content {
  3306. position: relative;
  3307. z-index: 2;
  3308. height: 100%;
  3309. width: 100%;
  3310. top: 0;
  3311. left: 0;
  3312. display: flex;
  3313. flex-direction: column;
  3314. justify-content: space-between;
  3315. .activity-box {
  3316. position: fixed;
  3317. top: 188rpx;
  3318. left: 30rpx;
  3319. z-index: 999999;
  3320. display: flex;
  3321. align-items: center;
  3322. .item-box {
  3323. -webkit-transform: translateZ(0);
  3324. /* 硬件加速 */
  3325. transform: translateZ(0);
  3326. border-radius: 16rpx;
  3327. background-color: rgba(77, 77, 77, 0.5);
  3328. width: 90rpx;
  3329. height: 100rpx;
  3330. margin-right: 20rpx;
  3331. position: relative;
  3332. z-index: 999;
  3333. .tip {
  3334. position: absolute;
  3335. width: 100%;
  3336. bottom: 0;
  3337. color: #fafcff;
  3338. font-size: 26rpx;
  3339. background-color: rgba(15, 15, 15, 0.8);
  3340. border-radius: 16rpx;
  3341. text-align: center;
  3342. }
  3343. .item {
  3344. margin: 0 auto;
  3345. padding: 10rpx 0;
  3346. .img {
  3347. height: 100%;
  3348. }
  3349. }
  3350. }
  3351. }
  3352. // 减少重绘
  3353. .side-group,
  3354. .content-top {
  3355. will-change: transform;
  3356. }
  3357. .side-group {
  3358. position: absolute;
  3359. top: 65%;
  3360. right: 30rpx;
  3361. z-index: 1000;
  3362. display: flex;
  3363. flex-direction: column;
  3364. align-items: center;
  3365. .side-item {
  3366. font-weight: 500;
  3367. font-size: 24rpx;
  3368. color: #ffffff;
  3369. margin-bottom: 32rpx;
  3370. text-align: center;
  3371. // 将 button 选择器改为类选择器
  3372. .button-reset::after {
  3373. border: none !important;
  3374. padding: 0 !important;
  3375. margin: 0 !important;
  3376. }
  3377. .button-reset {
  3378. background-color: transparent !important;
  3379. padding: 0 !important;
  3380. line-height: inherit !important;
  3381. margin: 0 !important;
  3382. width: auto !important;
  3383. font-weight: 500 !important;
  3384. border-radius: none !important;
  3385. }
  3386. .image {
  3387. width: 72rpx;
  3388. height: 72rpx;
  3389. }
  3390. }
  3391. }
  3392. .content-top {
  3393. width: 100%;
  3394. margin-top: 48rpx;
  3395. display: flex;
  3396. justify-content: space-between;
  3397. padding: 0 24rpx;
  3398. box-sizing: border-box;
  3399. .sum {
  3400. width: 80rpx;
  3401. height: 52rpx;
  3402. background: rgba(0, 0, 0, 0.5);
  3403. border-radius: 26rpx 26rpx 26rpx 26rpx;
  3404. font-size: 24rpx;
  3405. color: #ffffff;
  3406. text-align: center;
  3407. line-height: 52rpx;
  3408. }
  3409. }
  3410. .follow-btn {
  3411. padding: 8rpx 16rpx;
  3412. background: linear-gradient(270deg, #ff5c03 0%, #ffac64 100%);
  3413. border-radius: 26rpx;
  3414. font-weight: 500;
  3415. font-size: 26rpx;
  3416. color: #ffffff;
  3417. }
  3418. }
  3419. .trailer-box {
  3420. position: relative;
  3421. top: 15%;
  3422. display: flex;
  3423. flex-direction: column;
  3424. align-items: center;
  3425. color: #ffffff;
  3426. padding: 20rpx;
  3427. .button {
  3428. margin-top: 20rpx;
  3429. background: #6d7bd4;
  3430. color: #fff;
  3431. border-radius: 20rpx;
  3432. padding: 20rpx 30rpx;
  3433. position: relative;
  3434. z-index: 99999;
  3435. }
  3436. .ash {
  3437. background: #636363;
  3438. }
  3439. .countdown-item {
  3440. display: flex;
  3441. flex-direction: column;
  3442. align-items: center;
  3443. .white {
  3444. width: 60rpx;
  3445. height: 60rpx;
  3446. text-align: center;
  3447. overflow: hidden;
  3448. background: #ffffff;
  3449. border-radius: 8rpx;
  3450. margin: 30rpx 10rpx 0;
  3451. font-weight: 600;
  3452. font-size: 24rpx;
  3453. color: #000000;
  3454. line-height: 60rpx;
  3455. }
  3456. }
  3457. .item {
  3458. width: 100%;
  3459. height: 400rpx;
  3460. }
  3461. .name {
  3462. font-size: 34rpx;
  3463. }
  3464. .img {
  3465. margin-bottom: 40rpx;
  3466. width: 240rpx;
  3467. height: 240rpx;
  3468. }
  3469. .title {
  3470. margin-top: 30rpx;
  3471. font-size: 42rpx;
  3472. font-weight: 500;
  3473. }
  3474. }
  3475. .videolist {
  3476. position: relative;
  3477. height: 100vh;
  3478. width: 100%;
  3479. .video {
  3480. transform: translateZ(0);
  3481. backface-visibility: hidden;
  3482. perspective: 1000;
  3483. height: 100vh;
  3484. width: 100%;
  3485. // background-color: rgba(57, 57, 57, 0.4);
  3486. .item {
  3487. width: 100%;
  3488. height: 100%;
  3489. }
  3490. .time {
  3491. color: #ffffff;
  3492. font-size: 20rpx;
  3493. margin-left: 10rpx;
  3494. }
  3495. .end {
  3496. position: absolute;
  3497. top: 50%;
  3498. left: 50%;
  3499. transform: translate(-50%, -50%);
  3500. font-size: 36rpx;
  3501. color: #fff;
  3502. }
  3503. .lable {
  3504. position: absolute;
  3505. top: 50rpx;
  3506. right: 16rpx;
  3507. background-color: rgba(57, 57, 57, 0.6);
  3508. padding: 4rpx 10rpx;
  3509. color: #fff;
  3510. border-radius: 15rpx;
  3511. }
  3512. }
  3513. .video_row {
  3514. position: absolute;
  3515. top: 20%;
  3516. max-height: 450rpx;
  3517. z-index: 99;
  3518. }
  3519. }
  3520. .prize-card {
  3521. width: 504rpx;
  3522. padding: 40rpx 40rpx 30rpx;
  3523. box-sizing: border-box;
  3524. display: flex;
  3525. flex-direction: column;
  3526. border-radius: 20rpx;
  3527. align-items: center;
  3528. background: linear-gradient(180deg, #f7823f 0%, #ffd4be 27%, #ffffff 100%);
  3529. position: relative;
  3530. .nav-img {
  3531. width: 311rpx;
  3532. position: absolute;
  3533. top: -122rpx;
  3534. left: 50%;
  3535. transform: translateX(-50%);
  3536. }
  3537. .title {
  3538. color: #c32008;
  3539. font-size: 34rpx;
  3540. font-weight: 600;
  3541. margin: 20rpx 0 40rpx;
  3542. }
  3543. .prize-content {
  3544. width: 100%;
  3545. display: flex;
  3546. justify-content: space-between;
  3547. align-items: center;
  3548. font-size: 28rpx;
  3549. margin: 10rpx 0;
  3550. .txt {
  3551. font-weight: 600;
  3552. }
  3553. }
  3554. .tip {
  3555. font-size: 28rpx;
  3556. color: #414141;
  3557. margin: 40rpx 0;
  3558. }
  3559. .button {
  3560. width: 200rpx;
  3561. height: 70rpx;
  3562. line-height: 70rpx;
  3563. background: linear-gradient(180deg, #ff7c30 0%, #ff3a1e 100%);
  3564. border-radius: 28rpx;
  3565. font-weight: 500;
  3566. font-size: 32rpx;
  3567. color: #ffffff;
  3568. text-align: center;
  3569. }
  3570. }
  3571. .no-prize-card {
  3572. width: 504rpx;
  3573. padding: 40rpx 40rpx 30rpx;
  3574. box-sizing: border-box;
  3575. display: flex;
  3576. flex-direction: column;
  3577. border-radius: 20rpx;
  3578. align-items: center;
  3579. position: relative;
  3580. .img {
  3581. margin-top: 40rpx;
  3582. width: 300rpx;
  3583. height: 300rpx;
  3584. }
  3585. .tip {
  3586. font-size: 36rpx;
  3587. color: #414141;
  3588. margin: 40rpx 0;
  3589. }
  3590. .button {
  3591. width: 220rpx;
  3592. height: 80rpx;
  3593. line-height: 80rpx;
  3594. background: linear-gradient(180deg, #fdfbb8 0%, #b79243 100%);
  3595. border-radius: 28rpx;
  3596. font-weight: 500;
  3597. font-size: 32rpx;
  3598. color: #ffffff;
  3599. text-align: center;
  3600. }
  3601. }
  3602. .red-card {
  3603. width: 550rpx;
  3604. height: 636rpx;
  3605. position: relative;
  3606. .img {
  3607. position: absolute;
  3608. width: 100%;
  3609. height: 100%;
  3610. }
  3611. .red-content {
  3612. position: relative;
  3613. z-index: 5;
  3614. display: flex;
  3615. flex-direction: column;
  3616. align-items: center;
  3617. .title {
  3618. font-size: 36rpx;
  3619. color: #ff3a1e;
  3620. margin: 180rpx 0 90rpx;
  3621. }
  3622. .txt {
  3623. font-size: 28rpx;
  3624. color: #ffecc3;
  3625. margin: 80rpx 0 40rpx;
  3626. }
  3627. .button {
  3628. width: 392rpx;
  3629. height: 96rpx;
  3630. line-height: 96rpx;
  3631. background: linear-gradient(180deg, #fff4d5 0%, #ffe5b1 100%);
  3632. border-radius: 48rpx 48rpx 48rpx 48rpx;
  3633. font-weight: 600;
  3634. font-size: 36rpx;
  3635. color: #c32008;
  3636. text-align: center;
  3637. }
  3638. }
  3639. }
  3640. .integral-box {
  3641. min-width: 400rpx;
  3642. max-width: 600rpx;
  3643. display: flex;
  3644. flex-direction: column;
  3645. align-items: center;
  3646. border-radius: 20rpx;
  3647. overflow: hidden;
  3648. .top {
  3649. width: 100%;
  3650. position: relative;
  3651. .title {
  3652. width: 100%;
  3653. font-weight: 600;
  3654. font-size: 40rpx;
  3655. color: #ffffff;
  3656. text-shadow: 0px 4px 8px rgba(255, 89, 2, 0.8);
  3657. position: absolute;
  3658. top: 50rpx;
  3659. text-align: center;
  3660. }
  3661. .photo {
  3662. width: 100%;
  3663. }
  3664. }
  3665. .item {
  3666. padding: 20rpx;
  3667. .title {
  3668. font-weight: 500;
  3669. font-size: 32rpx;
  3670. text-align: center;
  3671. }
  3672. .button {
  3673. font-size: 32rpx;
  3674. margin-top: 20rpx;
  3675. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  3676. color: #fff;
  3677. text-align: center;
  3678. padding: 18rpx 60rpx;
  3679. border-radius: 10rpx;
  3680. font-weight: 500;
  3681. }
  3682. }
  3683. }
  3684. .goods {
  3685. position: fixed;
  3686. bottom: 140rpx;
  3687. right: 104rpx;
  3688. z-index: 5;
  3689. background-color: #fff;
  3690. border-radius: 20rpx;
  3691. overflow: hidden;
  3692. width: 280rpx;
  3693. padding: 4rpx;
  3694. .top {
  3695. position: absolute;
  3696. top: 4rpx;
  3697. display: flex;
  3698. justify-content: space-between;
  3699. align-items: center;
  3700. color: #fff;
  3701. width: 100%;
  3702. padding-right: 10rpx;
  3703. box-sizing: border-box;
  3704. .left {
  3705. background-color: rgba(0, 0, 0, 0.8);
  3706. padding: 12rpx;
  3707. font-size: 22rpx;
  3708. display: flex;
  3709. justify-content: space-between;
  3710. align-items: center;
  3711. border-radius: 10rpx;
  3712. }
  3713. }
  3714. .photo {
  3715. width: 100%;
  3716. height: 180rpx;
  3717. border-radius: 16rpx 16rpx 0 0;
  3718. overflow: hidden;
  3719. }
  3720. .item {
  3721. padding: 4rpx;
  3722. .price {
  3723. font-size: 30rpx;
  3724. .red {
  3725. color: #ff5701;
  3726. font-weight: 600;
  3727. margin-right: 10rpx;
  3728. }
  3729. .del {
  3730. color: #828282;
  3731. font-weight: 500;
  3732. font-size: 28rpx;
  3733. text-decoration: line-through;
  3734. }
  3735. }
  3736. .title {
  3737. font-weight: 500;
  3738. font-size: 30rpx;
  3739. margin: 10rpx 0 12rpx;
  3740. }
  3741. .button {
  3742. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  3743. color: #fff;
  3744. text-align: center;
  3745. padding: 16rpx 0;
  3746. border-radius: 10rpx;
  3747. font-weight: 500;
  3748. font-size: 30rpx;
  3749. }
  3750. }
  3751. }
  3752. .coupon-pop {
  3753. position: fixed;
  3754. bottom: 140rpx;
  3755. right: 100rpx;
  3756. z-index: 5;
  3757. border-radius: 20rpx;
  3758. width: 320rpx;
  3759. .coupon-block {
  3760. width: 100%;
  3761. position: relative;
  3762. .item {
  3763. width: 100%;
  3764. position: absolute;
  3765. top: 20rpx;
  3766. display: flex;
  3767. flex-direction: column;
  3768. align-items: center;
  3769. color: #fff;
  3770. .title {
  3771. font-weight: 500;
  3772. font-size: 30rpx;
  3773. margin: 16rpx 0 12rpx;
  3774. }
  3775. .price {
  3776. font-size: 40rpx;
  3777. .bold {
  3778. font-size: 56rpx;
  3779. font-weight: 600;
  3780. }
  3781. }
  3782. .txt {
  3783. font-weight: 500;
  3784. font-size: 30rpx;
  3785. margin: 5rpx 0;
  3786. }
  3787. .button {
  3788. background: linear-gradient(270deg, #fffce1 0%, #ffeaaf 100%);
  3789. color: #ff0004;
  3790. text-align: center;
  3791. padding: 16rpx 0;
  3792. border-radius: 40rpx;
  3793. font-weight: 500;
  3794. font-size: 30rpx;
  3795. width: 70%;
  3796. margin-top: 26rpx;
  3797. }
  3798. }
  3799. .bg {
  3800. height: 432rpx;
  3801. width: 100%;
  3802. }
  3803. .nav {
  3804. position: absolute;
  3805. height: 120rpx;
  3806. top: -120rpx;
  3807. left: 0;
  3808. width: 100%;
  3809. z-index: 6;
  3810. }
  3811. .close {
  3812. position: absolute;
  3813. right: 10rpx;
  3814. top: 10rpx;
  3815. }
  3816. }
  3817. }
  3818. .icon-bg {
  3819. background-color: rgba(57, 57, 57, 0.8);
  3820. border-radius: 50%;
  3821. width: 88rpx;
  3822. height: 88rpx;
  3823. display: flex;
  3824. justify-content: center;
  3825. align-items: center;
  3826. transition: transform 0.2s ease;
  3827. }
  3828. .list {
  3829. width: 80%;
  3830. margin-bottom: 20rpx;
  3831. animation: simpleFade 0.2s;
  3832. }
  3833. @keyframes simpleFade {
  3834. from {
  3835. opacity: 0;
  3836. }
  3837. to {
  3838. opacity: 1;
  3839. }
  3840. }
  3841. .shop-prompt {
  3842. position: absolute;
  3843. bottom: 750rpx;
  3844. left: 24rpx;
  3845. padding: 6rpx 20rpx;
  3846. background: rgba(230, 154, 34, 0.7);
  3847. border-radius: 24rpx;
  3848. z-index: 9;
  3849. font-weight: 500;
  3850. color: #ffffff;
  3851. transition: opacity 0.3s ease;
  3852. }
  3853. .view-box {
  3854. position: relative;
  3855. height: 40vh;
  3856. /* 设置弹出层高度为视窗高度的70% */
  3857. padding: 40rpx 0rpx;
  3858. box-sizing: border-box;
  3859. display: flex;
  3860. flex-direction: column;
  3861. .scroll-content {
  3862. flex: 1;
  3863. margin-top: 50rpx;
  3864. overflow-y: auto;
  3865. padding: 0 40rpx;
  3866. }
  3867. .bottom {
  3868. padding: 20rpx 40rpx;
  3869. position: absolute;
  3870. bottom: 0;
  3871. width: 100%;
  3872. box-shadow: 0rpx -4rpx 10rpx 0rpx rgba(195, 195, 195, 0.3);
  3873. background: #fff;
  3874. }
  3875. }
  3876. // 抽奖
  3877. .prize-box {
  3878. position: relative;
  3879. .nav-img {
  3880. width: 311rpx;
  3881. position: absolute;
  3882. top: -122rpx;
  3883. left: 50%;
  3884. transform: translateX(-50%);
  3885. }
  3886. .bg-img {
  3887. position: absolute;
  3888. top: 0;
  3889. left: 0;
  3890. width: 100%;
  3891. height: 100%;
  3892. z-index: 1;
  3893. }
  3894. .prize-content {
  3895. position: relative;
  3896. z-index: 2;
  3897. padding: 24rpx 0 68rpx;
  3898. .item {
  3899. flex: 1;
  3900. text-align: center;
  3901. }
  3902. .white-item {
  3903. width: 40rpx;
  3904. height: 40rpx;
  3905. text-align: center;
  3906. overflow: hidden;
  3907. background: #ffffff;
  3908. box-shadow: inset 0rpx 2rpx 8rpx 0rpx #ffebb2;
  3909. border-radius: 8rpx;
  3910. margin: 4rpx;
  3911. font-weight: 600;
  3912. font-size: 24rpx;
  3913. color: #f85d22;
  3914. line-height: 40rpx;
  3915. }
  3916. .item-group {
  3917. width: 100%;
  3918. }
  3919. .point-group {
  3920. margin: 20rpx 0 50rpx;
  3921. display: flex;
  3922. gap: 6rpx;
  3923. .item {
  3924. width: 20rpx;
  3925. height: 8rpx;
  3926. background: rgba(255, 255, 255, 0.5);
  3927. border-radius: 4rpx 4rpx 4rpx 4rpx;
  3928. }
  3929. .selected {
  3930. background: #ffeb66;
  3931. }
  3932. }
  3933. .button {
  3934. margin-top: 30rpx;
  3935. width: 520rpx;
  3936. height: 88rpx;
  3937. line-height: 88rpx;
  3938. background: linear-gradient(180deg, #fff4d6 0%, #ffeb66 100%);
  3939. box-shadow: 0rpx 10rpx 8rpx 4rpx rgba(246, 82, 25, 0.5);
  3940. border-radius: 44rpx;
  3941. font-weight: 500;
  3942. font-size: 36rpx;
  3943. color: #f4410b;
  3944. text-align: center;
  3945. }
  3946. }
  3947. }
  3948. .more-block {
  3949. border-radius: 20rpx 0 0 20rpx;
  3950. padding: 70rpx 30rpx;
  3951. display: flex;
  3952. justify-content: space-between;
  3953. .item {
  3954. text-align: center;
  3955. }
  3956. }
  3957. .winning_record {
  3958. position: relative;
  3959. height: 800rpx;
  3960. .head_bg {
  3961. position: absolute;
  3962. top: -125rpx;
  3963. left: 50%;
  3964. width: 311rpx;
  3965. transform: translateX(-50%);
  3966. }
  3967. .bg {
  3968. width: 100%;
  3969. height: 100%;
  3970. }
  3971. .winning_content {
  3972. position: absolute;
  3973. top: 50rpx;
  3974. color: #fff;
  3975. width: 100%;
  3976. padding: 0 36rpx;
  3977. box-sizing: border-box;
  3978. .title {
  3979. text-align: center;
  3980. font-size: 40rpx;
  3981. font-weight: 500;
  3982. margin-bottom: 40rpx;
  3983. }
  3984. .row {
  3985. display: flex;
  3986. justify-content: space-between;
  3987. .head {
  3988. flex: 1;
  3989. text-align: center;
  3990. }
  3991. .start {
  3992. flex: 1;
  3993. }
  3994. .end {
  3995. flex: 1;
  3996. text-align: end;
  3997. }
  3998. }
  3999. }
  4000. }
  4001. .shoppop {
  4002. padding: 22rpx 16rpx;
  4003. .shoppop-top {
  4004. display: flex;
  4005. justify-content: space-between;
  4006. align-items: center;
  4007. padding: 0 16rpx 22rpx;
  4008. .search-input {
  4009. width: 414rpx;
  4010. height: 76rpx;
  4011. background: #ffffff;
  4012. border-radius: 36rpx;
  4013. margin-left: 20rpx;
  4014. padding: 0 32rpx;
  4015. box-sizing: border-box;
  4016. font-size: 24rpx;
  4017. margin-right: 24rpx;
  4018. }
  4019. .search-top {
  4020. font-size: 20rpx;
  4021. color: #222222;
  4022. }
  4023. }
  4024. .shop-list {
  4025. overflow: hidden;
  4026. .list-item {
  4027. display: flex;
  4028. align-items: center;
  4029. padding: 20rpx 16rpx;
  4030. background: #ffffff;
  4031. border-radius: 16rpx;
  4032. margin-bottom: 16rpx;
  4033. .goods-img {
  4034. width: 200rpx;
  4035. height: 200rpx;
  4036. border-radius: 16rpx;
  4037. overflow: hidden;
  4038. position: relative;
  4039. margin-right: 24rpx;
  4040. .img {
  4041. width: 100%;
  4042. height: 100%;
  4043. }
  4044. .goods-label {
  4045. position: absolute;
  4046. top: 0;
  4047. width: 64rpx;
  4048. height: 40rpx;
  4049. background: rgba(0, 0, 0, 0.5);
  4050. border-radius: 16rpx 0rpx 16rpx 0rpx;
  4051. text-align: center;
  4052. font-weight: 500;
  4053. font-size: 28rpx;
  4054. color: #ffffff;
  4055. }
  4056. }
  4057. .goods-right {
  4058. flex: 1;
  4059. .goods-title {
  4060. font-weight: 500;
  4061. font-size: 30rpx;
  4062. color: #000000;
  4063. margin-bottom: 10rpx;
  4064. }
  4065. .goods-details {
  4066. font-size: 24rpx;
  4067. color: #999999;
  4068. margin: 10rpx 0 20rpx;
  4069. }
  4070. .goods-people {
  4071. font-size: 22rpx;
  4072. color: #e69a22;
  4073. height: 56rpx;
  4074. }
  4075. .goods-shop {
  4076. display: flex;
  4077. justify-content: space-between;
  4078. .nummber {
  4079. color: #ff5c03;
  4080. font-size: 22rpx;
  4081. font-weight: 500;
  4082. }
  4083. .btn-group {
  4084. text-align: center;
  4085. line-height: 56rpx;
  4086. .collect-btn {
  4087. width: 72rpx;
  4088. height: 100%;
  4089. background: #f5f7fa;
  4090. border-radius: 8rpx 0rpx 0rpx 8rpx;
  4091. }
  4092. .shop-btn {
  4093. width: 152rpx;
  4094. background: linear-gradient(270deg, #ff5c03 0%, #ffac64 100%);
  4095. border-radius: 0rpx 8rpx 8rpx 0rpx;
  4096. font-weight: 500;
  4097. font-size: 30rpx;
  4098. color: #ffffff;
  4099. }
  4100. }
  4101. }
  4102. }
  4103. }
  4104. }
  4105. }
  4106. </style>