living.vue 136 KB

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