living_1.vue 120 KB

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