living-new.vue 125 KB

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