living.vue 120 KB

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