living.vue 137 KB

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