living.vue 141 KB

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