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