living.vue 140 KB

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