living-new.vue 125 KB

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