living.vue 132 KB

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