living.vue 123 KB

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