living.vue 119 KB

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