living.vue 125 KB

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