living.vue 122 KB

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