living.vue 162 KB

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