living.vue 137 KB

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