living.vue 132 KB

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