living.vue 146 KB

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