living.vue 140 KB

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