living.vue 117 KB

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