living.vue 141 KB

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