living.vue 136 KB

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