living.vue 139 KB

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