living.vue 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835
  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, useServerTime = false) {
  1204. // 0. 安全校验:防止 undefined/null 导致 crash
  1205. if (!timeStr) {
  1206. return 0;
  1207. }
  1208. // 1. 获取当前时间戳(毫秒)- 倒计时场景使用服务器时间
  1209. const now = this.getServerTimeNow();
  1210. // 2. 计算差值(毫秒 -> 秒)
  1211. // 结果为:当前时间 - 直播开始时间
  1212. const diffInSeconds = Math.floor((now - timeStr) / 1000);
  1213. return diffInSeconds;
  1214. },
  1215. calculateLiveEndTime(startTime, duration) {
  1216. if (!startTime) return '';
  1217. // 计算结束时间戳
  1218. const endTimeMs = startTime + (Number(duration) * 1000);
  1219. const endDate = new Date(endTimeMs);
  1220. // 格式化
  1221. const year = endDate.getFullYear();
  1222. const month = this.padZero(endDate.getMonth() + 1);
  1223. const day = this.padZero(endDate.getDate());
  1224. const hours = this.padZero(endDate.getHours());
  1225. const minutes = this.padZero(endDate.getMinutes());
  1226. const seconds = this.padZero(endDate.getSeconds());
  1227. return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  1228. },
  1229. startCountdown() {
  1230. if (!this.liveItem.completionPointsEnabled) {
  1231. return;
  1232. }
  1233. // 如果倒计时已经在运行,先清除旧的定时器
  1234. if (this.countdownTimer) {
  1235. clearInterval(this.countdownTimer);
  1236. this.countdownTimer = null;
  1237. }
  1238. // 使用服务器时间重新计算初始状态,确保设备时间不一致时也能正确判断
  1239. const liveStartTime = this.getLiveStartTime();
  1240. if (liveStartTime) {
  1241. this.diffLiveStartTime = this.calculateLiveTimeDiff(liveStartTime, true);
  1242. // 如果直播已开始,确保 isPreview 为 false
  1243. if (this.diffLiveStartTime >= 0 ) {
  1244. this.isPreview = false;
  1245. }
  1246. }
  1247. this.isCountdownActive = true;
  1248. // 立即执行一次更新,确保倒计时显示正确
  1249. this.updateCountdown();
  1250. this.countdownTimer = setInterval(() => {
  1251. this.updateCountdown();
  1252. }, 1000); // 每秒更新一次
  1253. },
  1254. updateCountdown() {
  1255. if (!this.liveItem) {
  1256. return;
  1257. }
  1258. // 使用服务器时间重新计算初始状态,确保设备时间不一致时也能正确判断
  1259. const liveStartTime = this.getLiveStartTime();
  1260. if (liveStartTime) {
  1261. this.diffLiveStartTime = this.calculateLiveTimeDiff(liveStartTime, true);
  1262. // 如果直播已开始,确保 isPreview 为 false
  1263. if (this.diffLiveStartTime >= 0 ) {
  1264. this.isPreview = false;
  1265. }
  1266. }
  1267. this.completionTime = this.liveItem.duration * this.completionRate;
  1268. // 已达成观看时间
  1269. if (this.watchDuration > this.completionTime) {
  1270. if (this.countdownTimer) {
  1271. clearInterval(this.countdownTimer);
  1272. this.countdownTimer = null;
  1273. this.isPreview = true;
  1274. return;
  1275. }
  1276. }
  1277. // 倒计时已结束
  1278. if (this.pointsRemainingTime < 0) {
  1279. this.stopCountdown();
  1280. return;
  1281. }
  1282. this.showPoints = false;
  1283. // 使用服务器时间计算差值
  1284. const serverTimeNow = this.getServerTimeNow();
  1285. this.diffLiveStartTime = this.calculateLiveTimeDiff(liveStartTime, true);
  1286. this.diffLiveEndTime = this.calculateLiveTimeDiff(liveStartTime, true) - this.liveItem.duration;
  1287. if (!this.liveItem.finishTime) {
  1288. this.liveItem.finishTime = this.calculateLiveEndTime(liveStartTime, this.liveItem.duration);
  1289. }
  1290. // 预告状态
  1291. if (this.diffLiveStartTime < 0) {
  1292. this.isPreview = true;
  1293. return;
  1294. } else {
  1295. // 直播已开始(基于服务器时间),确保 isPreview 为 false
  1296. this.isPreview = false;
  1297. }
  1298. if (this.diffLiveStartTime >= 0) {
  1299. if (this.diffLiveEndTime >= 0) {
  1300. // 回放文件生成中
  1301. if (this.diffLiveEndTime <= 180) {
  1302. this.isPreview = false;
  1303. this.pointsRemainingTime = Math.max(0, this.completionTime - this.totalWatchTime);
  1304. this.diffReplayGenerationSeconds++;
  1305. this.hasReplayGeneration = true;
  1306. return;
  1307. } else {
  1308. if (this.hasReplayGeneration) {
  1309. // 经历过回放生成 回放生成后扣减掉经历回放生成的时间
  1310. this.totalWatchTime = this.watchDuration + Math.floor((serverTimeNow - this.liveBeginWatchTime) / 1000) - this.diffReplayGenerationSeconds;
  1311. } else {
  1312. // 进入直播间时已过回放生成中
  1313. this.totalWatchTime = this.watchDuration + Math.floor((serverTimeNow - this.liveBeginWatchTime) / 1000);
  1314. }
  1315. }
  1316. } else {
  1317. // 直播中状态
  1318. this.totalWatchTime = this.watchDuration + Math.floor((serverTimeNow - this.liveBeginWatchTime) / 1000);
  1319. }
  1320. // 积分领取满足条件
  1321. if (this.totalWatchTime >= this.completionTime) {
  1322. if (this.countdownTimer) {
  1323. clearInterval(this.countdownTimer);
  1324. this.countdownTimer = null;
  1325. this.onCountdownComplete();
  1326. return;
  1327. }
  1328. }
  1329. this.isPreview = false;
  1330. // 直播中或回放状态都计算剩余时间
  1331. if (this.diffLiveStartTime >= 0) {
  1332. if (this.diffLiveEndTime < 0) {
  1333. // 直播中状态
  1334. this.pointsRemainingTime = Math.max(0, this.completionTime - this.totalWatchTime);
  1335. }
  1336. if (this.diffLiveEndTime > 180) {
  1337. // 直播回放中
  1338. this.pointsRemainingTime = Math.max(0, this.completionTime - this.totalWatchTime);
  1339. }
  1340. }
  1341. }
  1342. // 更新显示
  1343. this.updateCountdownDisplay();
  1344. },
  1345. stopCountdown() {
  1346. if (this.countdownTimer) {
  1347. clearInterval(this.countdownTimer)
  1348. this.countdownTimer = null
  1349. }
  1350. this.isCountdownActive = false
  1351. this.updateWatchDuration()
  1352. },
  1353. onCountdownComplete() {
  1354. console.log('倒计时完成!')
  1355. this.stopCountdown()
  1356. this.pointsRemainingTime = -1
  1357. this.triggerWatchComplete()
  1358. setTimeout(() => {
  1359. this.showToast = true
  1360. setTimeout(() => {
  1361. this.showToast = false
  1362. }, 5000)
  1363. }, 1000)
  1364. },
  1365. async triggerWatchComplete() {
  1366. if (!this.userInfo?.userId || !this.liveId) return
  1367. try {
  1368. console.log('用户已完成观看')
  1369. uni.removeStorageSync(this.watchProgressKey)
  1370. } catch (error) {
  1371. console.error('触发观看完成事件失败:', error)
  1372. }
  1373. },
  1374. padZero(num) {
  1375. return num < 10 ? `0${num}` : num.toString()
  1376. },
  1377. formatCountdown(seconds) {
  1378. const totalSeconds = Math.max(0, Math.floor(Number(seconds) || 0))
  1379. const hours = Math.floor(totalSeconds / 3600)
  1380. const remainingAfterHours = totalSeconds % 3600
  1381. const minutes = Math.floor(remainingAfterHours / 60)
  1382. const secs = remainingAfterHours % 60
  1383. return {
  1384. hours: this.padZero(hours),
  1385. minutes: this.padZero(minutes),
  1386. seconds: this.padZero(secs),
  1387. total: totalSeconds
  1388. }
  1389. },
  1390. getCountdownPercentage() {
  1391. if (!this.liveItem || !this.liveItem.duration) {
  1392. console.log('进度条计算:liveItem.duration无效', this.liveItem?.duration)
  1393. return 0
  1394. }
  1395. if (this.hasReachedTarget || this.pointsRemainingTime <= 0) {
  1396. return 100
  1397. }
  1398. const completionTime = this.liveItem.duration * this.completionRate;
  1399. const watchedTime = this.totalWatchTime;
  1400. if (watchedTime <= 0) {
  1401. return 0
  1402. }
  1403. const percentage = (watchedTime / completionTime) * 100
  1404. return Math.min(100, Math.max(0, percentage))
  1405. },
  1406. updateCountdownDisplay() {
  1407. this.$forceUpdate()
  1408. },
  1409. initWatchTime() {
  1410. const userId = this.userInfo?.userId || 'anonymous'
  1411. this.watchTimeStorageKey = `watchTime_${userId}_${this.liveId}`
  1412. try {
  1413. const storedTime = uni.getStorageSync(this.watchTimeStorageKey)
  1414. this.totalWatchTime = storedTime ? parseInt(storedTime) : 0
  1415. console.log(`加载累计观看时间: ${this.totalWatchTime}秒`)
  1416. } catch (error) {
  1417. console.error('加载观看时间失败:', error)
  1418. this.totalWatchTime = 0
  1419. }
  1420. },
  1421. saveWatchTime() {
  1422. if (!this.watchTimeStorageKey) return
  1423. try {
  1424. uni.setStorageSync(this.watchTimeStorageKey, this.totalWatchTime)
  1425. console.log(`保存观看时间: ${this.totalWatchTime}秒`)
  1426. } catch (error) {
  1427. console.error('保存观看时间失败:', error)
  1428. }
  1429. },
  1430. formatWatchTime(seconds) {
  1431. const hours = Math.floor(seconds / 3600)
  1432. const minutes = Math.floor((seconds % 3600) / 60)
  1433. const secs = seconds % 60
  1434. return {
  1435. hours: this.padZero(hours),
  1436. minutes: this.padZero(minutes),
  1437. seconds: this.padZero(secs),
  1438. total: seconds
  1439. }
  1440. },
  1441. handleFullscreenChange(isFullscreen) {
  1442. console.log('收到子组件全屏状态:', isFullscreen)
  1443. this.isFullscreen = isFullscreen
  1444. if (isFullscreen) {
  1445. this.shopping = false
  1446. this.isShowGift = false
  1447. this.isMore = false
  1448. this.showViewerList = false
  1449. this.isShowLotteryPop = false
  1450. this.winning = false
  1451. this.isFocus = false
  1452. }
  1453. this.$nextTick(() => {
  1454. this.$forceUpdate()
  1455. })
  1456. },
  1457. onInputFocus(value) {
  1458. this.isFocus = true
  1459. console.log('输入框聚焦:', value)
  1460. },
  1461. onInputBlur(value) {
  1462. this.isFocus = false
  1463. console.log('输入框失焦:', value)
  1464. },
  1465. onSendMessage(message) {
  1466. console.log('发送消息:', message)
  1467. this.sendMsg()
  1468. },
  1469. onInputChange(value) {
  1470. this.value = value
  1471. },
  1472. handleLiveStart() {
  1473. console.log('直播开始')
  1474. this.getliving(this.liveId)
  1475. },
  1476. handleSearchInput(keyword) {
  1477. this.inputInfo = keyword
  1478. clearTimeout(this.searchTimer)
  1479. this.searchTimer = setTimeout(() => {
  1480. this.queryCollect()
  1481. }, 500)
  1482. },
  1483. handleVideoError(error) {
  1484. console.error('视频播放错误:', error)
  1485. },
  1486. handleLiveStateChange(state) {
  1487. console.log('直播状态变化:', state)
  1488. },
  1489. handleNavigateToOrder() {
  1490. this.navgetTo('/pages_shopping/live/order')
  1491. },
  1492. handleShowMore() {
  1493. this.isMore = true
  1494. this.shopping = false
  1495. },
  1496. handleFillAddress(data) {
  1497. const {
  1498. productId,
  1499. recordId,
  1500. liveId
  1501. } = data
  1502. this.winning = false
  1503. this.navgetTo(
  1504. `/pages_shopping/live/confirmCreateOrder?type=win&productId=${productId}&liveId=${liveId}&recordId=${recordId}`
  1505. )
  1506. },
  1507. handleLotteryClose() {
  1508. this.isShowLotteryPop = false
  1509. },
  1510. handleLotteryClaim() {
  1511. this.onClaim()
  1512. },
  1513. handleGoShop(goodsData) {
  1514. this.goShop(goodsData.productId, goodsData.goodsId)
  1515. },
  1516. handleCloseGoods() {
  1517. this.isShowGoods = false
  1518. },
  1519. formatNumber(num) {
  1520. if (typeof num !== 'number') {
  1521. num = Number(num) || 0
  1522. }
  1523. if (num < 10000) {
  1524. return num.toString()
  1525. }
  1526. const wan = num / 10000
  1527. if (wan < 10) {
  1528. const rounded = Math.round(wan * 100) / 100
  1529. return rounded.toFixed(2).replace(/\.?0+$/, '') + 'w'
  1530. } else if (wan < 10000) {
  1531. const rounded = Math.round(wan * 10) / 10
  1532. return rounded.toFixed(1).replace(/\.0$/, '') + 'w'
  1533. } else {
  1534. const yi = wan / 10000
  1535. const rounded = Math.round(yi * 100) / 100
  1536. return rounded.toFixed(2).replace(/\.?0+$/, '') + '亿'
  1537. }
  1538. },
  1539. resetAllStates() {
  1540. this.liveUserCalled = false
  1541. this.talklist = []
  1542. this.liveViewersData = []
  1543. this.liveViewers = []
  1544. this.products = []
  1545. this.liveItem = []
  1546. this.isSocketOpen = false
  1547. this.isConnecting = false
  1548. this.isManualClose = true
  1549. this.reconnectCount = 0
  1550. this.heartBeatRetryCount = 0
  1551. this.lastHeartBeatTime = 0
  1552. this.adaptiveHeartBeatInterval = this.heartBeatInterval
  1553. this.isNetworkAvailable = true
  1554. this.networkType = 'unknown'
  1555. this.connectionStartTime = 0
  1556. this.connectionLatency = 0
  1557. this.messageCount = 0
  1558. this.errorCount = 0
  1559. this.lastPerformanceCheck = 0
  1560. },
  1561. getWebSocketPerformanceStats() {
  1562. const now = Date.now()
  1563. const uptime = this.connectionStartTime > 0 ? now - this.connectionStartTime : 0
  1564. return {
  1565. connectionLatency: this.connectionLatency,
  1566. uptime: uptime,
  1567. messageCount: this.messageCount,
  1568. errorCount: this.errorCount,
  1569. errorRate: this.messageCount > 0 ? (this.errorCount / this.messageCount * 100).toFixed(2) : 0,
  1570. messagesPerSecond: uptime > 0 ? (this.messageCount / (uptime / 1000)).toFixed(2) : 0,
  1571. networkType: this.networkType,
  1572. isConnected: this.isSocketAvailable(),
  1573. reconnectCount: this.reconnectCount
  1574. }
  1575. },
  1576. performanceCheck() {
  1577. const now = Date.now()
  1578. if (now - this.lastPerformanceCheck > 300000) {
  1579. const stats = this.getWebSocketPerformanceStats()
  1580. console.log('WebSocket性能统计:', stats)
  1581. this.lastPerformanceCheck = now
  1582. if (stats.errorRate > 10) {
  1583. console.warn(`WebSocket错误率过高: ${stats.errorRate}%`)
  1584. }
  1585. if (stats.connectionLatency > 5000) {
  1586. console.warn(`WebSocket连接延迟过高: ${stats.connectionLatency}ms`)
  1587. }
  1588. }
  1589. },
  1590. startVideoCacheCleanup() {
  1591. if (this.videoCleanupTimer) {
  1592. clearInterval(this.videoCleanupTimer)
  1593. }
  1594. this.videoCleanupTimer = setInterval(() => {
  1595. this.cleanupVideoCache()
  1596. }, 30000)
  1597. },
  1598. cleanupVideoCache() {
  1599. if (!this.liveItem || !this.liveId) return
  1600. if (this.liveItem.liveType === 2 && this.liveItem.videoUrl) {
  1601. this.reloadVideoPlayer()
  1602. }
  1603. },
  1604. reloadVideoPlayer() {
  1605. const videoId = `myVideo_${this.liveId}`
  1606. const videoContext = uni.createVideoContext(videoId, this)
  1607. if (videoContext) {
  1608. const currentTime = this.videoCurrentTime
  1609. videoContext.pause()
  1610. setTimeout(() => {
  1611. this.$set(this.liveItem, 'videoUrl', this.liveItem.videoUrl + '&t=' + Date.now())
  1612. setTimeout(() => {
  1613. if (videoContext.seek) {
  1614. videoContext.seek(currentTime)
  1615. }
  1616. videoContext.play()
  1617. }, 500)
  1618. }, 100)
  1619. }
  1620. },
  1621. startMemoryMonitoring() {
  1622. if (this.memoryMonitorTimer) {
  1623. clearInterval(this.memoryMonitorTimer)
  1624. }
  1625. this.memoryMonitorTimer = setInterval(() => {
  1626. this.checkMemoryUsage()
  1627. }, 15000)
  1628. },
  1629. checkMemoryUsage() {
  1630. try {
  1631. const timerCount = this.getActiveTimerCount()
  1632. if (timerCount > 10) {
  1633. console.warn(`检测到过多定时器: ${timerCount}个,可能存在内存泄漏`)
  1634. this.cleanupUnusedTimers()
  1635. }
  1636. if (this.messageQueue && this.messageQueue.length > 100) {
  1637. console.warn(`消息队列过长: ${this.messageQueue.length}条,清理旧消息`)
  1638. this.messageQueue = this.messageQueue.slice(-50)
  1639. }
  1640. if (this.userRandomColors && Object.keys(this.userRandomColors).length > 500) {
  1641. console.warn('用户颜色缓存过大,清理部分缓存')
  1642. const keys = Object.keys(this.userRandomColors)
  1643. const keysToRemove = keys.slice(0, keys.length - 200)
  1644. keysToRemove.forEach(key => delete this.userRandomColors[key])
  1645. }
  1646. if (Date.now() - this.lastPerformanceCheck > 60000) {
  1647. this.triggerGarbageCollection()
  1648. this.lastPerformanceCheck = Date.now()
  1649. }
  1650. } catch (error) {
  1651. console.error('内存检查失败:', error)
  1652. }
  1653. },
  1654. forceMemoryCleanup() {
  1655. console.log('执行强制内存清理')
  1656. this.cleanupVideoPlayer()
  1657. this.clearBigData()
  1658. this.triggerGarbageCollection()
  1659. },
  1660. cleanupVideoPlayer() {
  1661. const videoId = `myVideo_${this.liveId}`
  1662. const videoContext = uni.createVideoContext(videoId, this)
  1663. if (videoContext) {
  1664. videoContext.stop()
  1665. setTimeout(() => {
  1666. this.$set(this.liveItem, 'videoUrl', '')
  1667. setTimeout(() => {
  1668. this.$set(this.liveItem, 'videoUrl', this.getFreshVideoUrl())
  1669. if (this.$refs.liveVideo && this.$refs.liveVideo.playVideo) {
  1670. this.$refs.liveVideo.playVideo()
  1671. }
  1672. }, 500)
  1673. }, 100)
  1674. }
  1675. },
  1676. getFreshVideoUrl() {
  1677. if (!this.liveItem.originalVideoUrl) {
  1678. this.liveItem.originalVideoUrl = this.liveItem.videoUrl
  1679. }
  1680. const separator = this.liveItem.originalVideoUrl.includes('?') ? '&' : '?'
  1681. return this.liveItem.originalVideoUrl + separator + 't=' + Date.now()
  1682. },
  1683. clearBigData() {
  1684. if (this.talklist.length > 50) {
  1685. this.talklist = this.talklist.slice(-50)
  1686. }
  1687. if (this.liveViewersData.length > 100) {
  1688. this.liveViewersData = this.liveViewersData.slice(-100)
  1689. }
  1690. if (this.liveViewers.length > 100) {
  1691. this.liveViewers = this.liveViewers.slice(-100)
  1692. }
  1693. if (this.products.length > 50) {
  1694. this.products = this.products.slice(0, 50)
  1695. }
  1696. if (typeof gc === 'function') {
  1697. gc()
  1698. }
  1699. },
  1700. triggerGarbageCollection() {
  1701. if (wx && wx.triggerGC) {
  1702. wx.triggerGC()
  1703. }
  1704. },
  1705. forceScrollToBottom() {
  1706. console.log('执行强制滚动到底部')
  1707. this.scrollTop = 999999
  1708. this.$nextTick(() => {
  1709. if (this.talklist && this.talklist.length > 0) {
  1710. const lastMessage = this.talklist[this.talklist.length - 1]
  1711. const targetId = `list_${lastMessage.uniqueId || (this.talklist.length - 1)}`
  1712. console.log(
  1713. `尝试滚动到元素: ${targetId}, 当前消息数量: ${this.talklist.length}, 最后消息ID: ${lastMessage.uniqueId}`
  1714. )
  1715. this.scrollIntoView = targetId
  1716. setTimeout(() => {
  1717. this.scrollIntoView = ''
  1718. }, 200)
  1719. }
  1720. setTimeout(() => {
  1721. this.scrollTop = 999999
  1722. console.log('延迟设置scrollTop为999999')
  1723. }, 100)
  1724. setTimeout(() => {
  1725. this.nativeScrollToBottom()
  1726. }, 300)
  1727. })
  1728. },
  1729. simpleScrollToBottom() {
  1730. const now = Date.now()
  1731. if (now - this.lastScrollTime < this.scrollDebounceDelay) {
  1732. console.log('滚动防抖:忽略频繁调用')
  1733. return
  1734. }
  1735. this.lastScrollTime = now
  1736. console.log('执行可靠滚动到底部')
  1737. if (this.scrollTimer) {
  1738. clearTimeout(this.scrollTimer)
  1739. this.scrollTimer = null
  1740. }
  1741. this.scrollTop = 999999999
  1742. console.log('方案1: 设置scrollTop为999999999')
  1743. if (this.talklist.length > 0) {
  1744. const lastMessage = this.talklist[this.talklist.length - 1]
  1745. if (lastMessage && lastMessage.uniqueId) {
  1746. this.scrollIntoView = `msg-${lastMessage.uniqueId}`
  1747. console.log(`方案2: 设置scrollIntoView为msg-${lastMessage.uniqueId}`)
  1748. }
  1749. }
  1750. this.scrollTimer = setTimeout(() => {
  1751. this.scrollTop = 999999999
  1752. console.log('方案3: 延迟设置scrollTop为999999999')
  1753. this.scrollTimer = null
  1754. }, 50)
  1755. },
  1756. forceScrollToBottomOnSend() {
  1757. console.log('执行强制滚动到底部(发送消息专用)')
  1758. if (this.scrollTimer) {
  1759. clearTimeout(this.scrollTimer)
  1760. this.scrollTimer = null
  1761. }
  1762. this.lastScrollTime = Date.now()
  1763. this.scrollIntoView = ''
  1764. if (this.talklist.length > 0) {
  1765. const lastMessage = this.talklist[this.talklist.length - 1]
  1766. if (lastMessage && lastMessage.uniqueId) {
  1767. this.scrollIntoView = `list_${lastMessage.uniqueId}`
  1768. }
  1769. }
  1770. const targetScrollTop = Date.now()
  1771. this.scrollTop = targetScrollTop
  1772. this.nativeScrollToBottom()
  1773. this.$nextTick(() => {
  1774. this.scrollIntoView = ''
  1775. this.scrollTop = targetScrollTop + 1
  1776. setTimeout(() => {
  1777. this.nativeScrollToBottom()
  1778. }, 50)
  1779. })
  1780. this.scrollTimer = setTimeout(() => {
  1781. this.checkAndForceScroll(targetScrollTop)
  1782. this.scrollTimer = null
  1783. }, 200)
  1784. },
  1785. checkAndForceScroll(targetScrollTop) {
  1786. if (this.talklist.length > 0) {
  1787. const lastMessage = this.talklist[this.talklist.length - 1]
  1788. if (lastMessage && lastMessage.uniqueId) {
  1789. this.scrollIntoView = `list_${lastMessage.uniqueId}`
  1790. }
  1791. }
  1792. this.scrollTop = Date.now() + Math.random() * 1000
  1793. this.nativeScrollToBottom()
  1794. setTimeout(() => {
  1795. this.nativeScrollToBottom()
  1796. }, 100)
  1797. },
  1798. nativeScrollToBottom() {
  1799. try {
  1800. const query = uni.createSelectorQuery().in(this)
  1801. query.select('#msgScroll').node((res) => {
  1802. if (res && res.node) {
  1803. console.log('找到msgScroll节点,执行原生滚动')
  1804. const scrollHeight = res.node.scrollHeight
  1805. res.node.scrollTop = scrollHeight
  1806. setTimeout(() => {
  1807. res.node.scrollTop = scrollHeight + 100
  1808. }, 50)
  1809. }
  1810. }).exec()
  1811. } catch (error) {
  1812. console.error('原生滚动失败:', error)
  1813. }
  1814. },
  1815. onScroll(e) {
  1816. this.currentScrollTop = e.detail.scrollTop
  1817. },
  1818. stopMemoryMonitor() {
  1819. if (this.memoryMonitorTimer) {
  1820. clearInterval(this.memoryMonitorTimer)
  1821. this.memoryMonitorTimer = null
  1822. }
  1823. },
  1824. getActiveTimerCount() {
  1825. const timers = [
  1826. 'trafficTimer', 'pingTimeoutTimer', 'heartBeatTimer', 'liveViewDataTimer',
  1827. 'reconnectTimer', 'scrollTimer', 'searchTimer', 'purchasePromptTimer',
  1828. 'welcomeTimer', 'redTimer', 'liveStartTimer', 'lotteryTimer', 'noticeTimer',
  1829. 'memoryMonitorTimer', 'networkStatusTimer', 'networkRetryTimer'
  1830. ];
  1831. return timers.filter(timer => this[timer] !== null).length
  1832. },
  1833. cleanupUnusedTimers() {
  1834. const timers = [
  1835. 'trafficTimer', 'pingTimeoutTimer', 'heartBeatTimer', 'liveViewDataTimer',
  1836. 'reconnectTimer', 'scrollTimer', 'searchTimer', 'purchasePromptTimer',
  1837. 'welcomeTimer', 'redTimer', 'liveStartTimer', 'lotteryTimer',
  1838. 'networkStatusTimer', 'networkRetryTimer'
  1839. ];
  1840. timers.forEach(timerName => {
  1841. if (this[timerName] && typeof this[timerName] === 'number') {
  1842. if (timerName.includes('Interval')) {
  1843. clearInterval(this[timerName])
  1844. } else {
  1845. clearTimeout(this[timerName])
  1846. }
  1847. this[timerName] = null
  1848. console.log(`清理了可能泄漏的定时器: ${timerName}`)
  1849. }
  1850. })
  1851. },
  1852. clearAllTimersEnhanced() {
  1853. this.clearAllTimers()
  1854. if (this.networkRetryTimer) {
  1855. clearTimeout(this.networkRetryTimer)
  1856. this.networkRetryTimer = null
  1857. }
  1858. this.stopMemoryMonitor()
  1859. this.userRandomColors = Object.create(null)
  1860. this.shownEntryUsers.clear()
  1861. this.messageCount = 0
  1862. this.errorCount = 0
  1863. this.connectionLatency = 0
  1864. this.lastPerformanceCheck = 0
  1865. console.log('增强清理完成:所有定时器和缓存已清理')
  1866. },
  1867. goMiniProgram() {
  1868. uni.showToast({
  1869. title: '系统升级中,兑换请联系伴学助手!',
  1870. icon: 'none'
  1871. })
  1872. },
  1873. preventDoubleClick(e) {
  1874. e.preventDefault();
  1875. e.stopPropagation();
  1876. return false
  1877. },
  1878. clearAllTimers() {
  1879. const timers = [
  1880. 'noticeTimer',
  1881. 'scrollTimer',
  1882. 'liveViewDataTimer',
  1883. 'redTimer',
  1884. 'liveStartTimer',
  1885. 'lotteryTimer',
  1886. 'welcomeTimer',
  1887. 'trafficInterval',
  1888. 'lookTimer',
  1889. 'trafficTimer',
  1890. 'intervalId',
  1891. 'reconnectTimer',
  1892. 'searchTimer',
  1893. 'purchasePromptTimer',
  1894. 'heartBeatTimer',
  1895. 'pingTimeoutTimer'
  1896. ]
  1897. timers.forEach((timer) => {
  1898. if (this[timer]) {
  1899. if (timer.includes('Interval') || timer.includes('Timer')) {
  1900. clearInterval(this[timer])
  1901. } else {
  1902. clearTimeout(this[timer])
  1903. }
  1904. this[timer] = null
  1905. }
  1906. })
  1907. this.stayTime = 0
  1908. this.startTime = 0
  1909. this.totalTraffic = 0
  1910. this.scrollPending = false
  1911. this.reconnectCount = 0
  1912. this.heartBeatRetryCount = 0
  1913. },
  1914. scrollToBottom() {
  1915. const now = Date.now()
  1916. if (now - this.lastScrollTime < this.scrollDebounceDelay) {
  1917. console.log('滚动防抖:忽略频繁调用')
  1918. return
  1919. }
  1920. this.lastScrollTime = now
  1921. if (this.scrollTimer) {
  1922. clearTimeout(this.scrollTimer)
  1923. this.scrollTimer = null
  1924. }
  1925. this.scrollTop = 999999999
  1926. },
  1927. startMemoryMonitor() {
  1928. if (this.memoryMonitorTimer) {
  1929. clearInterval(this.memoryMonitorTimer)
  1930. }
  1931. this.memoryMonitorTimer = setInterval(() => {
  1932. this.checkAndCleanMemory()
  1933. }, 5 * 60 * 1000);
  1934. },
  1935. checkAndCleanMemory() {
  1936. try {
  1937. if (this.talklist && this.talklist.length > 25) {
  1938. const keepCount = 20
  1939. this.talklist.splice(0, this.talklist.length - keepCount)
  1940. }
  1941. if (this.userRandomColors && Object.keys(this.userRandomColors).length > 50) {
  1942. const entries = Object.entries(this.userRandomColors)
  1943. const keepEntries = entries.slice(-50)
  1944. this.userRandomColors = Object.fromEntries(keepEntries)
  1945. }
  1946. if (this.shownEntryUsers && this.shownEntryUsers.size > 100) {
  1947. const array = Array.from(this.shownEntryUsers)
  1948. this.shownEntryUsers.clear()
  1949. array.slice(-100).forEach((id) => this.shownEntryUsers.add(id))
  1950. }
  1951. console.log('内存清理完成')
  1952. } catch (error) {
  1953. console.error('内存清理失败:', error)
  1954. }
  1955. },
  1956. async resumePageActivity() {
  1957. if (this.liveItem) {
  1958. await this.getliving(this.liveId)
  1959. this.startTimeTimer(this.liveItem)
  1960. }
  1961. if (!this.isSocketAvailable()) {
  1962. this.initSocket()
  1963. }
  1964. },
  1965. getUserRandomColor(userId) {
  1966. if (!userId) {
  1967. return '#8978e2'
  1968. }
  1969. if (this.userRandomColors[userId]) {
  1970. return this.userRandomColors[userId]
  1971. }
  1972. const color = this.generateStableColor(userId)
  1973. this.userRandomColors[userId] = color
  1974. this.saveUserColorsToStorage()
  1975. return color
  1976. },
  1977. generateStableColor(userId) {
  1978. let seed = 0
  1979. for (let i = 0; i < userId.length; i++) {
  1980. seed = (seed * 31 + userId.charCodeAt(i)) % 1000000
  1981. }
  1982. const colorPool = [
  1983. '#FF6B6B',
  1984. '#4ECDC4',
  1985. '#45B7D1',
  1986. '#96CEB4',
  1987. '#FFEAA7',
  1988. '#DDA0DD',
  1989. '#98D8C8',
  1990. '#F7DC6F',
  1991. '#BB8FCE',
  1992. '#85C1E9',
  1993. '#F8C471',
  1994. '#82E0AA',
  1995. '#F1948A',
  1996. '#85C1E9',
  1997. '#D7BDE2'
  1998. ]
  1999. return colorPool[seed % colorPool.length]
  2000. },
  2001. saveUserColorsToStorage() {
  2002. try {
  2003. uni.setStorageSync('userRandomColors', this.userRandomColors)
  2004. } catch (e) {
  2005. console.warn('保存用户颜色缓存失败:', e)
  2006. }
  2007. },
  2008. loadUserColorsFromStorage() {
  2009. try {
  2010. const cached = uni.getStorageSync('userRandomColors')
  2011. if (cached) {
  2012. this.userRandomColors = cached
  2013. }
  2014. } catch (e) {
  2015. console.warn('加载用户颜色缓存失败:', e)
  2016. }
  2017. },
  2018. getNicknameInitial(nickName) {
  2019. if (!nickName || typeof nickName !== 'string') return '未'
  2020. if (/^[\u4e00-\u9fa5]/.test(nickName[0])) {
  2021. return nickName[0]
  2022. }
  2023. return nickName[0].toUpperCase()
  2024. },
  2025. async getUserInfo() {
  2026. await getUserInfo().then((res) => {
  2027. if (res.code == 200) {
  2028. this.userData = res.user
  2029. } else {
  2030. uni.showToast({
  2031. icon: 'none',
  2032. title: '请求失败'
  2033. })
  2034. }
  2035. },
  2036. (rej) => {}
  2037. )
  2038. },
  2039. /**
  2040. * 获取当前服务器时间戳(毫秒)
  2041. * 如果存在 serviceTime,则基于服务器时间计算;否则使用本地时间
  2042. */
  2043. getServerTimeNow() {
  2044. if (!this.liveItem || !this.liveItem.serviceTime) {
  2045. return Date.now();
  2046. }
  2047. const localTimeWhenReceived = this.liveItem._localTimeWhenReceived;
  2048. if (!localTimeWhenReceived) {
  2049. // 如果没有记录接收时间,使用本地时间
  2050. return Date.now();
  2051. }
  2052. let serverTimeWhenReceived;
  2053. const serviceTime = this.liveItem.serviceTime;
  2054. //如果 serviceTime 是数字类型(毫秒级时间戳)
  2055. if (typeof serviceTime === 'number') {
  2056. serverTimeWhenReceived = serviceTime;
  2057. }
  2058. //如果 serviceTime 是字符串格式的数字时间戳
  2059. else if (typeof serviceTime === 'string' && /^\d+$/.test(serviceTime)) {
  2060. // 纯数字字符串,转换为数字
  2061. const numTime = Number(serviceTime);
  2062. // 判断是秒级还是毫秒级时间戳(13位及以上为毫秒级)
  2063. serverTimeWhenReceived = numTime < 1000000000000 ? numTime * 1000 : numTime;
  2064. }
  2065. //如果 serviceTime 是时间字符串
  2066. else {
  2067. const safeTimeStr = String(serviceTime).replace(/-/g, '/');
  2068. serverTimeWhenReceived = Date.parse(safeTimeStr);
  2069. if (isNaN(serverTimeWhenReceived)) {
  2070. return Date.now();
  2071. }
  2072. }
  2073. //计算服务器时间与本地时间的差值(毫秒)
  2074. const timeDiff = serverTimeWhenReceived - localTimeWhenReceived;
  2075. // 当前服务器时间 = 当前本地时间 + 时间差
  2076. return Date.now() + timeDiff;
  2077. },
  2078. /**
  2079. * 获取直播开始时间,优先使用 serviceStartTime,如果不存在则使用 startTime
  2080. */
  2081. getLiveStartTime() {
  2082. if (!this.liveItem) {
  2083. return null;
  2084. }
  2085. // 优先使用 serviceStartTime(服务器返回的直播开始时间)
  2086. if (this.liveItem.serviceStartTime) {
  2087. return this.liveItem.serviceStartTime;
  2088. }
  2089. // 如果不存在,回退到 startTime
  2090. return this.liveItem.startTime || null;
  2091. },
  2092. handleAgreement() {
  2093. const templateId = this.templateId
  2094. if (this.hasSubscribed) return;
  2095. uni.requestSubscribeMessage({
  2096. tmplIds: [templateId],
  2097. success: (res) => {
  2098. if (res[templateId] === 'accept') {
  2099. uni.showToast({
  2100. title: '订阅成功,开播将提醒您',
  2101. icon: 'success',
  2102. duration: 2500 // 成功提示延长到2.5秒
  2103. })
  2104. this.hasSubscribed = true;
  2105. uni.setStorageSync('subscribe_status_' + this.liveId, true);
  2106. this.callSendMessageApi()
  2107. } else if (res[templateId] === 'reject') {
  2108. uni.showToast({
  2109. title: '您已拒绝订阅,将无法收到提醒',
  2110. icon: 'none',
  2111. duration: 2500 // 成功提示延长到2.5秒
  2112. })
  2113. } else if (res[templateId] === 'ban') {
  2114. uni.showToast({
  2115. title: '您已关闭所有订阅权限,请在设置中开启',
  2116. icon: 'none',
  2117. duration: 2500 // 成功提示延长到2.5秒
  2118. })
  2119. }
  2120. },
  2121. fail: (err) => {
  2122. console.error('订阅消息失败', err)
  2123. uni.showToast({
  2124. title: '订阅失败,请重试',
  2125. icon: 'none',
  2126. duration: 2500 // 成功提示延长到2.5秒
  2127. })
  2128. }
  2129. })
  2130. },
  2131. async callSendMessageApi() {
  2132. if (!this.userData.userId) return
  2133. const templateData = {
  2134. liveId: this.liveId,
  2135. userId: this.userData.userId,
  2136. templateId: this.templateId || '',
  2137. maOpenId: this.userData.maOpenId || '',
  2138. appid: this.appid || '',
  2139. data: {
  2140. thing6: this.liveItem.liveName,
  2141. date7: this.liveItem.startTime
  2142. }
  2143. }
  2144. subNotifyLive(templateData).then(
  2145. (res) => {
  2146. if (res.code == 200) {
  2147. this.isAgreement = true
  2148. uni.setStorageSync('isAgreement', true)
  2149. } else {
  2150. uni.showToast({
  2151. title: res.msg,
  2152. icon: 'none'
  2153. })
  2154. }
  2155. },
  2156. (rej) => {}
  2157. )
  2158. },
  2159. sendHeartBeat() {
  2160. if (!this.isSocketAvailable() || !this.isNetworkAvailable) {
  2161. console.warn('网络不可用或Socket连接异常,跳过心跳发送')
  2162. return
  2163. }
  2164. this.lastHeartBeatTime = Date.now()
  2165. try {
  2166. const heartBeatMsg = JSON.stringify({
  2167. cmd: 'heartbeat',
  2168. msg: 'ping',
  2169. userId: this.userData.userId || '',
  2170. liveId: this.liveId,
  2171. timestamp: this.lastHeartBeatTime,
  2172. networkType: this.networkType
  2173. })
  2174. this.socket.send({
  2175. data: heartBeatMsg,
  2176. success: () => {
  2177. this.heartBeatRetryCount = 0
  2178. this.adjustHeartBeatInterval(true)
  2179. this.startPingTimeout()
  2180. },
  2181. fail: (err) => {
  2182. console.error('心跳包发送失败:', err)
  2183. this.heartBeatRetryCount++
  2184. this.adjustHeartBeatInterval(false)
  2185. const retryDelay = this.getRetryDelay()
  2186. if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
  2187. setTimeout(() => this.sendHeartBeat(), retryDelay)
  2188. } else {
  2189. this.heartBeatRetryCount = 0
  2190. this.handleReconnect()
  2191. }
  2192. }
  2193. })
  2194. } catch (err) {
  2195. console.error('心跳发送异常:', err)
  2196. this.heartBeatRetryCount++
  2197. const retryDelay = this.getRetryDelay()
  2198. if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
  2199. setTimeout(() => this.sendHeartBeat(), retryDelay)
  2200. } else {
  2201. this.heartBeatRetryCount = 0
  2202. this.handleReconnect()
  2203. }
  2204. }
  2205. },
  2206. getRetryDelay() {
  2207. const baseDelay = 2000
  2208. const retryMultiplier = Math.pow(1.5, this.heartBeatRetryCount)
  2209. let networkMultiplier = 1
  2210. switch (this.networkType) {
  2211. case '2g':
  2212. networkMultiplier = 3
  2213. break
  2214. case '3g':
  2215. networkMultiplier = 2
  2216. break
  2217. case '4g':
  2218. case '5g':
  2219. networkMultiplier = 1
  2220. break
  2221. case 'wifi':
  2222. networkMultiplier = 0.8
  2223. break
  2224. default:
  2225. networkMultiplier = 1.5
  2226. }
  2227. return Math.min(baseDelay * retryMultiplier * networkMultiplier, 10000)
  2228. },
  2229. adjustHeartBeatInterval(isSuccess) {
  2230. if (isSuccess) {
  2231. this.adaptiveHeartBeatInterval = Math.min(this.adaptiveHeartBeatInterval * 1.1, 30000)
  2232. } else {
  2233. this.adaptiveHeartBeatInterval = Math.max(this.adaptiveHeartBeatInterval * 0.9, 10000)
  2234. }
  2235. },
  2236. startPingTimeout() {
  2237. if (this.pingTimeoutTimer) {
  2238. clearTimeout(this.pingTimeoutTimer)
  2239. this.pingTimeoutTimer = null
  2240. }
  2241. this.pingTimeoutTimer = setTimeout(() => {
  2242. console.warn('心跳超时,触发重连')
  2243. this.pingTimeoutTimer = null
  2244. this.heartBeatRetryCount++
  2245. if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
  2246. console.log(`心跳超时,尝试重发 (${this.heartBeatRetryCount}/${this.maxHeartBeatRetries})`)
  2247. setTimeout(() => this.sendHeartBeat(), 1000)
  2248. } else {
  2249. console.log('心跳重试次数用尽,触发重连')
  2250. this.heartBeatRetryCount = 0
  2251. this.handleReconnect()
  2252. }
  2253. }, this.pingTimeout)
  2254. },
  2255. stopHeartBeat() {
  2256. if (this.heartBeatTimer) {
  2257. clearInterval(this.heartBeatTimer)
  2258. this.heartBeatTimer = null
  2259. }
  2260. if (this.pingTimeoutTimer) {
  2261. clearTimeout(this.pingTimeoutTimer)
  2262. this.pingTimeoutTimer = null
  2263. }
  2264. },
  2265. isSocketAvailable() {
  2266. return this.socket && this.isSocketOpen && this.socket.readyState === 1
  2267. },
  2268. handleReconnect() {
  2269. if (this.isManualClose) {
  2270. console.log('手动关闭连接,不进行重连')
  2271. return
  2272. }
  2273. if (this.reconnectTimer) {
  2274. console.log('重连已在进行中,跳过重复重连')
  2275. return
  2276. }
  2277. this.stopHeartBeat()
  2278. if (!this.isNetworkAvailable) {
  2279. console.warn('网络不可用,延迟重连')
  2280. this.reconnectTimer = setTimeout(() => {
  2281. this.reconnectTimer = null
  2282. this.handleReconnect()
  2283. }, 5000)
  2284. return
  2285. }
  2286. if (this.reconnectCount < this.maxReconnectAttempts) {
  2287. this.reconnectCount++
  2288. const baseDelay = 1000
  2289. const exponentialDelay = baseDelay * Math.pow(2, this.reconnectCount - 1)
  2290. const jitter = Math.random() * 1000
  2291. const totalDelay = Math.min(exponentialDelay + jitter, 30000)
  2292. console.log(`第${this.reconnectCount}次重连,延迟${Math.round(totalDelay)}ms,网络类型:${this.networkType}`)
  2293. this.reconnectTimer = setTimeout(() => {
  2294. this.reconnectTimer = null
  2295. if (this.isNetworkAvailable && !this.isManualClose && !this.isSocketAvailable()) {
  2296. console.log('开始执行重连...')
  2297. this.initSocket()
  2298. } else if (this.isSocketAvailable()) {
  2299. console.log('连接已恢复,取消重连')
  2300. this.reconnectCount = 0
  2301. } else {
  2302. console.warn('重连时网络不可用或已手动关闭')
  2303. this.handleReconnect()
  2304. }
  2305. }, totalDelay)
  2306. } else {
  2307. console.log(`已达最大重连次数(${this.maxReconnectAttempts}),停止重连`)
  2308. this.showReconnectFailedMessage()
  2309. }
  2310. },
  2311. showReconnectFailedMessage() {
  2312. uni.showToast({
  2313. title: '网络连接异常,请检查网络后重新进入',
  2314. icon: 'none',
  2315. duration: 3000
  2316. })
  2317. },
  2318. handleConnectionError(errorType, error) {
  2319. console.error(`WebSocket ${errorType}:`, error)
  2320. if (errorType === '连接请求失败') {
  2321. if (!this.isNetworkAvailable) {
  2322. console.warn('网络不可用,等待网络恢复后重连')
  2323. return
  2324. }
  2325. }
  2326. this.handleReconnect()
  2327. },
  2328. resetReconnectState() {
  2329. this.reconnectCount = 0
  2330. this.heartBeatRetryCount = 0
  2331. if (this.reconnectTimer) {
  2332. clearTimeout(this.reconnectTimer)
  2333. this.reconnectTimer = null
  2334. }
  2335. this.adaptiveHeartBeatInterval = this.heartBeatInterval
  2336. },
  2337. initNetworkStatusListener() {
  2338. uni.getNetworkType({
  2339. success: (res) => {
  2340. this.networkType = res.networkType
  2341. this.isNetworkAvailable = res.networkType !== 'none'
  2342. console.log('当前网络类型:', res.networkType)
  2343. }
  2344. })
  2345. uni.onNetworkStatusChange((res) => {
  2346. const oldNetworkType = this.networkType
  2347. const oldNetworkAvailable = this.isNetworkAvailable
  2348. this.networkType = res.networkType
  2349. this.isNetworkAvailable = res.isConnected
  2350. console.log(`网络状态变化: ${oldNetworkType} -> ${res.networkType}, 连接状态: ${res.isConnected}`)
  2351. if (!oldNetworkAvailable && res.isConnected) {
  2352. console.log('网络恢复,尝试重连WebSocket')
  2353. this.resetReconnectState()
  2354. setTimeout(() => {
  2355. if (!this.isSocketAvailable()) {
  2356. this.initSocket()
  2357. }
  2358. }, 1000)
  2359. }
  2360. if (oldNetworkType !== res.networkType && res.isConnected) {
  2361. this.adjustHeartBeatForNetworkType(res.networkType)
  2362. }
  2363. if (!res.isConnected) {
  2364. console.warn('网络断开,停止心跳')
  2365. this.stopHeartBeat()
  2366. }
  2367. })
  2368. },
  2369. adjustHeartBeatForNetworkType(networkType) {
  2370. let newInterval = this.heartBeatInterval
  2371. switch (networkType) {
  2372. case '2g':
  2373. newInterval = 30000
  2374. break
  2375. case '3g':
  2376. newInterval = 20000
  2377. break
  2378. case '4g':
  2379. case '5g':
  2380. newInterval = 15000
  2381. break
  2382. case 'wifi':
  2383. newInterval = 10000
  2384. break
  2385. default:
  2386. newInterval = 15000
  2387. }
  2388. if (newInterval !== this.adaptiveHeartBeatInterval) {
  2389. this.adaptiveHeartBeatInterval = newInterval
  2390. console.log(`根据网络类型(${networkType})调整心跳间隔为${newInterval}ms`)
  2391. if (this.heartBeatTimer && this.isSocketAvailable()) {
  2392. this.startHeartBeat()
  2393. }
  2394. }
  2395. },
  2396. inputFocus() {
  2397. this.isFocus = true
  2398. this.isKeyboardShow = true
  2399. },
  2400. inputBlur() {
  2401. this.isFocus = false
  2402. },
  2403. onRed() {
  2404. if (!this.liveId) return
  2405. if (!this.redInfo?.redId) return
  2406. if (this.redTimer) {
  2407. clearInterval(this.redTimer)
  2408. this.redTimer = null
  2409. }
  2410. let data = {
  2411. liveId: this.liveId,
  2412. userId: this.userData.userId,
  2413. redId: this.redInfo.redId
  2414. }
  2415. liveRed(data).then(
  2416. (res) => {
  2417. this.isShowRed = false
  2418. this.redCard = res
  2419. this.isShowRedCard = true
  2420. },
  2421. (rej) => {}
  2422. )
  2423. },
  2424. onCoupon() {
  2425. if (!this.couponInfo.couponIssueId) return
  2426. let data = {
  2427. goodsId: this.couponInfo.goodsId,
  2428. couponIssueId: this.couponInfo.couponIssueId,
  2429. liveId: this.liveId
  2430. }
  2431. coupon(data).then((res) => {
  2432. this.isShowCoupon = false
  2433. if (res.code == 200) {
  2434. uni.showToast({
  2435. title: res.msg,
  2436. icon: 'none'
  2437. })
  2438. } else {
  2439. uni.showToast({
  2440. title: res.msg,
  2441. icon: 'none'
  2442. })
  2443. }
  2444. }).catch((rej) => {})
  2445. },
  2446. getMyLottery() {
  2447. this.winning = true
  2448. myLottery()
  2449. .then((res) => {
  2450. if (res.code == 200) {
  2451. this.prizeAll = res.data.list || {}
  2452. } else {}
  2453. })
  2454. .catch((rej) => {})
  2455. },
  2456. onLottery() {
  2457. if (!this.lotteryInfo) return
  2458. let data = {
  2459. lotteryId: this.lotteryInfo.lotteryId
  2460. }
  2461. liveLottery(data)
  2462. .then((res) => {
  2463. if (res.code == 200) {
  2464. const resData = res.data || {}
  2465. this.lotteryList = Array.isArray(resData) ? resData : []
  2466. this.lotteryProducts = Array.isArray(resData.products) ? resData.products : []
  2467. if (resData.duration) {
  2468. this.isShowLotteryPop = true
  2469. }
  2470. } else {
  2471. uni.showToast({
  2472. title: res.msg,
  2473. icon: 'none'
  2474. })
  2475. this.lotteryList = []
  2476. this.lotteryProducts = []
  2477. }
  2478. })
  2479. .catch((rej) => {
  2480. uni.showToast({
  2481. title: '获取抽奖信息失败',
  2482. icon: 'none'
  2483. })
  2484. this.lotteryList = []
  2485. this.lotteryProducts = []
  2486. })
  2487. },
  2488. onClaim() {
  2489. let data = {
  2490. liveId: this.liveId,
  2491. lotteryId: this.lotteryInfo.lotteryId
  2492. }
  2493. claim(data).then(
  2494. (res) => {
  2495. if (res.code == 200) {
  2496. uni.showToast({
  2497. title: res.msg,
  2498. icon: 'none'
  2499. })
  2500. this.isShowLotteryPop = false
  2501. this.havePrize = true
  2502. uni.setStorageSync('havePrize', this.havePrize)
  2503. } else {
  2504. uni.showToast({
  2505. title: res.msg,
  2506. icon: 'none'
  2507. })
  2508. }
  2509. },
  2510. (rej) => {}
  2511. )
  2512. },
  2513. confirm() {
  2514. this.isShowPrize = false
  2515. this.havePrize = false
  2516. uni.setStorageSync('havePrize', this.havePrize)
  2517. },
  2518. onGoodsCollect(item) {
  2519. if (!item || item.length === 0 || !item.goodsId) {
  2520. return
  2521. }
  2522. collectGoods(item.goodsId).then(
  2523. (res) => {
  2524. if (res.code == 200) {
  2525. uni.showToast({
  2526. title: res.msg,
  2527. icon: 'none'
  2528. })
  2529. item.isFavorite = !item.isFavorite
  2530. } else {
  2531. uni.showToast({
  2532. title: res.msg,
  2533. icon: 'none'
  2534. })
  2535. }
  2536. },
  2537. (rej) => {}
  2538. )
  2539. },
  2540. handleGoShopFromCart(item) {
  2541. this.goShop(item.productId, item.goodsId)
  2542. },
  2543. getliveOrder(item) {
  2544. if (!this.liveId) {
  2545. return
  2546. }
  2547. liveOrderUser(this.liveId).then(
  2548. (res) => {
  2549. if (res.code == 200) {
  2550. this.orderUser = res
  2551. } else {
  2552. console.log('获取正在购买用户失败')
  2553. }
  2554. },
  2555. (rej) => {}
  2556. )
  2557. },
  2558. onLiveStateChange(e, liveItem) {
  2559. const stateCode = e.detail.code
  2560. if (e.detail.code == -2301 || e.detail.code == -2302) {
  2561. if (this.$refs.liveVideo && this.$refs.liveVideo.playVideo) {
  2562. this.$refs.liveVideo.playVideo()
  2563. }
  2564. } else if (e.detail.code == 2004) {
  2565. this.calculateTimeDiff(this.liveItem)
  2566. this.startTrafficCalculation(this.bitrateLive)
  2567. }
  2568. },
  2569. onLiveError(e, liveItem) {
  2570. this.videoError(e, liveItem)
  2571. console.log('错误')
  2572. },
  2573. getCurrentActivities() {
  2574. if (!this.liveId) return
  2575. currentActivities(this.liveId).then(
  2576. (res) => {
  2577. if (res.code === 200) {
  2578. this.redInfo = (Array.isArray(res.red) ? res.red : [])[0] || {}
  2579. this.lotteryInfo = (Array.isArray(res.lottery) ? res.lottery : [])[0] || {}
  2580. this.goodsCard = res.goods || {}
  2581. this.notice = res.topMsg || {}
  2582. this.isShowGoods = this.goodsCard && this.goodsCard.status == 1
  2583. this.isShowRed = this.redInfo && this.redInfo.redStatus == 1
  2584. this.isShowLottery = this.lotteryInfo && this.lotteryInfo.lotteryStatus == 1
  2585. if (this.isShowRed) {
  2586. this.redTimer = setInterval(() => {
  2587. const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo
  2588. .duration)
  2589. if (!redCountdown) {
  2590. this.isShowRed = false
  2591. clearInterval(this.redTimer)
  2592. }
  2593. }, 1000)
  2594. }
  2595. if (this.notice.msg) {
  2596. this.noticeTimer = setInterval(() => {
  2597. const noticeCountdown = this.handleTime(this.notice.endTime, 0)
  2598. console.log('出现1>>>', noticeCountdown)
  2599. if (!noticeCountdown) {
  2600. this.isShowNotice = false
  2601. clearInterval(this.noticeTimer)
  2602. } else {
  2603. this.isShowNotice = true
  2604. }
  2605. }, 1000)
  2606. }
  2607. if (this.isShowLottery) {
  2608. this.lotteryTimer = setInterval(() => {
  2609. this.countdown = this.handleTime(this.lotteryInfo.updateTime, this
  2610. .lotteryInfo.duration)
  2611. }, 1000)
  2612. }
  2613. } else {
  2614. uni.showToast({
  2615. title: res.msg,
  2616. icon: 'none'
  2617. })
  2618. }
  2619. },
  2620. (rej) => {}
  2621. )
  2622. },
  2623. calculateTimeDiff(item) {
  2624. if (!item.startTime) return
  2625. let timeStr = item.startTime
  2626. const time = new Date(timeStr.replace(/-/g, '/'))
  2627. if (isNaN(time.getTime())) {
  2628. return
  2629. }
  2630. const now = new Date()
  2631. let diffMs = Math.max(0, now.getTime() - time.getTime())
  2632. const totalSeconds = Math.floor(diffMs / 1000)
  2633. const hours = this.padZero(Math.floor(totalSeconds / 3600))
  2634. const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60))
  2635. const seconds = this.padZero(totalSeconds % 60)
  2636. this.diffTotalTime = `${hours}:${minutes}:${seconds}`
  2637. },
  2638. padZero(num) {
  2639. return num < 10 ? `0${num}` : num
  2640. },
  2641. startTimeTimer(item) {
  2642. if (!item) return
  2643. const totalTime = this.calculateTimeDiff(item)
  2644. item.timeTimer = setInterval(() => {
  2645. const totalTime = this.calculateTimeDiff(item)
  2646. }, 1000);
  2647. },
  2648. toggleViewerList() { //加载直播间观众
  2649. const now = Date.now()
  2650. if (now - this.lastClickTime > this.clickDelay) {
  2651. this.showViewerList = !this.showViewerList
  2652. this.lastClickTime = now;
  2653. }
  2654. },
  2655. closeViewerList() {
  2656. this.showViewerList = false
  2657. },
  2658. openViewerList() {
  2659. // this.$nextTick(() => {
  2660. // this.calculateScrollHeight()
  2661. // })
  2662. },
  2663. calculateScrollHeight() {
  2664. // const query = uni.createSelectorQuery().in(this)
  2665. // query.select('.viewer-list-popup').boundingClientRect((data) => {
  2666. // if (data) {
  2667. // this.scrollHeight = data.height - 120
  2668. // }
  2669. // }).exec()
  2670. },
  2671. openViews() {
  2672. this.$nextTick(() => {
  2673. const query = uni.createSelectorQuery().in(this)
  2674. query.select('.view-box').boundingClientRect((data) => {
  2675. if (data) {
  2676. this.scrollHeight = data.height - 80
  2677. }
  2678. }).exec();
  2679. })
  2680. },
  2681. async handleViewerLoadMore(page) {
  2682. if (this.viewLoading) return;
  2683. this.viewPageNum = page.num;
  2684. // 调用getliveUser加载更多数据
  2685. await this.getliveUser(page.num > 1);
  2686. },
  2687. async getLiveMsg(liveItem) {
  2688. if (!liveItem || !this.liveId) {
  2689. console.error('getLiveMsg 错误:无效的 liveItem')
  2690. return
  2691. }
  2692. try {
  2693. const res = await liveMsg(this.liveId, 30, 1)
  2694. if (res.code == 200) {
  2695. const rows = Array.isArray(res.rows) ? res.rows : []
  2696. const reversedTalkList = [...rows].reverse()
  2697. this.talklist = Array.isArray(reversedTalkList) ? reversedTalkList : []
  2698. this.$nextTick(() => {
  2699. this.scrollToBottom()
  2700. })
  2701. } else {
  2702. this.talklist = []
  2703. }
  2704. } catch (error) {
  2705. this.talklist = []
  2706. console.error('获取聊天记录失败:', error)
  2707. }
  2708. },
  2709. generateRandomChineseName() {
  2710. const prefixes = [
  2711. '幸福', '快乐', '安康', '吉祥', '如意', '平安', '健康', '长寿', '福气', '美满',
  2712. '和谐', '团圆', '富贵', '荣华', '宁静', '淡泊', '知足', '常乐', '悠然', '自在',
  2713. '夕阳', '晚霞', '金秋', '银发', '老顽童', '开心', '笑口常开', '岁月静好', '云淡风轻', '海阔天空'
  2714. ]
  2715. const suffixes = [
  2716. '老人', '大爷', '大妈', '爷爷', '奶奶', '伯伯', '阿姨', '前辈', '先生', '女士',
  2717. '长者', '翁', '婆', '哥', '姐', '友', '客', '迷', '粉丝', '达人',
  2718. '爱好者', '之家', '之人', '之心', '之情', '之乐', '之旅', '之梦', '之歌', '之韵'
  2719. ]
  2720. const specialNames = [
  2721. '老有所乐', '知足常乐', '笑看人生', '云淡风轻', '岁月如歌', '夕阳红', '金色年华', '老当益壮',
  2722. '鹤发童颜', '老骥伏枥', '闲云野鹤', '淡泊明志', '宁静致远', '随遇而安', '顺其自然',
  2723. '老来俏', '开心果', '老宝贝', '不老松', '常青树'
  2724. ]
  2725. if (Math.random() < 0.3) {
  2726. return specialNames[Math.floor(Math.random() * specialNames.length)]
  2727. } else {
  2728. const prefix = prefixes[Math.floor(Math.random() * prefixes.length)]
  2729. const suffix = suffixes[Math.floor(Math.random() * suffixes.length)]
  2730. return prefix + suffix
  2731. }
  2732. },
  2733. async getliveUser(isLoadMore = false) {
  2734. if (!isLoadMore) {
  2735. this.liveViewers = []
  2736. this.viewPageNum = 1
  2737. }
  2738. this.viewLoading = true;
  2739. try {
  2740. const res = await watchUserList(this.liveId, this.viewPageSize, this.viewPageNum, false);
  2741. console.log("qxj watchUserList res", res);
  2742. if (res.code === 200) {
  2743. const newRows = Array.isArray(res.rows) ? res.rows : []
  2744. const newViewers = newRows.map((item) => ({
  2745. avatar: item.avatar || '',
  2746. userId: item.userId || '',
  2747. nickName: item.nickName || '未命名'
  2748. }));
  2749. let virtualData = [];
  2750. // 计算虚拟总数
  2751. let virtualTotal = res.total * 2 + 50;
  2752. // 计算需要生成的虚拟数据数量
  2753. let totalVirtualNeeded = virtualTotal - res.total;
  2754. totalVirtualNeeded = Math.max(0, Math.min(totalVirtualNeeded, 90)); // 最多生成90条虚拟数据
  2755. if (!isLoadMore) {
  2756. // 首次加载时,生成第一批虚拟数据(与真实数据合计不超过10个)
  2757. let firstBatchVirtualCount = Math.max(0, 10 - newRows.length);
  2758. for (let i = 0; i < firstBatchVirtualCount; i++) {
  2759. let data = {
  2760. avatar: '',
  2761. userId: '8565' + i,
  2762. nickName: this.generateRandomChineseName()
  2763. }
  2764. virtualData.push(data);
  2765. }
  2766. this.liveViewersData = [...newViewers, ...virtualData];
  2767. } else {
  2768. // 后续加载时,计算已加载的虚拟数据数量
  2769. let loadedVirtualCount = this.liveViewers.filter(v => String(v.userId).startsWith('8565')).length;
  2770. // 计算还需要加载的虚拟数据数量
  2771. let remainingVirtualCount = totalVirtualNeeded - loadedVirtualCount;
  2772. // 本次加载的虚拟数据数量(最多10个)
  2773. let currentBatchVirtualCount = Math.min(remainingVirtualCount, this.viewPageSize);
  2774. // 生成本次加载的虚拟数据
  2775. for (let i = 0; i < currentBatchVirtualCount; i++) {
  2776. let data = {
  2777. avatar: '',
  2778. userId: '8565' + (loadedVirtualCount + i),
  2779. nickName: this.generateRandomChineseName()
  2780. }
  2781. virtualData.push(data);
  2782. }
  2783. }
  2784. // 过滤掉旧列表中的虚拟数据,保留真实用户
  2785. let currentRealViewers = isLoadMore ? this.liveViewers.filter(v => !String(v.userId)
  2786. .startsWith('8565')) : [];
  2787. // 合并真实用户
  2788. let allRealViewers = [...currentRealViewers, ...newViewers];
  2789. // 合并虚拟用户
  2790. let currentVirtualViewers = isLoadMore ? this.liveViewers.filter(v => String(v.userId).startsWith('8565')) : [];
  2791. let allVirtualViewers = [...currentVirtualViewers, ...virtualData];
  2792. // 合并所有用户
  2793. let mergedViewers = [...allRealViewers, ...allVirtualViewers];
  2794. // 确保观众列表不超过100个
  2795. if (mergedViewers.length > 100) {
  2796. mergedViewers = mergedViewers.slice(0, 100);
  2797. }
  2798. this.liveViewers = mergedViewers;
  2799. // 检查虚拟数据是否还有剩余
  2800. let totalLoaded = allRealViewers.length + allVirtualViewers.length;
  2801. let remainingVirtualCount = totalVirtualNeeded - allVirtualViewers.length;
  2802. // 计算是否还有更多数据
  2803. // 1. 如果真实用户还有更多
  2804. // 2. 或者虚拟数据还有剩余
  2805. // 3. 但不超过100个
  2806. let hasMore = ((newRows.length >= this.viewPageSize) || (remainingVirtualCount > 0)) && (totalLoaded < 100);
  2807. // 确保即使真实用户数据加载完毕,只要虚拟数据还有剩余且未超过100个,就继续加载
  2808. if (remainingVirtualCount > 0 && totalLoaded < 100) {
  2809. hasMore = true;
  2810. }
  2811. if (totalLoaded >= virtualTotal || totalLoaded >= 100) {
  2812. hasMore = false;
  2813. this.lookAudsCount = Math.max(0, virtualTotal - 100);
  2814. } else {
  2815. this.lookAudsCount = 0;
  2816. }
  2817. if (this.$refs.viewer) {
  2818. this.$refs.viewer.endSuccess(newRows.length + virtualData.length, hasMore);
  2819. }
  2820. } else {
  2821. if (this.$refs.viewer) this.$refs.viewer.endErr();
  2822. }
  2823. } catch (error) {
  2824. console.error('获取观众列表失败:', error)
  2825. if (this.$refs.viewer) this.$refs.viewer.endErr();
  2826. } finally {
  2827. this.viewLoading = false
  2828. }
  2829. },
  2830. async getliveUserInit(isLoadMore = false) {
  2831. try {
  2832. const res = await watchUserList(this.liveId, this.viewPageSize, 1, false);
  2833. console.log("qxj watchUserList res", res);
  2834. if (res.code === 200) {
  2835. const userRows = Array.isArray(res.rows) ? res.rows : []
  2836. let array = userRows.map((item) => ({
  2837. avatar: item.avatar || '',
  2838. userId: item.userId || '',
  2839. nickName: item.nickName || '未命名'
  2840. }));
  2841. let virtualTotal = res.total * 2 + 50;
  2842. // 使用虚拟的观众总数
  2843. this.liveUserTotal = virtualTotal || 0;
  2844. this.liveTopViewersData = [...array];
  2845. }
  2846. } catch (error) {
  2847. console.error('获取观众列表失败:', error)
  2848. } finally {}
  2849. },
  2850. showPurchaseMessage() {
  2851. if (this.purchasePromptTimer) {
  2852. clearTimeout(this.purchasePromptTimer)
  2853. }
  2854. this.showPurchasePrompt = true
  2855. this.purchasePromptTimer = setTimeout(() => {
  2856. this.showPurchasePrompt = false
  2857. }, 2000)
  2858. },
  2859. truncateString(str, maxLength) {
  2860. if (typeof str !== 'string' || str.length <= maxLength) {
  2861. return str
  2862. }
  2863. return str.slice(0, maxLength) + '...'
  2864. },
  2865. navgetTo(url) {
  2866. uni.navigateTo({
  2867. url: url
  2868. })
  2869. },
  2870. async getliving(liveId) {
  2871. if (!liveId) return
  2872. const param = {
  2873. id: liveId
  2874. }
  2875. try {
  2876. const res = await getlive(param)
  2877. if (res.code !== 200) {
  2878. uni.showToast({
  2879. title: res.msg,
  2880. icon: 'none'
  2881. })
  2882. return
  2883. }
  2884. this.liveItem = Object.assign({}, this.liveItem, res.data)
  2885. this.startTimeTimer(this.liveItem)
  2886. if (this.liveStartTimer) {
  2887. clearInterval(this.liveStartTimer)
  2888. this.liveStartTimer = null
  2889. }
  2890. if (res.data.status == 1) {
  2891. this.liveStartTimer = setInterval(async () => {
  2892. this.liveCountdown = this.handleTime(res.data.startTime, 0)
  2893. if (!this.liveCountdown) {
  2894. uni.removeStorageSync('isAgreement')
  2895. await this.getliving(this.liveId)
  2896. clearInterval(this.liveStartTimer)
  2897. }
  2898. }, 1000)
  2899. this.$set(this.liveItem, 'previewUrl', res.data.previewUrl)
  2900. this.$set(this.liveItem, 'livingUrl', '')
  2901. this.$set(this.liveItem, 'videoUrl', '')
  2902. } else if (res.data.status == 2) {
  2903. if (res.data.liveType == 1) {
  2904. let cTime = Math.floor(Math.random() * 10000) + 1
  2905. let livingUrl = res.data.flvHlsUrl + '&t=' + cTime
  2906. this.$set(this.liveItem, 'livingUrl', livingUrl)
  2907. this.$set(this.liveItem, 'videoUrl', '')
  2908. } else if (res.data.liveType === 2) {
  2909. this.$set(this.liveItem, 'videoUrl', res.data.videoUrl)
  2910. this.$set(this.liveItem, 'livingUrl', '')
  2911. }
  2912. } else if (res.data.status == 4 && res.data.liveType == 3) {
  2913. this.$set(this.liveItem, 'videoUrl', res.data.videoUrl)
  2914. this.$set(this.liveItem, 'livingUrl', '')
  2915. } else {
  2916. this.$set(this.liveItem, 'livingUrl', '')
  2917. this.$set(this.liveItem, 'videoUrl', '')
  2918. }
  2919. // if (this.liveItem.configJson) {
  2920. // this.completionRate = JSON.parse(this.liveItem.configJson).completionRate * 0.01;
  2921. // }
  2922. this.$set(this.liveItem, 'autoplay', res.data.liveType !== 0)
  2923. this.$set(this.liveItem, 'showType', res.data.showType)
  2924. this.storeId = res.storeId
  2925. this.diffLiveStartTime = this.calculateLiveTimeDiff(this.liveItem.startTime);
  2926. if (this.diffLiveStartTime < 0) { //预告
  2927. this.isPreview = true;
  2928. this.liveBeginWatchTime = Date.now();
  2929. } else {
  2930. if (!this.hasLiveEnd) { //没经历过直播结束
  2931. this.liveBeginWatchTime = Date.now();
  2932. }
  2933. }
  2934. console.log("是否调用积分列表", this.liveItem.completionPointsEnabled)
  2935. if (this.liveItem.completionPointsEnabled) {
  2936. console.log("是否调用积分列表")
  2937. this.getRemainingTime()
  2938. }
  2939. // 初始化累计观看时间
  2940. this.initWatchTime();
  2941. this.startLiveViewDataTimer()
  2942. if (this.$refs.liveVideo && this.$refs.liveVideo.playVideo) {
  2943. this.$refs.liveVideo.playVideo()
  2944. }
  2945. } catch (err) {
  2946. console.error('获取直播信息失败:', err)
  2947. uni.showToast({
  2948. title: '获取直播信息失败',
  2949. icon: 'none'
  2950. })
  2951. }
  2952. },
  2953. getPureDecimal(num, precision = 6) {
  2954. const decimalPart = Math.abs(num).toFixed(precision).split('.')[1]
  2955. return decimalPart?.replace(/0+$/, '') || ''
  2956. },
  2957. goBack() {
  2958. if (this.liveItem) {
  2959. if (this.$refs.liveVideo && this.$refs.liveVideo.pauseVideo) {
  2960. this.$refs.liveVideo.pauseVideo()
  2961. }
  2962. }
  2963. this.closeWebSocket(true)
  2964. const pages = getCurrentPages()
  2965. if (pages.length > 1) {
  2966. uni.navigateBack()
  2967. } else {
  2968. uni.reLaunch({
  2969. url: '/pages_course/livingList'
  2970. })
  2971. }
  2972. },
  2973. async onLike() {
  2974. if (!this.liveId) return
  2975. try {
  2976. const res = await liveDataLike(this.liveId)
  2977. if (res?.like) {
  2978. this.liveViewData.like++
  2979. } else {
  2980. uni.showToast({
  2981. title: res.msg,
  2982. icon: 'none'
  2983. })
  2984. }
  2985. } catch (error) {
  2986. console.error('点赞失败:', error)
  2987. }
  2988. },
  2989. getliveViewData() {
  2990. if (!this.liveId) return
  2991. getLiveViewData(this.liveId).then((res) => {
  2992. if (res.code == 200) {
  2993. this.liveViewData = res
  2994. }
  2995. }).catch((error) => {
  2996. console.error('获取直播间数据失败:', error)
  2997. this.liveViewData = {
  2998. like: 0,
  2999. watchCount: 0
  3000. }
  3001. })
  3002. },
  3003. startLiveViewDataTimer() {
  3004. if (this.liveViewDataTimer) {
  3005. clearInterval(this.liveViewDataTimer)
  3006. this.liveViewDataTimer = null
  3007. }
  3008. this.getliveViewData()
  3009. this.liveViewDataTimer = setInterval(() => {
  3010. if (this.liveId) {
  3011. this.getliveViewData()
  3012. }
  3013. }, 20000)
  3014. },
  3015. goShop(productId, goodsId) {
  3016. if (!this.liveId) return
  3017. uni.navigateTo({
  3018. url: '/pages_shopping/live/goods?productId=' + productId + '&liveId=' + this.liveId +
  3019. '&goodsId=' + goodsId + '&storeId=' + this.storeId
  3020. })
  3021. },
  3022. async queryCollect() {
  3023. this.loadingProducts = true
  3024. if (!this.liveId) return
  3025. if (this.inputInfo == null) this.inputInfo = ''
  3026. uni.showLoading({
  3027. title: '加载中'
  3028. })
  3029. try {
  3030. const res = await liveStore(this.liveId, this.inputInfo)
  3031. uni.hideLoading()
  3032. this.shopping = true
  3033. if (res.code === 200) {
  3034. this.products = Array.isArray(res.data) ? res.data : []
  3035. }
  3036. } catch (error) {
  3037. console.error('获取小黄车商品失败:', error)
  3038. } finally {
  3039. this.loadingProducts = false
  3040. }
  3041. },
  3042. initTime() {
  3043. const now = new Date()
  3044. this.timestamp = now.getTime()
  3045. },
  3046. showGift() {
  3047. this.isShowGift = true
  3048. },
  3049. clearChatInput() {
  3050. this.$refs.chatInput.clearInput()
  3051. },
  3052. openCart() {
  3053. this.queryCollect()
  3054. },
  3055. closeGift() {
  3056. this.isShowGift = false
  3057. },
  3058. closeShop() {
  3059. this.shopping = false
  3060. },
  3061. closeMore() {
  3062. this.isMore = false
  3063. },
  3064. closeWin() {
  3065. this.winning = false
  3066. },
  3067. closeWebSocket(isManual = true) {
  3068. if (!this.socket || !this.isSocketOpen) {
  3069. console.warn('WebSocket 任务不存在或未打开,无需关闭')
  3070. return
  3071. }
  3072. console.log(`WebSocket连接关闭 - ${isManual ? '手动' : '自动'}`)
  3073. this.isManualClose = isManual
  3074. this.cleanupAllResources()
  3075. try {
  3076. const socketToClose = this.socket
  3077. this.socket = null
  3078. this.isSocketOpen = false
  3079. this.isConnecting = false
  3080. socketToClose.close({
  3081. code: 1000,
  3082. reason: isManual ? '主动关闭' : '异常关闭'
  3083. })
  3084. console.log('WebSocket连接已发起关闭')
  3085. } catch (err) {
  3086. console.error('关闭WebSocket失败:', err)
  3087. this.socket = null
  3088. this.isSocketOpen = false
  3089. this.isConnecting = false
  3090. }
  3091. },
  3092. cleanupAllResources() {
  3093. this.stopHeartBeat()
  3094. if (this.pingTimeoutTimer) {
  3095. clearTimeout(this.pingTimeoutTimer)
  3096. this.pingTimeoutTimer = null
  3097. }
  3098. if (this.networkStatusTimer) {
  3099. clearTimeout(this.networkStatusTimer)
  3100. this.networkStatusTimer = null
  3101. }
  3102. this.resetReconnectState()
  3103. this.heartBeatRetryCount = 0
  3104. this.lastHeartBeatTime = 0
  3105. this.adaptiveHeartBeatInterval = this.heartBeatInterval
  3106. },
  3107. startHeartBeat() {
  3108. this.stopHeartBeat()
  3109. this.heartBeatTimer = setInterval(() => {
  3110. this.sendHeartBeat()
  3111. }, this.adaptiveHeartBeatInterval)
  3112. },
  3113. initSocket() {
  3114. if (this.isConnecting) {
  3115. console.log('WebSocket正在连接中,跳过重复连接')
  3116. return
  3117. }
  3118. if (!this.isNetworkAvailable) {
  3119. console.warn('网络不可用,延迟WebSocket连接')
  3120. if (!this.networkRetryTimer) {
  3121. this.networkRetryTimer = setTimeout(() => {
  3122. this.networkRetryTimer = null
  3123. this.initSocket()
  3124. }, 3000)
  3125. }
  3126. return
  3127. }
  3128. if (this.socket && this.socket.readyState === 1) {
  3129. console.log('WebSocket连接已存在且正常,无需重新连接')
  3130. this.reconnectCount = 0
  3131. return
  3132. }
  3133. if (this.socket && (this.socket.readyState === 0 || this.socket.readyState === 1)) {
  3134. console.log('关闭现有WebSocket连接,创建新连接')
  3135. this.closeWebSocket(false)
  3136. setTimeout(() => {
  3137. this.createWebSocketConnection()
  3138. }, 100)
  3139. return
  3140. }
  3141. this.createWebSocketConnection()
  3142. },
  3143. createWebSocketConnection() {
  3144. if (!this.liveId) {
  3145. console.error('缺失直播间ID,无法初始化WebSocket')
  3146. return
  3147. }
  3148. if (!this.userData || !this.userData.userId) {
  3149. console.error('用户信息缺失,无法初始化WebSocket')
  3150. return
  3151. }
  3152. this.isConnecting = true
  3153. this.isSocketOpen = false
  3154. this.connectionStartTime = Date.now()
  3155. this.resetReconnectState()
  3156. setTimeout(() => {
  3157. this.getliveUserInit(false)
  3158. }, 200)
  3159. const now = new Date()
  3160. this.timestamp = now.getTime()
  3161. const signature = CryptoJS.HmacSHA256(
  3162. `${this.liveId}${this.userData.userId}${this.userType}${this.timestamp}`, this.timestamp.toString()
  3163. ).toString(CryptoJS.enc.Hex)
  3164. try {
  3165. const baseWsUrl = 'wss://im.fhhx.runtzh.com/ws/app/webSocket'
  3166. let wsUrl =
  3167. `${baseWsUrl}?userId=${this.userData.userId}&liveId=${this.liveId}&userType=${this.userType}&timestamp=${this.timestamp}&signature=${signature}`
  3168. if (this.qrFrom) {
  3169. wsUrl += this.qrFrom
  3170. }
  3171. console.log('qxj wsUrl', wsUrl)
  3172. const socketTask = uni.connectSocket({
  3173. url: wsUrl,
  3174. success: () => {
  3175. console.log('WebSocket连接请求发送成功')
  3176. },
  3177. fail: (err) => {
  3178. console.error('WebSocket连接请求失败:', err)
  3179. this.isConnecting = false
  3180. this.handleConnectionError('连接请求失败', err)
  3181. }
  3182. })
  3183. socketTask.onOpen((res) => {
  3184. console.log('WebSocket连接已打开')
  3185. this.socket = socketTask
  3186. this.isConnecting = false
  3187. this.isSocketOpen = true
  3188. if (this.connectionStartTime > 0) {
  3189. this.connectionLatency = Date.now() - this.connectionStartTime
  3190. console.log(`WebSocket连接延迟: ${this.connectionLatency}ms`)
  3191. }
  3192. this.reconnectCount = 0
  3193. this.resetReconnectState()
  3194. this.heartBeatRetryCount = 0
  3195. this.shownEntryUsers.clear()
  3196. if (this.reconnectCount === 0) {
  3197. console.log('WebSocket连接建立成功')
  3198. } else {
  3199. console.log(`WebSocket重连成功(第${this.reconnectCount}次尝试)`)
  3200. }
  3201. this.startHeartBeat()
  3202. })
  3203. socketTask.onMessage((res) => {
  3204. this.messageCount++
  3205. try {
  3206. const data = JSON.parse(res.data)
  3207. if (!!data.data && data.data.cmd === 'heartbeat') {
  3208. if (this.pingTimeoutTimer) {
  3209. clearTimeout(this.pingTimeoutTimer)
  3210. this.pingTimeoutTimer = null
  3211. }
  3212. this.heartBeatRetryCount = 0
  3213. this.adjustHeartBeatInterval(true)
  3214. return
  3215. }
  3216. this.handleSocketMessage(res)
  3217. } catch (err) {
  3218. console.error('消息解析异常:', err)
  3219. this.errorCount++
  3220. }
  3221. })
  3222. socketTask.onError((err) => {
  3223. console.error('WebSocket连接错误:', err)
  3224. this.errorCount++
  3225. this.isSocketOpen = false
  3226. this.isConnecting = false
  3227. this.stopHeartBeat()
  3228. this.handleConnectionError('连接错误', err)
  3229. })
  3230. socketTask.onClose((res) => {
  3231. console.log('WebSocket连接关闭:', res)
  3232. this.isSocketOpen = false
  3233. this.isConnecting = false
  3234. this.stopHeartBeat()
  3235. if (!this.isManualClose) {
  3236. if (res.code === 1000) {
  3237. console.log('WebSocket正常关闭,不进行重连')
  3238. } else {
  3239. console.warn(`WebSocket异常关闭 (code: ${res.code}, reason: ${res.reason})`)
  3240. this.handleReconnect()
  3241. }
  3242. } else {
  3243. console.log('WebSocket手动关闭,不进行重连')
  3244. }
  3245. })
  3246. } catch (e) {
  3247. console.error('创建WebSocket异常:', e)
  3248. this.handleReconnect()
  3249. }
  3250. },
  3251. handleTime(time, duration) {
  3252. let timeStamp
  3253. if (typeof time === 'number' && time > 0 && time < 9999999999999) {
  3254. timeStamp = time
  3255. } else if (typeof time === 'string' && time.trim() !== '') {
  3256. const match = time.match(/^(\w{3}) (\w{3}) (\d{1,2}) (\d{1,2}):(\d{2}):(\d{2}) CST (\d{4})$/)
  3257. if (match) {
  3258. const [, day, month, date, hours, minutes, seconds, year] = match
  3259. const monthMap = {
  3260. 'Jan': 0,
  3261. 'Feb': 1,
  3262. 'Mar': 2,
  3263. 'Apr': 3,
  3264. 'May': 4,
  3265. 'Jun': 5,
  3266. 'Jul': 6,
  3267. 'Aug': 7,
  3268. 'Sep': 8,
  3269. 'Oct': 9,
  3270. 'Nov': 10,
  3271. 'Dec': 11
  3272. }
  3273. const jsDate = new Date(
  3274. parseInt(year),
  3275. monthMap[month],
  3276. parseInt(date),
  3277. parseInt(hours),
  3278. parseInt(minutes),
  3279. parseInt(seconds)
  3280. )
  3281. timeStamp = jsDate.getTime()
  3282. } else {
  3283. const date = new Date(time)
  3284. if (!isNaN(date.getTime())) {
  3285. timeStamp = date.getTime()
  3286. } else {
  3287. console.error('无效的日期格式:', time)
  3288. return false
  3289. }
  3290. }
  3291. } else {
  3292. console.error('time参数必须是有效的时间戳(数字)或日期字符串')
  3293. return false
  3294. }
  3295. const targetTimestamp = timeStamp + duration * 60 * 1000
  3296. const currentTimestamp = Date.now()
  3297. const timeDiffMs = targetTimestamp - currentTimestamp
  3298. if (timeDiffMs <= 0) {
  3299. return false
  3300. }
  3301. const hours = Math.floor(timeDiffMs / (1000 * 60 * 60))
  3302. const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60))
  3303. const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000)
  3304. const formatNum = (num) => num.toString().padStart(2, '0')
  3305. return {
  3306. hours: formatNum(hours),
  3307. minutes: formatNum(minutes),
  3308. seconds: formatNum(seconds)
  3309. }
  3310. },
  3311. addToTalkList(message) {
  3312. const MAX_TALK_ITEMS = 30
  3313. if (!Array.isArray(this.talklist)) {
  3314. this.talklist = []
  3315. }
  3316. const wasAtLimit = this.talklist.length >= MAX_TALK_ITEMS
  3317. const isMyMessage = message.userId === this.userData.userId
  3318. try {
  3319. message.uniqueId = ++this.messageIdCounter
  3320. let msgdata = {}
  3321. try {
  3322. msgdata = JSON.parse(message.data)
  3323. } catch (e) {
  3324. console.warn('JSON解析失败:', e)
  3325. msgdata = {}
  3326. }
  3327. message.msgId = msgdata.msgId || Date.now()
  3328. this.talklist.push(message)
  3329. } catch (error) {
  3330. console.error('处理消息时出错:', error)
  3331. }
  3332. if (this.talklist.length > MAX_TALK_ITEMS) {
  3333. const removeCount = this.talklist.length - MAX_TALK_ITEMS
  3334. this.talklist.splice(0, removeCount)
  3335. }
  3336. this.$forceUpdate()
  3337. this.$nextTick(() => {
  3338. this.forceScrollToBottomOnSend()
  3339. })
  3340. },
  3341. async handleSocketMessage(message) {
  3342. try {
  3343. let data = JSON.parse(message.data)
  3344. const socketMessage = data.data
  3345. if (data.code == 200) {
  3346. const messageData = {
  3347. ...socketMessage,
  3348. cmd: socketMessage.cmd || '',
  3349. ts: Date.now()
  3350. }
  3351. if (socketMessage.cmd == 'sendMsg') {
  3352. if (!this.isSocketAvailable()) {
  3353. uni.showToast({
  3354. title: '连接已断开,正在重试...',
  3355. icon: 'none'
  3356. })
  3357. this.handleReconnect()
  3358. return
  3359. }
  3360. this.addToTalkList(messageData)
  3361. } else if (socketMessage.cmd == 'red') {
  3362. const redData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
  3363. this.redInfo = redData || {}
  3364. this.isShowRed = socketMessage.status === 1
  3365. if (this.isShowRed) {
  3366. this.redTimer = setInterval(() => {
  3367. const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo
  3368. .duration)
  3369. if (!redCountdown) {
  3370. this.isShowRed = false
  3371. clearInterval(this.redTimer)
  3372. }
  3373. }, 1000)
  3374. }
  3375. } else if (socketMessage.cmd == 'goods') {
  3376. const goodsData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
  3377. this.goodsCard = goodsData || {}
  3378. this.isShowGoods = socketMessage.status == 1
  3379. } else if (socketMessage.cmd == 'coupon') {
  3380. const couponData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
  3381. this.couponInfo = couponData || {}
  3382. this.isShowCoupon = socketMessage.status === 1
  3383. } else if (socketMessage.cmd == 'likeDetail') {
  3384. this.liveViewData.like = socketMessage.data
  3385. } else if (socketMessage.cmd == 'lottery') {
  3386. const lotteryData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
  3387. this.lotteryInfo = lotteryData || {}
  3388. this.isShowLottery = socketMessage.status === 1
  3389. if (socketMessage.status != 1) {
  3390. this.isShowLotteryPop = false
  3391. }
  3392. clearTimeout(this.lotteryTimer)
  3393. if (this.isShowLottery) {
  3394. this.lotteryTimer = setInterval(() => {
  3395. this.countdown = this.handleTime(this.lotteryInfo.updateTime, this
  3396. .lotteryInfo.duration)
  3397. if (!this.countdown) {
  3398. console.log('倒计时', this.countdown)
  3399. this.isShowLottery = false
  3400. this.isShowLotteryPop = false
  3401. clearInterval(this.lotteryTimer)
  3402. }
  3403. }, 1000)
  3404. } else {
  3405. this.isShowLottery = false
  3406. }
  3407. } else if (socketMessage.cmd == 'deleteMsg') {
  3408. const index = this.talklist.findIndex(item => item.msgId == socketMessage.msg)
  3409. if (index !== -1) {
  3410. this.talklist.splice(index, 1)
  3411. }
  3412. } else if (socketMessage.cmd == 'globalVisible') {} else if (socketMessage.cmd ==
  3413. 'singleVisible') {} else if (socketMessage.cmd == 'entry') {
  3414. try {
  3415. //if (!this.liveUserCalled) {
  3416. await this.getliveUserInit(false)
  3417. this.liveUserCalled = true;
  3418. //}
  3419. const userIdToEntry = socketMessage.userId
  3420. const existingIndex = this.liveViewersData.findIndex((item) => item.userId ===
  3421. userIdToEntry);
  3422. if (existingIndex === -1) {
  3423. const liveViewers = {
  3424. userId: socketMessage.userId,
  3425. nickName: socketMessage.nickName,
  3426. avatar: socketMessage.avatar
  3427. }
  3428. this.liveViewersData.push(liveViewers)
  3429. this.liveUserTotal++
  3430. }
  3431. const userData = JSON.parse(socketMessage.data || '{}')
  3432. const userId = userData.userId || socketMessage.userId
  3433. if (!userId) return
  3434. if (!this.shownEntryUsers.has(userId)) {
  3435. this.inAndOut = socketMessage;
  3436. this.showWelcomeMessage = true;
  3437. this.shownEntryUsers.add(userId);
  3438. if (this.welcomeTimer) clearTimeout(this.welcomeTimer)
  3439. this.welcomeTimer = setTimeout(() => {
  3440. this.showWelcomeMessage = false
  3441. }, 3000)
  3442. }
  3443. } catch (err) {
  3444. console.error('解析entry用户数据失败:', err)
  3445. }
  3446. } else if (socketMessage.cmd == 'out') {
  3447. if (this.liveUserTotal > 0) {
  3448. const userIdToRemove = socketMessage.userId
  3449. const index = this.liveViewersData.findIndex((item) => item.userId === userIdToRemove)
  3450. if (index !== -1) {
  3451. this.liveViewersData.splice(index, 1)
  3452. this.liveUserTotal--
  3453. }
  3454. }
  3455. this.inAndOut = socketMessage
  3456. this.showWelcomeMessage = true
  3457. if (this.welcomeTimer) clearTimeout(this.welcomeTimer)
  3458. this.welcomeTimer = setTimeout(() => {
  3459. this.showWelcomeMessage = false
  3460. }, 3000)
  3461. } else if (socketMessage.cmd == 'sendTopMsg') {
  3462. clearInterval(this.noticeTimer)
  3463. console.log('公告消息>>>>', socketMessage)
  3464. const noticeData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
  3465. this.notice = noticeData || {}
  3466. this.isShowNotice = true
  3467. if (this.isShowNotice) {
  3468. this.noticeTimer = setInterval(() => {
  3469. const noticeCountdown = this.handleTime(this.notice.endTime, 0)
  3470. if (!noticeCountdown) {
  3471. this.isShowNotice = false
  3472. clearInterval(this.noticeTimer)
  3473. }
  3474. }, 1000)
  3475. }
  3476. } else if (socketMessage.cmd == 'live_start' || socketMessage.cmd == 'live_end') {
  3477. if (this.liveStartTimer) {
  3478. clearInterval(this.liveStartTimer)
  3479. this.liveStartTimer = null
  3480. }
  3481. if (this.redTimer) {
  3482. clearInterval(this.redTimer)
  3483. this.redTimer = null
  3484. }
  3485. await this.getliving(this.liveId)
  3486. } else if (socketMessage.cmd == 'Integral') {
  3487. this.integral = {
  3488. msg: socketMessage.msg,
  3489. status: true
  3490. }
  3491. } else if (socketMessage.cmd == 'LotteryDetail') {
  3492. try {
  3493. this.prizeInfo = Array.isArray(JSON.parse(socketMessage.data || '[]')) ? JSON.parse(
  3494. socketMessage.data || '[]') : []
  3495. } catch (err) {
  3496. console.error('解析抽奖结果失败:', err)
  3497. this.prizeInfo = []
  3498. }
  3499. this.isShowPrize = true
  3500. this.isShowLottery = false
  3501. this.isShowLotteryPop = false
  3502. } else if (socketMessage.cmd == 'blockUser') {
  3503. uni.removeStorage({
  3504. key: 'AppToken',
  3505. success: () => {
  3506. uni.reLaunch({
  3507. url: '/pages/auth/login'
  3508. })
  3509. }
  3510. })
  3511. }
  3512. } else {
  3513. uni.showToast({
  3514. title: data.msg,
  3515. icon: 'none'
  3516. })
  3517. }
  3518. } catch (error) {
  3519. console.error('Socket消息处理失败:', error)
  3520. }
  3521. },
  3522. onBarrage(item) {
  3523. if (this.isSending) return
  3524. this.isSending = true
  3525. setTimeout(() => {
  3526. this.isSending = false
  3527. }, 800)
  3528. const text = (item || '').trim()
  3529. if (!text) {
  3530. uni.showToast({
  3531. title: '不能发送空消息',
  3532. icon: 'none'
  3533. })
  3534. return
  3535. }
  3536. if (!this.isSocketAvailable()) {
  3537. if (retries > 0) {
  3538. uni.showToast({
  3539. title: `连接不稳定,正在重试(${retries}次)...`,
  3540. icon: 'none'
  3541. })
  3542. setTimeout(() => this.sendMsg(retries - 1), 500)
  3543. } else {
  3544. uni.showToast({
  3545. title: '连接已断开,发送失败',
  3546. icon: 'none'
  3547. })
  3548. }
  3549. return
  3550. }
  3551. const liveId = this.liveId
  3552. const data = {
  3553. liveId,
  3554. userId: this.userData.userId,
  3555. userType: 0,
  3556. cmd: 'sendMsg',
  3557. msg: text,
  3558. nickName: this.userData.nickname || '未命名',
  3559. avatar: this.userData.avatar || '/static/images/avatar.png'
  3560. }
  3561. try {
  3562. this.socket.send({
  3563. data: JSON.stringify(data),
  3564. success: () => {
  3565. this.forceScrollToBottomOnSend()
  3566. },
  3567. fail: (err) => {
  3568. console.error('消息发送失败:', err)
  3569. if (retries > 0) {
  3570. uni.showToast({
  3571. title: `发送失败,正在重试(${retries}次)`,
  3572. icon: 'none'
  3573. })
  3574. setTimeout(() => this.sendMsg(retries - 1), 500)
  3575. } else {
  3576. uni.showToast({
  3577. title: '发送失败,请稍后再试',
  3578. icon: 'none'
  3579. })
  3580. }
  3581. }
  3582. })
  3583. } catch (err) {
  3584. console.error('发送消息异常:', err)
  3585. if (retries > 0) {
  3586. setTimeout(() => this.sendMsg(retries - 1), 500)
  3587. } else {
  3588. uni.showToast({
  3589. title: '发送失败,请稍后再试',
  3590. icon: 'none'
  3591. })
  3592. }
  3593. }
  3594. },
  3595. sendMsg(retries = 1) {
  3596. if (this.isSending) return
  3597. this.isSending = true
  3598. setTimeout(() => {
  3599. this.isSending = false
  3600. }, 800)
  3601. const text = (this.value || '').trim()
  3602. if (!text) {
  3603. uni.showToast({
  3604. title: '不能发送空消息',
  3605. icon: 'none'
  3606. })
  3607. return
  3608. }
  3609. if (!this.isSocketAvailable()) {
  3610. if (retries > 0) {
  3611. uni.showToast({
  3612. title: `连接不稳定,正在重试(${retries}次)...`,
  3613. icon: 'none'
  3614. })
  3615. setTimeout(() => this.sendMsg(retries - 1), 500)
  3616. } else {
  3617. uni.showToast({
  3618. title: '连接已断开,发送失败',
  3619. icon: 'none'
  3620. })
  3621. this.value = text
  3622. }
  3623. return
  3624. }
  3625. const liveId = this.liveId
  3626. this.value = ''
  3627. const data = {
  3628. liveId,
  3629. userId: this.userData.userId,
  3630. userType: 0,
  3631. cmd: 'sendMsg',
  3632. msg: text,
  3633. nickName: this.userData.nickname || '未命名',
  3634. avatar: this.userData.avatar || '/static/images/avatar.png'
  3635. }
  3636. try {
  3637. this.socket.send({
  3638. data: JSON.stringify(data),
  3639. success: () => {
  3640. this.value = ''
  3641. this.forceScrollToBottomOnSend()
  3642. },
  3643. fail: (err) => {
  3644. console.error('消息发送失败:', err)
  3645. if (retries > 0) {
  3646. uni.showToast({
  3647. title: `发送失败,正在重试(${retries}次)`,
  3648. icon: 'none'
  3649. })
  3650. setTimeout(() => this.sendMsg(retries - 1), 500)
  3651. } else {
  3652. uni.showToast({
  3653. title: '发送失败,请稍后再试',
  3654. icon: 'none'
  3655. })
  3656. this.value = text
  3657. }
  3658. }
  3659. })
  3660. } catch (err) {
  3661. console.error('发送消息异常:', err)
  3662. if (retries > 0) {
  3663. setTimeout(() => this.sendMsg(retries - 1), 500)
  3664. } else {
  3665. uni.showToast({
  3666. title: '发送失败,请稍后再试',
  3667. icon: 'none'
  3668. })
  3669. this.value = text
  3670. }
  3671. }
  3672. }
  3673. }
  3674. }
  3675. </script>
  3676. <style scoped lang="scss">
  3677. // 弹窗
  3678. .custom-toast {
  3679. position: fixed;
  3680. top: 50%;
  3681. left: 50%;
  3682. transform: translate(-50%, -50%);
  3683. z-index: 999999;
  3684. }
  3685. .toast-content {
  3686. background-color: rgba(0, 0, 0, 0.7);
  3687. color: white;
  3688. padding: 20rpx 40rpx;
  3689. border-radius: 16rpx;
  3690. max-width: 80vw;
  3691. text-align: center;
  3692. line-height: 1.5;
  3693. font-weight: 500;
  3694. font-size: 32rpx;
  3695. }
  3696. .swiper-wrapper {
  3697. position: relative;
  3698. width: 100%;
  3699. height: 100vh;
  3700. overflow: hidden;
  3701. background-color: #000000;
  3702. .live-bg {
  3703. position: absolute;
  3704. top: 0;
  3705. width: 100%;
  3706. height: 100%;
  3707. }
  3708. .container {
  3709. width: 100%;
  3710. height: 100%;
  3711. position: relative;
  3712. transition: opacity 0.3s ease;
  3713. transform: translateZ(0);
  3714. will-change: opacity;
  3715. &.fullscreen {
  3716. .content-top,
  3717. .side-group,
  3718. .chat-area-container,
  3719. .shop-popup,
  3720. .lottery-popup,
  3721. .more-popup,
  3722. .shop-card,
  3723. .gift-popup,
  3724. .coupon-pop,
  3725. .prize-popup,
  3726. .winning-popup,
  3727. .integral-popup,
  3728. .red-card-popup,
  3729. .viewer-popup {
  3730. display: none !important;
  3731. visibility: hidden !important;
  3732. opacity: 0 !important;
  3733. pointer-events: none !important;
  3734. }
  3735. .live-video {
  3736. position: fixed !important;
  3737. top: 0 !important;
  3738. left: 0 !important;
  3739. width: 100vw !important;
  3740. height: 100vh !important;
  3741. z-index: 99999 !important;
  3742. background: #000 !important;
  3743. }
  3744. }
  3745. }
  3746. }
  3747. .content {
  3748. position: relative;
  3749. z-index: 2;
  3750. height: 100%;
  3751. width: 100%;
  3752. top: 0;
  3753. left: 0;
  3754. display: flex;
  3755. flex-direction: column;
  3756. justify-content: space-between;
  3757. .progress-countdown {
  3758. margin-top: 24rpx;
  3759. z-index: 9000;
  3760. width: 180rpx;
  3761. display: flex;
  3762. flex-direction: column;
  3763. align-items: center;
  3764. background: rgba(0, 0, 0, 0.3);
  3765. border-radius: 16rpx;
  3766. padding: 16rpx;
  3767. flex-direction: column;
  3768. &.progress-vertical {
  3769. top: 15%;
  3770. left: 24rpx;
  3771. }
  3772. .title {
  3773. width: 148rpx;
  3774. height: 28rpx;
  3775. }
  3776. .progress-bar-bg {
  3777. width: 148rpx;
  3778. height: 8rpx;
  3779. margin-top: 16rpx;
  3780. background: #ffffff;
  3781. border-radius: 6rpx;
  3782. overflow: hidden;
  3783. margin-bottom: 16rpx;
  3784. .progress-bar-fill {
  3785. height: 100%;
  3786. background: #face15;
  3787. border-radius: 6rpx;
  3788. transition: width 1s linear;
  3789. }
  3790. }
  3791. .progress-text {
  3792. color: #fff;
  3793. font-size: 20rpx;
  3794. }
  3795. }
  3796. }
  3797. .content-top {
  3798. width: 100%;
  3799. display: flex;
  3800. justify-content: space-between;
  3801. padding: 0 24rpx;
  3802. box-sizing: border-box;
  3803. position: fixed;
  3804. margin-top: 88rpx;
  3805. top: 0;
  3806. z-index: 5;
  3807. will-change: transform;
  3808. .x-f {
  3809. display: flex;
  3810. align-items: center;
  3811. .avatar-container {
  3812. padding: 6rpx 8rpx;
  3813. height: 64rpx;
  3814. background: rgba(0, 0, 0, 0.5);
  3815. border-radius: 32rpx;
  3816. display: flex;
  3817. align-items: center;
  3818. }
  3819. }
  3820. .end {
  3821. display: flex;
  3822. flex-direction: column;
  3823. align-items: flex-end;
  3824. .viewer-preview {
  3825. margin-top: 120rpx;
  3826. display: flex;
  3827. align-items: center;
  3828. .sum {
  3829. width: 80rpx;
  3830. height: 52rpx;
  3831. background: rgba(0, 0, 0, 0.5);
  3832. border-radius: 26rpx;
  3833. font-size: 30rpx;
  3834. color: #ffffff;
  3835. text-align: center;
  3836. line-height: 52rpx;
  3837. }
  3838. }
  3839. .complaint-box {
  3840. width: 140rpx;
  3841. margin-top: 20rpx;
  3842. display: flex;
  3843. align-items: center;
  3844. justify-content: center;
  3845. background: rgba(0, 0, 0, 0.3);
  3846. padding: 16rpx 0;
  3847. color: #fff;
  3848. border-radius: 28rpx;
  3849. z-index: 999;
  3850. }
  3851. }
  3852. }
  3853. .side-group {
  3854. position: absolute;
  3855. top: 52%;
  3856. right: 24rpx;
  3857. z-index: 1000;
  3858. display: flex;
  3859. flex-direction: column;
  3860. align-items: center;
  3861. will-change: transform;
  3862. &.top2 {
  3863. top: 65%;
  3864. }
  3865. &.top3 {
  3866. top: 55%;
  3867. }
  3868. .side-item {
  3869. font-weight: 500;
  3870. font-size: 22rpx;
  3871. color: #ffffff;
  3872. margin-bottom: 26rpx;
  3873. text-align: center;
  3874. .button-reset {
  3875. background-color: transparent !important;
  3876. padding: 0 !important;
  3877. line-height: 1 !important;
  3878. margin: 0 !important;
  3879. width: auto !important;
  3880. font-weight: 500 !important;
  3881. border-radius: none !important;
  3882. &::after {
  3883. border: none !important;
  3884. padding: 0 !important;
  3885. margin: 0 !important;
  3886. }
  3887. }
  3888. .image {
  3889. width: 72rpx;
  3890. height: auto;
  3891. }
  3892. .txt {
  3893. font-size: 30rpx;
  3894. margin-top: 4rpx;
  3895. }
  3896. }
  3897. }
  3898. .chat-area-container {
  3899. position: fixed;
  3900. width: 100%;
  3901. bottom: 0;
  3902. z-index: 100;
  3903. transform: translateZ(0);
  3904. will-change: transform;
  3905. backface-visibility: hidden;
  3906. &.chat-area-focused {
  3907. transform: translateY(calc(-1 * var(--keyboard-height, 0rpx))) translateZ(0);
  3908. // z-index: 1000;
  3909. }
  3910. }
  3911. .chat-content {
  3912. height: 36vh;
  3913. overflow: hidden;
  3914. padding-left: 20rpx;
  3915. transform: translateZ(0);
  3916. will-change: height;
  3917. display: flex;
  3918. flex-direction: column;
  3919. &.chat-content-preview {
  3920. height: 20vh;
  3921. }
  3922. &.chat-content-focused {
  3923. height: 64rpx;
  3924. }
  3925. }
  3926. .shop-prompt {
  3927. width: auto;
  3928. display: inline-flex !important;
  3929. max-width: max-content;
  3930. padding: 6rpx 20rpx;
  3931. background: rgba(230, 154, 34, 0.7);
  3932. border-radius: 24rpx;
  3933. z-index: 9;
  3934. font-weight: 500;
  3935. color: #ffffff;
  3936. transition: opacity 0.3s ease;
  3937. margin-bottom: 20rpx;
  3938. }
  3939. .welcome-message {
  3940. width: 100%;
  3941. color: white;
  3942. border-radius: 20rpx;
  3943. z-index: 10;
  3944. transition: opacity 0.3s ease;
  3945. }
  3946. .notice-message {
  3947. max-width: 80%;
  3948. padding: 24rpx;
  3949. background: linear-gradient(135deg,
  3950. rgba(255, 220, 41, 0.8) 0%,
  3951. rgba(218, 187, 30, 0.4) 100%);
  3952. margin-bottom: 10rpx;
  3953. border-radius: 20rpx;
  3954. color: #ffffff;
  3955. }
  3956. .scrolly {
  3957. width: calc(100% - 20rpx);
  3958. -webkit-overflow-scrolling: touch;
  3959. }
  3960. .list {
  3961. width: 80%;
  3962. margin-bottom: 20rpx;
  3963. animation: simpleFade 0.2s;
  3964. .talk-list {
  3965. will-change: transform;
  3966. contain: layout style paint;
  3967. backface-visibility: hidden;
  3968. transform: translateZ(0);
  3969. max-width: 100%;
  3970. border-radius: 30rpx;
  3971. background: rgba(0, 0, 0, 0.3);
  3972. padding: 10rpx 30rpx;
  3973. .talk-item {
  3974. line-height: 1.4;
  3975. word-break: break-all;
  3976. word-wrap: break-word;
  3977. overflow-wrap: break-word;
  3978. .nickname {
  3979. color: #ffda73;
  3980. }
  3981. .message {
  3982. color: #ffffff;
  3983. }
  3984. }
  3985. }
  3986. }
  3987. .barrage {
  3988. background: rgba(0, 0, 0, 0.3);
  3989. padding: 12rpx 20rpx;
  3990. color: #fff;
  3991. margin: 30rpx 20rpx 0 20rpx;
  3992. border-radius: 30rpx;
  3993. white-space: nowrap;
  3994. }
  3995. .prize-card {
  3996. width: 504rpx;
  3997. padding: 40rpx 40rpx 30rpx;
  3998. box-sizing: border-box;
  3999. display: flex;
  4000. flex-direction: column;
  4001. border-radius: 20rpx;
  4002. align-items: center;
  4003. background: linear-gradient(180deg, #f7823f 0%, #ffd4be 27%, #ffffff 100%);
  4004. position: relative;
  4005. .nav-img {
  4006. width: 311rpx;
  4007. position: absolute;
  4008. top: -122rpx;
  4009. left: 50%;
  4010. transform: translateX(-50%);
  4011. }
  4012. .title {
  4013. color: #c32008;
  4014. font-size: 34rpx;
  4015. font-weight: 600;
  4016. margin: 20rpx 0 40rpx;
  4017. }
  4018. .prize-content {
  4019. width: 100%;
  4020. display: flex;
  4021. justify-content: space-between;
  4022. align-items: center;
  4023. font-size: 28rpx;
  4024. margin: 10rpx 0;
  4025. .txt {
  4026. font-weight: 600;
  4027. }
  4028. }
  4029. .tip {
  4030. font-size: 28rpx;
  4031. color: #414141;
  4032. margin: 40rpx 0;
  4033. }
  4034. .button {
  4035. width: 200rpx;
  4036. height: 70rpx;
  4037. line-height: 70rpx;
  4038. background: linear-gradient(180deg, #ff7c30 0%, #ff3a1e 100%);
  4039. border-radius: 28rpx;
  4040. font-weight: 500;
  4041. font-size: 32rpx;
  4042. color: #ffffff;
  4043. text-align: center;
  4044. }
  4045. }
  4046. .no-prize-card {
  4047. width: 504rpx;
  4048. padding: 40rpx 40rpx 30rpx;
  4049. box-sizing: border-box;
  4050. display: flex;
  4051. flex-direction: column;
  4052. border-radius: 20rpx;
  4053. align-items: center;
  4054. position: relative;
  4055. .img {
  4056. margin-top: 40rpx;
  4057. width: 300rpx;
  4058. height: 300rpx;
  4059. }
  4060. .tip {
  4061. font-size: 36rpx;
  4062. color: #414141;
  4063. margin: 40rpx 0;
  4064. }
  4065. .button {
  4066. width: 220rpx;
  4067. height: 80rpx;
  4068. line-height: 80rpx;
  4069. background: linear-gradient(180deg, #fdfbb8 0%, #b79243 100%);
  4070. border-radius: 28rpx;
  4071. font-weight: 500;
  4072. font-size: 32rpx;
  4073. color: #ffffff;
  4074. text-align: center;
  4075. }
  4076. }
  4077. .red-card {
  4078. width: 550rpx;
  4079. height: 636rpx;
  4080. position: relative;
  4081. .img {
  4082. position: absolute;
  4083. width: 100%;
  4084. height: 100%;
  4085. }
  4086. .red-content {
  4087. position: relative;
  4088. z-index: 5;
  4089. display: flex;
  4090. flex-direction: column;
  4091. align-items: center;
  4092. .title {
  4093. font-size: 36rpx;
  4094. color: #ff3a1e;
  4095. margin: 180rpx 0 90rpx;
  4096. }
  4097. .txt {
  4098. font-size: 28rpx;
  4099. color: #ffecc3;
  4100. margin: 80rpx 0 40rpx;
  4101. }
  4102. .button {
  4103. width: 392rpx;
  4104. height: 96rpx;
  4105. line-height: 96rpx;
  4106. background: linear-gradient(180deg, #fff4d5 0%, #ffe5b1 100%);
  4107. border-radius: 48rpx;
  4108. font-weight: 600;
  4109. font-size: 36rpx;
  4110. color: #c32008;
  4111. text-align: center;
  4112. }
  4113. }
  4114. }
  4115. .integral-box {
  4116. min-width: 400rpx;
  4117. max-width: 600rpx;
  4118. display: flex;
  4119. flex-direction: column;
  4120. align-items: center;
  4121. border-radius: 20rpx;
  4122. overflow: hidden;
  4123. .top {
  4124. width: 100%;
  4125. position: relative;
  4126. .title {
  4127. width: 100%;
  4128. font-weight: 600;
  4129. font-size: 40rpx;
  4130. color: #ffffff;
  4131. text-shadow: 0px 4rpx 8rpx rgba(255, 89, 2, 0.8);
  4132. position: absolute;
  4133. top: 50rpx;
  4134. text-align: center;
  4135. }
  4136. .photo {
  4137. width: 100%;
  4138. }
  4139. }
  4140. .item {
  4141. padding: 20rpx;
  4142. .title {
  4143. font-weight: 500;
  4144. font-size: 32rpx;
  4145. text-align: center;
  4146. }
  4147. .button {
  4148. font-size: 32rpx;
  4149. margin-top: 20rpx;
  4150. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  4151. color: #fff;
  4152. text-align: center;
  4153. padding: 18rpx 60rpx;
  4154. border-radius: 10rpx;
  4155. font-weight: 500;
  4156. }
  4157. }
  4158. }
  4159. .coupon-pop {
  4160. position: fixed;
  4161. bottom: 140rpx;
  4162. right: 100rpx;
  4163. z-index: 5;
  4164. border-radius: 20rpx;
  4165. width: 320rpx;
  4166. .coupon-block {
  4167. width: 100%;
  4168. position: relative;
  4169. .bg {
  4170. height: 452rpx;
  4171. width: 100%;
  4172. }
  4173. .nav {
  4174. position: absolute;
  4175. height: 120rpx;
  4176. top: -120rpx;
  4177. left: 0;
  4178. width: 100%;
  4179. z-index: 6;
  4180. }
  4181. .close {
  4182. position: absolute;
  4183. right: 10rpx;
  4184. top: 10rpx;
  4185. z-index: 99;
  4186. }
  4187. .item {
  4188. width: 100%;
  4189. position: absolute;
  4190. top: 20rpx;
  4191. display: flex;
  4192. flex-direction: column;
  4193. align-items: center;
  4194. color: #fff;
  4195. .title {
  4196. font-weight: 500;
  4197. font-size: 30rpx;
  4198. margin: 16rpx 0 12rpx;
  4199. }
  4200. .price {
  4201. font-size: 40rpx;
  4202. .bold {
  4203. font-size: 56rpx;
  4204. font-weight: 600;
  4205. }
  4206. }
  4207. .txt {
  4208. font-weight: 500;
  4209. font-size: 30rpx;
  4210. margin: 5rpx 0;
  4211. }
  4212. .button {
  4213. background: linear-gradient(270deg, #fffce1 0%, #ffeaaf 100%);
  4214. color: #ff0004;
  4215. text-align: center;
  4216. padding: 16rpx 0;
  4217. border-radius: 40rpx;
  4218. font-weight: 500;
  4219. font-size: 30rpx;
  4220. width: 70%;
  4221. margin-top: 26rpx;
  4222. }
  4223. }
  4224. }
  4225. }
  4226. .more-block {
  4227. border-radius: 20rpx 0 0 20rpx;
  4228. padding: 70rpx 30rpx;
  4229. display: flex;
  4230. justify-content: space-between;
  4231. .item {
  4232. text-align: center;
  4233. }
  4234. }
  4235. .integral-popup {
  4236. min-width: 400rpx;
  4237. max-width: 600rpx;
  4238. display: flex;
  4239. flex-direction: column;
  4240. align-items: center;
  4241. border-radius: 20rpx;
  4242. overflow: hidden;
  4243. .integral-header {
  4244. width: 100%;
  4245. position: relative;
  4246. .integral-title {
  4247. width: 100%;
  4248. font-weight: 600;
  4249. font-size: 40rpx;
  4250. color: #ffffff;
  4251. text-shadow: 0px 4rpx 8rpx rgba(255, 89, 2, 0.8);
  4252. position: absolute;
  4253. top: 50rpx;
  4254. text-align: center;
  4255. }
  4256. .integral-background-image {
  4257. width: 100%;
  4258. }
  4259. }
  4260. .integral-content {
  4261. padding: 20rpx;
  4262. .integral-message {
  4263. font-weight: 500;
  4264. font-size: 32rpx;
  4265. text-align: center;
  4266. }
  4267. .integral-confirm-button {
  4268. font-size: 32rpx;
  4269. margin-top: 20rpx;
  4270. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  4271. color: #fff;
  4272. text-align: center;
  4273. padding: 18rpx 60rpx;
  4274. border-radius: 10rpx;
  4275. font-weight: 500;
  4276. }
  4277. }
  4278. }
  4279. .gift {
  4280. padding: 32rpx 24rpx;
  4281. color: #ffffff;
  4282. .gift-top {
  4283. margin-bottom: 32rpx;
  4284. display: flex;
  4285. justify-content: space-between;
  4286. align-items: center;
  4287. .left {
  4288. font-weight: 600;
  4289. font-size: 28rpx;
  4290. .orange {
  4291. color: #f4a007;
  4292. }
  4293. }
  4294. }
  4295. .gift-block {
  4296. display: flex;
  4297. justify-content: space-between;
  4298. flex-wrap: wrap;
  4299. .item {
  4300. width: 162rpx;
  4301. height: 212rpx;
  4302. text-align: center;
  4303. margin-bottom: 20rpx;
  4304. border: 1rpx solid transparent;
  4305. .name {
  4306. font-size: 24rpx;
  4307. color: rgba(255, 255, 255, 0.8);
  4308. margin: 16rpx 0 12rpx;
  4309. }
  4310. .number {
  4311. font-size: 18rpx;
  4312. color: rgba(255, 255, 255, 0.4);
  4313. }
  4314. .button {
  4315. font-size: 24rpx;
  4316. width: 100%;
  4317. height: 56rpx;
  4318. line-height: 56rpx;
  4319. background: linear-gradient(270deg, #ff5701 0%, #ffb501 100%);
  4320. }
  4321. }
  4322. .active {
  4323. overflow: hidden;
  4324. background: #333333;
  4325. border-radius: 16rpx;
  4326. border: 1rpx solid rgba(255, 255, 255, 0.1);
  4327. .name {
  4328. margin: 4rpx 0 14rpx;
  4329. }
  4330. }
  4331. }
  4332. }
  4333. .view-box {
  4334. position: relative;
  4335. height: 40vh;
  4336. padding: 40rpx 0rpx;
  4337. box-sizing: border-box;
  4338. display: flex;
  4339. flex-direction: column;
  4340. .scroll-content {
  4341. flex: 1;
  4342. margin-top: 50rpx;
  4343. overflow-y: auto;
  4344. padding: 0 40rpx;
  4345. }
  4346. .bottom {
  4347. padding: 20rpx 40rpx;
  4348. position: absolute;
  4349. bottom: 0;
  4350. width: 100%;
  4351. box-shadow: 0rpx -4rpx 10rpx 0rpx rgba(195, 195, 195, 0.3);
  4352. background: #fff;
  4353. }
  4354. }
  4355. @keyframes simpleFade {
  4356. from {
  4357. opacity: 0;
  4358. }
  4359. to {
  4360. opacity: 1;
  4361. }
  4362. }
  4363. .skeleton-item {
  4364. display: flex;
  4365. padding: 20rpx;
  4366. background: #fff;
  4367. margin-bottom: 16rpx;
  4368. border-radius: 16rpx;
  4369. }
  4370. .skeleton-img {
  4371. width: 200rpx;
  4372. height: 200rpx;
  4373. background: #f0f0f0;
  4374. border-radius: 8rpx;
  4375. margin-right: 24rpx;
  4376. animation: pulse 1.5s ease-in-out infinite;
  4377. }
  4378. .skeleton-content {
  4379. flex: 1;
  4380. }
  4381. .skeleton-line {
  4382. height: 20rpx;
  4383. background: #f0f0f0;
  4384. margin-bottom: 16rpx;
  4385. border-radius: 4rpx;
  4386. animation: pulse 1.5s ease-in-out infinite;
  4387. &.short {
  4388. width: 60%;
  4389. }
  4390. &.medium {
  4391. width: 80%;
  4392. }
  4393. &.long {
  4394. width: 95%;
  4395. }
  4396. }
  4397. @keyframes pulse {
  4398. 0% {
  4399. opacity: 1;
  4400. }
  4401. 50% {
  4402. opacity: 0.5;
  4403. }
  4404. 100% {
  4405. opacity: 1;
  4406. }
  4407. }
  4408. .text-white {
  4409. color: #ffffff;
  4410. }
  4411. .text-xs {
  4412. font-size: 18rpx;
  4413. }
  4414. .text-sm {
  4415. font-size: 24rpx;
  4416. }
  4417. .w52,
  4418. .w72 {
  4419. display: flex;
  4420. align-items: center;
  4421. justify-content: center;
  4422. }
  4423. .w52.h52.mr4 {
  4424. border-radius: 26rpx;
  4425. }
  4426. .x-f {
  4427. display: flex;
  4428. align-items: center;
  4429. }
  4430. .align-center {
  4431. display: flex;
  4432. align-items: center;
  4433. }
  4434. .justify-start {
  4435. display: flex;
  4436. justify-content: flex-start;
  4437. }
  4438. .flex-1 {
  4439. flex: 1;
  4440. }
  4441. .column {
  4442. flex-direction: column;
  4443. }
  4444. .colorf {
  4445. color: #ffffff;
  4446. }
  4447. .orange {
  4448. color: #f4a007;
  4449. }
  4450. ::v-deep .u-icon--right {
  4451. justify-content: flex-end !important;
  4452. }
  4453. /* 微信昵称授权弹窗样式 */
  4454. .userlogo {
  4455. padding: 36rpx 40rpx;
  4456. color: #000000;
  4457. .mt42 {
  4458. margin-top: 42rpx;
  4459. }
  4460. .boxweixin {
  4461. width: 44rpx;
  4462. height: 44rpx;
  4463. border-radius: 50%;
  4464. text-align: center;
  4465. line-height: 34rpx;
  4466. color: #0a0;
  4467. }
  4468. .button-container {
  4469. position: relative;
  4470. margin: auto;
  4471. .hidden-input {
  4472. width: calc(100vw - 80rpx);
  4473. text-align: center;
  4474. height: 104rpx;
  4475. background: #07C160;
  4476. padding: 30rpx 0;
  4477. box-sizing: border-box;
  4478. border-radius: 12rpx;
  4479. font-size: 32rpx !important;
  4480. color: #FFFFFF !important;
  4481. /* 输入文字大小 */
  4482. }
  4483. /* 针对 placeholder 的样式 */
  4484. .hidden-input::placeholder {
  4485. font-size: 44rpx !important;
  4486. color: #FFFFFF !important;
  4487. }
  4488. /* 兼容微信小程序的 placeholder 样式 */
  4489. .hidden-input .placeholder {
  4490. font-size: 44rpx !important;
  4491. color: #FFFFFF !important;
  4492. }
  4493. }
  4494. .submitname {
  4495. height: 104rpx;
  4496. line-height: 104rpx;
  4497. background: #F2F2F2;
  4498. border-radius: 12rpx;
  4499. font-size: 32rpx;
  4500. color: #07C160;
  4501. margin-top: 32rpx;
  4502. text-align: center;
  4503. }
  4504. }
  4505. </style>