living.vue 119 KB

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