living.vue 135 KB

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