living.vue 115 KB

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