living.vue 115 KB

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