living.vue 132 KB

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