| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885 |
- <template>
- <view class="swiper-wrapper">
- <!-- 状态栏占位 -->
- <image src="https://fs-1323137866.cos.ap-chongqing.myqcloud.com/live_bg.jpg" class="live-bg"></image>
- <view class="container" :class="isFullscreen ? 'fullscreen ' : ''">
- <view class="content">
- <view style="position: fixed; top: 0; z-index: 5" class="content-top">
- <view class="">
- <view class="x-f">
- <image v-if="!scene" @click="goBack" class="w60 h64 mr6"
- src="/static/images/return3.png" />
- <view class="align-center"
- style="padding: 6rpx 8rpx; height: 64rpx; background: rgba(0,0,0,0.5); border-radius: 32rpx">
- <u-avatar :src="liveItem.liveImgUrl || '/static/images/avatar.png'"
- :size="32"></u-avatar>
- <view class="colorf ml10 mr6">
- <view>111{{ liveItem.liveName ? truncateString(liveItem.liveName, 8) : '未命名' }}</view>
- </view>
- </view>
- </view>
- <!-- 积分倒计时 -->
- <view class="progress-countdown" :class="liveItem.showType == 2 ? ' progress-vertical' : ''"
- :style="{ 'display': isFocus ? 'none' : '' }"
- v-if="countdownPercentage != 100 && liveItem.completionPointsEnabled && liveItem.status == 2 && !isPreview">
- <image class="title" src="/static/images/points_title.png"></image>
- <view class="progress-bar-bg">
- <view class="progress-bar-fill" :style="{ width: countdownPercentage + '%' }"></view>
- </view>
- <view class="progress-text">
- 倒计时{{ formattedCountdown.hours || '00' }}:{{ formattedCountdown.minutes || '00' }}:{{
- formattedCountdown.seconds ||'00' }}
- </view>
- </view>
- </view>
- <view class="end">
- <view v-if="Array.isArray(filteredViewers)" class="align-center"
- style="margin-top: 88rpx">
- <view v-for="(item, viewerIndex) in filteredViewers" :key="viewerIndex">
- <image v-if="item.avatar" class="w52 h52 mr4" style="border-radius: 26rpx"
- :src="item.avatar" />
- <view v-else class="w52 h52 mr4"
- :style="{ backgroundColor: getUserRandomColor(item.userId), borderRadius: '50%' }">
- <text class="text-white text-xs">{{ getNicknameInitial(item.nickName) }}</text>
- </view>
- </view>
- <view class="sum">{{ formattedWatchCount || 0 }}</view>
- </view>
- <view class="complaint-box" @click="navgetTo('/pages_shopping/live/complaintList')">
- <image class="image w32 h32 mr10" src="/static/images/complaint.png" mode="widthFix" />
- <view class="fs26">投诉</view>
- </view>
- </view>
- </view>
- <!-- 右边的side -->
- <view v-show="!isFocus" class="side-group" :class="{
- 'top2': (!isShowRed && !(isShowLottery && countdown)),
- 'top3': (isShowRed || (isShowLottery && countdown))
- }">
- <view class="side-item" @click="onRed()" v-if="isShowRed">
- <button class="button button-reset" style="height: 70rpx;">
- <image class="image" style="width: 72rpx;" src="/static/images/redbag.png"
- mode="widthFix" />
- </button>
- <view class="fs30">领红包</view>
- </view>
- <view class="side-item" @click="onLottery()" v-if="isShowLottery && countdown">
- <button class="button button-reset">
- <image class="image" src="/static/images/lottery.png" mode="widthFix" />
- </button>
- <view class="fs30">抽奖</view>
- </view>
- <view class="side-item" @click="onLike">
- <LikeButton :initialCount="100" :heartsPerClick="5" @like="onLike" />
- <view class="txt" style="font-size: 30rpx;">{{ formattedLikeCount || 0 }}</view>
- </view>
- <view class="side-item">
- <button open-type="share" class="button button-reset">
- <image class="image" src="/static/images/weixin1.png" mode="widthFix" />
- </button>
- <view class="txt" style="font-size: 30rpx;">分享</view>
- </view>
- </view>
- <!-- 直播 -->
- <LiveVideo class="live-video" ref="liveVideo" :isAgreement="isAgreement" :liveItem="liveItem"
- :hasSubscribed="hasSubscribed" :liveId="liveId" :userData="userData" @liveStart="handleLiveStart"
- @videoError="handleVideoError" @liveStateChange="handleLiveStateChange"
- @agreementClick="handleAgreement" @fullscreen-change="handleFullscreenChange" />
- <!-- 底部聊天区域 -->
- <view class="chat-area-container" :class="{ 'chat-area-focused': isFocus }"
- :style="{ '--keyboard-height': keyboardHeight + 'rpx' }">
- <view class="mt20 chat-content"
- :class="{ 'chat-content-focused': isFocus, 'chat-content-preview': liveItem.status == 1 }">
- <view v-if="showPurchasePrompt && orderUser && orderUser.count && liveItem.status == 2"
- class="shop-prompt f30 mb20">
- <image class="w32 h32 mr8" src="/static/images/shopping.png" />
- <text>{{ orderUser.count || 0 }}人正在去购买</text>
- </view>
- <view v-if="showWelcomeMessage" class="welcome-message" style="max-width: 100%">
- <view class="list justify-start" v-show="inAndOut.cmd == 'entry' || inAndOut.cmd == 'out'">
- <view class="talk-list justify-start">
- <view class="fs30">
- <text style="color: #ff89d6">{{ inAndOut.nickName || '未命名' }}</text>
- <text class="colorf">{{ inAndOut.msg }}直播间</text>
- </view>
- </view>
- </view>
- </view>
- <view class="notice-message" v-if="!isFocus && isShowNotice">
- 公告消息: {{ notice.msg }}
- </view>
- <scroll-view id="msgScroll" v-if="Array.isArray(talklist)" enable-flex scroll-y="true"
- :enhanced="true" :bounces="false" :show-scrollbar="false" :fast-deceleration="false"
- :enable-back-to-top="false" class="scrolly flex-1 column"
- style="width: calc(100% - 20rpx); -webkit-overflow-scrolling: touch;"
- :scroll-top="scrollTop" :scroll-into-view="scrollIntoView" @scroll="onScroll"
- ref="scrollView" scroll-with-animation="true" :scroll-animation-duration="300">
- <view class="list justify-start" v-for="(item, talkIndex) in talklist || []"
- :key="talkIndex" :id="`list_${item.uniqueId || talkIndex}`"
- v-show="item.cmd != 'red' && item.cmd != 'out' && item.cmd != 'entry'">
- <view class="talk-list justify-start">
- <view class="fs30 talk-item" style="max-width: 100%;">
- <text class="nickname" style="color: #ffda73;">{{ item.nickName || '未命名'
- }}:</text>
- <text class="message colorf">{{ item.msg }}</text>
- </view>
- </view>
- </view>
- </scroll-view>
- <!-- 一键弹幕 -->
- <u-scroll-list :indicator="false" v-if="!isFocus">
- <view class="barrage" v-for="(item, index) in barrageList" :key="index"
- @click="onBarrage(item)">
- {{ item }}
- </view>
- </u-scroll-list>
- </view>
- <!-- 聊天输入组件 -->
- <ChatInput ref="chatInput" :value="value" :focused="isFocus" :placeholderText="placeholderText"
- @focus="onInputFocus" @blur="onInputBlur" @send="onSendMessage" @open-cart="openCart"
- @show-gift="showGift" @input="onInputChange" @show-more="handleShowMore" />
- </view>
- </view>
- <!-- 商品卡片 -->
- <LiveGoods class="shop-card" :isShow="isShowGoods" :goodsData="goodsCard" @goShop="handleGoShop"
- @close="handleCloseGoods" />
- <!-- 抽奖弹窗 -->
- <LotteryPopup :show="isShowLotteryPop && countdown" :countdown="countdown" :products="lotteryProducts"
- @close="handleLotteryClose" @claim="handleLotteryClaim" />
- <u-popup :show="!!integral.status" round="20rpx" mode="center" bgColor="#ffffff" zIndex="10076">
- <view class="integral-box">
- <view class="top">
- <view class="title">观看视频领芳华币</view>
- <image class="photo" src="/static/images/integral_bg.png" mode="widthFix" />
- </view>
- <view class="item">
- <view class="title">{{ integral.msg }}</view>
- <view class="button" @click="integral.status = false">确认</view>
- </view>
- </view>
- </u-popup>
- <u-popup :show="shouldShowIntegralPopup" round="20rpx" mode="center" bgColor="#ffffff" zIndex="10076">
- <view class="integral-popup color9">
- <view class="integral-header">
- <view class="integral-title">观看视频领积分</view>
- <image class="integral-background-image"
- src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/integral_bg.png"
- mode="widthFix" />
- </view>
- <view class="integral-content">
- <view class="integral-message">积分发放成功</view>
- </view>
- </view>
- </u-popup>
- <u-popup :show="isShowRedCard" round="20rpx" mode="center" bgColor="transparent" zIndex="10076">
- <view class="red-card">
- <image class="img" src="/static/images/red_card.png" />
- <view class="red-content">
- <view class="title">{{ redCard.msg }}</view>
- <view class="txt">直播惊喜芳华币</view>
- <view class="button" @click="isShowRedCard = false">确认</view>
- </view>
- </view>
- </u-popup>
- <!-- 中奖和未中奖 -->
- <u-popup :show="isShowPrize && havePrize" round="20rpx" mode="center" bgColor="#fff" zIndex="10076">
- <view class="prize-card" v-if="isCurrentUserWon">
- <image class="nav-img" src="/static/images/red_head.png" mode="widthFix" />
- <view class="title">恭喜您 中奖啦!</view>
- <view class="prize-content" v-for="(item, index) in prizeInfo || []" :key="index">
- <view class="item">{{ item.userName }}</view>
- <view class="item">{{ item.userId }}</view>
- <view class="txt item">{{ item.prizeLevel }}等奖</view>
- </view>
- <view class="tip">请填写收货地址,主播将会将奖品发给您</view>
- <view class="button"
- @click="navgetTo('/pages_shopping/live/confirmCreateOrder?type=win&productId=' + getCurrentUserPrizeProductId + '&liveId=' + liveId + '&recordId=' + getCurrentUserPrizeRecordId), confirm()">
- 填写地址
- </view>
- </view>
- <view class="no-prize-card" v-else>
- <image class="img" src="/static/images/no-prize.png" mode="widthFix" />
- <view class="tip">很遗憾 您未中奖</view>
- <view class="button" @click="confirm">确认</view>
- </view>
- </u-popup>
- <!-- 中奖记录 -->
- <WinningPopup :show="winning" :prizeList="prizeAll" :liveId="liveId" @close="closeWin"
- @fill-address="handleFillAddress" />
-
-
- <!-- 更多弹窗 -->
- <u-popup :show="isMore" @close="closeMore" round="20rpx" bgColor="#f3f5f9" zIndex="10076">
- <view class="more-block">
- <view class="item" @click="navgetTo('/pages_shopping/live/integral'), (isMore = false)">
- <image class="w48 h48" src="/static/images/points.png" />
- <view style="text-align: center">芳华币</view>
- </view>
- <view class="item" @click="goOrder(), (isMore = false)">
- <image class="w48 h48" src="/static/images/order.png" />
- <view style="text-align: center">我的订单</view>
- </view>
- <view class="item"
- @click="navgetTo('/pages_shopping/live/storeOrderRefundList?liveId=' + liveId), (isMore = false)">
- <image class="w48 h48" src="/static/images/after_sales.png" />
- <view style="text-align: center">售后订单</view>
- </view>
- <view class="item" @click="getMyLottery(), (isMore = false), (winning = true)">
- <image class="w48 h48" src="/static/images/health_sel.png" />
- <view style="text-align: center">中奖记录</view>
- </view>
- </view>
- </u-popup>
- <!-- 送礼物 -->
- <u-popup :show="isShowGift" @close="closeGift" round="20rpx" bgColor="#242424" zIndex="10076">
- <view class="gift">
- <view class="gift-top">
- <view class="left">
- 送花给<text class="ml8 orange">{{ liveItem.liveName }}</text>
- </view>
- <view class="align-center" @click="navgetTo('/pages_shopping/live/integral')">
- <image class="w32 h32" src="/static/images/coin.png" />
- <text class="ml6 mr6 f24">{{ integralNum }}</text>
- <image class="w24 h24" src="/static/images/arrow_white.png" />
- </view>
- </view>
- <view class="gift-block">
- <view :class="['item', { 'active': activeIndex === index }]" @click="activeIndex = index"
- v-for="(item, index) in giftList" :key="index">
- <image class="w104 h104" :src="item.img" />
- <view class="name">{{ item.giftName }}</view>
- <view v-if="activeIndex === index" class="button" @click="sendliveGift(item)">赠送</view>
- <view class="number" v-else>{{ item.price }}芳华币</view>
- </view>
- </view>
- </view>
- </u-popup>
- <!-- 微信昵称授权弹窗 -->
- <u-popup :show="userlogo" mode="bottom" round='12'>
- <view class="userlogo column">
- <view class="bold fs36 mt42">授权你的昵称信息</view>
- <view class=" justify-between align-center mt42">
- <view class="button-container">
- <input type="nickname" class="hidden-input"
- placeholder-style="color:#ffffff; font-size:32rpx;" @blur="onNickNameInput"
- placeholder="请点击授权微信昵称" @input="onNickNameInput" />
- </view>
- </view>
- <view class="submitname" @click="confimrname">确定</view>
- </view>
- </u-popup>
- <!-- 商品弹窗组件 -->
- <ShopPopup class="shop" :show="shopping" :searchKeyword="inputInfo" :products="products"
- :loading="loadingProducts" :boxHeight="boxHeight" @close="closeShop" @search="handleSearchInput"
- @navigate-to-order="handleNavigateToOrder" @show-more="handleShowMore" @collect="onGoodsCollect"
- @go-shop="handleGoShopFromCart" />
- <!-- 优惠券弹窗 -->
- <view class="coupon-pop" v-if="isShowCoupon">
- <view class="coupon-block">
- <image class="bg" src="/static/images/coupon_bg.png" />
- <image class="nav" src="/static/images/coupon_top.png" />
- <image @click="isShowCoupon = false" class="w40 h40 close" style="z-index: 99"
- src="/static/images/close1.png" />
- <view class="item">
- <view class="title">{{ couponInfo.couponName }}</view>
- <view class="price">
- ¥
- <text class="bold">{{ couponInfo.couponPrice }}</text>
- </view>
- <view class="txt">满{{ couponInfo.useMinPrice }}元可用</view>
- <view class="txt" style="margin-top: 26rpx">指定商品可用</view>
- <view class="txt">自领取起{{ couponInfo.couponTime }}天内有效</view>
- <view class="button" @click="onCoupon()">立即领券</view>
- </view>
- </view>
- </view>
- <view class="custom-toast" v-if="showToast">
- <view class="toast-content">
- 观看奖励已到账
- </view>
- </view>
- </view>
- </view>
- </template>
- <script>
- import ChatInput from '@/pages_course/components/chatInput.vue'
- import LiveVideo from '@/pages_course/components/liveVideo.vue'
- import ShopPopup from '@/pages_course/components/shopPopup.vue'
- import LotteryPopup from '@/pages_course/components/lotteryPopup.vue'
- import WinningPopup from '@/pages_course/components/winningPopup.vue'
- import LiveGoods from '@/pages_course/components/liveGoods.vue'
- import LikeButton from '@/pages_course/components/like.vue'
- import CryptoJS from 'crypto-js'
- import {
- myLottery,
- coupon,
- liveLottery,
- claim,
- liveRed,
- liveDataLike,
- collectStore,
- collectGoods,
- watchUserList,
- liveMsg,
- liveStore,
- liveOrderUser,
- getLiveInfo,
- getLiveViewData,
- currentActivities,
- getlive,
- subNotifyLive,
- internetTraffic,
- liveInternetTraffic,
- remainingTime,
- updateWatchDuration,
- receivePoints,
- activeList,
- sendliveGift,
- getUserIntegralInfo, //芳华币
- loginByMp
- } from '@/api/living.js'
- import {
- getUserInfo,
- editUser
- } from '@/api/user'
- import {
- generateRandomString
- } from '@/utils/common.js'
- import dayjs from 'dayjs'
- import {
- nextTick
- } from 'vue'
- var isSocketOpen = false
- var socket = null
- export default {
- components: {
- LikeButton,
- LiveGoods,
- LotteryPopup,
- WinningPopup,
- ShopPopup,
- LiveVideo,
- ChatInput
- },
- data() {
- return {fakeAvatar: Array.from({
- length: 11
- }, (_, i) =>
- `https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/avatar${i + 1}.jpg`),
- hasSubscribed: false, // 已成功订阅(永久禁用)
- integralNum: null, //礼物芳华币数量
- isPreview: true, //是否预告
- hasReplayGeneration: false, //是否经历回放生成
- diffLiveStartTime: 0, //距离直播开始时间差值
- diffLiveEndTime: 0, //距离直播结束时间差值
- diffReplayGenerationSeconds: 0, //经历回放生成的秒速
- completionTime: 0, //领取积分所需时间
- hasLiveEnd: false, //是否经历过首播结束
- isPageLoadFirst: true, //是否首次加载直播间
- pointsRetryTimer: null, // 积分领取重试定时器
- showToast: false,
- videoDuration: 0, //要看的时长
- pointsRemainingTime: 0,
- hasReceived: false,
- completionRate: 0,
- liveBeginWatchTime: 0,
- showPoints: false,
- remainingTime: null,
- // receiveStatus: false,
- watchDuration: null,
- isFullscreen: null,
- notice: [],
- isShowNotice: false,
- giftList: [{
- img: '/static/images/gift1.png',
- name: '人气票',
- number: 1
- },
- {
- img: '/static/images/gift2.png',
- name: '小心心',
- number: 1
- },
- {
- img: '/static/images/gift3.png',
- name: '棒棒糖',
- number: 9
- },
- {
- img: '/static/images/gift4.png',
- name: '玫瑰',
- number: 50
- },
- {
- img: '/static/images/gift5.png',
- name: '鲜花',
- number: 88
- },
- {
- img: '/static/images/gift6.png',
- name: '水晶球',
- number: 99
- },
- {
- img: '/static/images/gift7.png',
- name: '啤酒',
- number: 128
- },
- {
- img: '/static/images/gift8.png',
- name: '浪漫热气球',
- number: 1000
- }
- ],
- activeIndex: -1,
- barrageList: ['支持你!', '谢谢你!', '平台真好!', '666', '欢迎回家!'],
- uuId: '',
- totalTraffic: 0,
- bitrate: 800,
- bitrateLive: 1600,
- trafficTimer: null,
- pingTimeoutTimer: null,
- heartBeatTimer: null,
- liveViewDataTimer: null,
- lookAudsCount: 0, //更多的观众人数
- reconnectTimer: null,
- scrollTimer: null,
- lastScrollTime: 0,
- scrollDebounceDelay: 200,
- searchTimer: null,
- purchasePromptTimer: null,
- welcomeTimer: null,
- redTimer: null,
- liveStartTimer: null,
- lotteryTimer: null,
- memoryMonitorTimer: null,
- networkStatusTimer: null,
- networkRetryTimer: null,
- lastHeartBeatTime: 0,
- connectionStartTime: 0,
- connectionLatency: 0,
- messageCount: 0,
- errorCount: 0,
- lastPerformanceCheck: 0,
- stayTime: 0,
- startTime: 0,
- scrollTop: 0,
- currentScrollTop: 0,
- scrollIntoView: '',
- messageIdCounter: 0,
- scrollPending: false,
- isOnload: false,
- isConnecting: false,
- hasInitialized: false,
- liveViewersData: [],
- liveTopViewersData: [],
- liveUserCalled: false,
- userRandomColors: Object.create(null),
- heartBeatRetryCount: 0,
- maxHeartBeatRetries: 3,
- pingTimeout: 25000,
- shownEntryUsers: new Set(),
- socket: null,
- isSocketOpen: false,
- heartBeatInterval: 15000,
- adaptiveHeartBeatInterval: 15000,
- reconnectCount: 0,
- maxReconnectAttempts: 5,
- isManualClose: false,
- networkType: 'unknown',
- isNetworkAvailable: true,
- templateId: 'oDN_EoYNNb5RKbhTAfVtXevSGRhoyoOQwR9JKqeKMbA',
- isAgreement: false,
- wsNewUrl: 'wss://api.fhhx.runtzh.com/ws/app/webSocket',
- qrFrom: null,
- scene: '',
- liveCountdown: {},
- countdown: {},
- liveViewData: {},
- keyboardHeight: 0,
- videoCurrentTime: 0,
- videoProgressKey: '',
- inAndOut: {},
- winning: false,
- isShowPrize: false,
- isShowCoupon: false,
- isShowGift: false,
- prizeInfo: [],
- havePrize: uni.getStorageSync('havePrize') || false,
- countDownKey: 0,
- lotteryProducts: [],
- lotteryList: [],
- talklist: [],
- isShowLotteryPop: false,
- liveItem: {},
- isSending: false,
- isMore: false,
- value: '',
- placeholderText: '说点什么...',
- prizeAll: [],
- isShowLottery: false,
- isShowRedCard: false,
- redCard: null,
- integral: {},
- lotteryInfo: {},
- goodsCard: {},
- couponInfo: {},
- redInfo: {},
- storeId: null,
- isFocus: false,
- shopping: false,
- systemInfo: null,
- inputInfo: '',
- showWelcomeMessage: false,
- isShowGoods: false,
- isShowRed: false,
- lastClickTime: 0,
- videoRetryCounts: Object.create(null),
- clickDelay: 300,
- liveUserTotal: 0,
- showPurchasePrompt: false,
- prevOrderCount: 0,
- videoUrl: null,
- boxHeight: 300,
- products: [],
- loadingProducts: false,
- orderUser: {},
- userType: 0,
- timestamp: '',
- liveId: null,
- userinfo: '',
- userData: {},
- diffTotalTime: '',
- virtualTotal: 0,
- userlogo: false,
- user: {},
- userInfo: '',
- urlOption: {}
- }
- },
- async onLoad(options) {
- if (options.liveId) {
- this.liveId = options.liveId
- }
- if (options.scene) {
- this.scene = options.scene
- const decodedScene = decodeURIComponent(this.scene)
- const params = {}
- decodedScene.split('&').forEach((item) => {
- const [key, value] = item.split('=')
- params[key] = value
- this.liveId = params.a
- })
- if (params.b && params.c) {
- this.qrFrom = `&companyId=${params.b||this.liveItem.companyId||-1}&companyUserId=${params.c}`
- }
- }
- if (options.companyId && options.companyUserId) {
- this.qrFrom = `&companyId=${options.companyId||this.liveItem.companyId||-1}&companyUserId=${options.companyUserId}`
- }
- // 保存url参数
- this.urlOption = options;
- this.userinfo = uni.getStorageSync('userInfo')
- this.userData = uni.getStorageSync('userData')
- this.hasSubscribed = uni.getStorageSync('subscribe_status_' + this.liveId) || false;
- try {
- const isLogin = await this.utils.checkLiveToken();
- this.hasCheckedLogin = true;
- if (isLogin) {
- // 登录后:优先加载直播间信息,然后加载视频资源
- await this.haveLogin();
- } else {
- // 未登录:先登录,登录成功后再加载数据
- this.goLogin();
- }
- } catch (error) {
- console.error('初始化失败:', error);
- this.hasCheckedLogin = true;
- }
- this.startMemoryMonitor();
- //获取礼物列表
- this.getActiveList();
- uni.onKeyboardHeightChange((res) => {
- console.log('键盘高度变化:', res.height, '平台:', this.systemInfo.platform)
- if (this.systemInfo.platform === 'ios') {
- if (res.height > 0) {
- this.isKeyboardShow = true
- let calculatedHeight = res.height * 2
- if (this.systemInfo.model) {
- if (this.systemInfo.model.includes('iPhone X') ||
- this.systemInfo.model.includes('iPhone 11') ||
- this.systemInfo.model.includes('iPhone 12') ||
- this.systemInfo.model.includes('iPhone 13') ||
- this.systemInfo.model.includes('iPhone 14') ||
- this.systemInfo.model.includes('iPhone 15') ||
- this.systemInfo.model.includes('iPhone 16') ||
- this.systemInfo.model.includes('iPhone 17')) {
- calculatedHeight = calculatedHeight + 20
- }
- }
- const safeAreaBottom = this.systemInfo.safeAreaInsets ? this.systemInfo.safeAreaInsets
- .bottom : 0
- if (safeAreaBottom > 0) {
- calculatedHeight = calculatedHeight - (safeAreaBottom * 3.0)
- }
- this.keyboardHeight = Math.max(400, calculatedHeight)
- } else {
- this.isKeyboardShow = false
- this.keyboardHeight = 0
- }
- } else {
- console.log('手机型号是>>>>', this.systemInfo.model)
- if (res.height > 0) {
- this.isKeyboardShow = true
- const safeAreaBottom = this.systemInfo.safeAreaInsets ? this.systemInfo.safeAreaInsets
- .bottom : 0
- if (this.systemInfo.brand == 'vivo') {
- this.keyboardHeight = res.height * 2
- } else {
- this.keyboardHeight = (res.height * 1.78) + 20
- }
- console.log('高度是', this.keyboardHeight)
- } else {
- this.isKeyboardShow = false
- this.keyboardHeight = 0
- }
- }
- })
- this.initNetworkStatusListener();
- },
- onPullDownRefresh() {
- this.getLiveMsg(this.liveItem);
- this.getliveUserInit();
- setTimeout(() => {
- uni.stopPullDownRefresh()
- }, 1000)
- },
- async onShow() {
- try {
- const isLogin = await this.utils.checkLiveToken()
- if (isLogin) {
- await this.haveLogin();
- } else {
- this.goLogin();
- }
- } catch (error) {
- console.error('初始化失败:', error)
- }
- if (this.liveId) {
- await this.getLiveMsg(this.liveItem)
- }
- if (!this.liveViewData) {
- this.getliveViewData()
- }
- this.uuId = generateRandomString(16)
- const isLiveLogin = uni.getStorageSync('isLiveLogin')
- this.share = uni.getStorageSync('share')
- this.scene = uni.getStorageSync('scene')
- if (this.share && this.share.length > 0) {
- this.liveId = this.share.liveId
- this.qrFrom = `&companyId=${this.share.companyId||this.liveItem.companyId||-1}&companyUserId=${this.share.companyUserId}`
- uni.removeStorageSync('share')
- }
- if (this.scene) {
- const decodedScene = decodeURIComponent(this.scene)
- const params = {}
- decodedScene.split('&').forEach((item) => {
- const [key, value] = item.split('=')
- params[key] = value
- this.liveId = params.a
- })
- if (params.b && params.c) {
- this.qrFrom = `&companyId=${params.b||this.liveItem.companyId||-1}&companyUserId=${params.c}`
- }
- uni.removeStorageSync('scene')
- }
- if (isLiveLogin) {
- if (this.liveId) {
- const userInfo = uni.getStorageSync('userInfo');
- if (userInfo) {
- await this.getliving(this.liveId)
- this.getCurrentActivities()
- this.getliveOrder()
- this.initSocket()
- }
- }
- this.$nextTick(() => {
- if (!this.userData.unionId) {
- uni.navigateTo({
- url: '/pages/auth/login'
- })
- }
- })
- this.hasInitialized = true
- uni.removeStorageSync('isLiveLogin')
- }
- await this.resumePageActivity()
- this.userinfo = uni.getStorageSync('userInfo')
- this.isAgreement = uni.getStorageSync('isAgreement')
- this.$nextTick(() => {
- if (this.$refs.liveVideo && this.$refs.liveVideo.setVideoProgress) {
- this.$refs.liveVideo.setVideoProgress()
- }
- });
- if (this.lookTimer) {
- clearInterval(this.lookTimer)
- this.lookTimer = null
- this.stayTime = 0
- this.startTime = 0
- }
- // 清除等待定时器
- if (this.$refs.liveVideo && this.$refs.liveVideo.waitingTimer) {
- clearTimeout(this.$refs.liveVideo.waitingTimer);
- this.$refs.liveVideo.waitingTimer = null;
- }
- // 同时清理自身的waitingTimer(如果存在)
- if (this.waitingTimer) {
- clearTimeout(this.waitingTimer);
- this.waitingTimer = null;
- }
- if (this.trafficTimer) {
- clearInterval(this.trafficTimer)
- this.trafficTimer = null
- this.startTime = 0
- this.totalTraffic = 0
- }
- if (this.$refs.liveVideo && this.$refs.liveVideo.startTimer) {
- this.$refs.liveVideo.startTimer()
- }
- if (this.liveItem.completionPointsEnabled && !this.hasReceived) {
- setTimeout(() => {
- this.startCountdown();
- }, 500);
- }
- },
- onShareAppMessage() {
- return {
- title: '邀请你来观看直播:' + this.liveItem.liveName,
- path: '/pages_course/living?companyId=-2&companyUserId=' + this.userData.userId + '&liveId=' + this.liveId,
- imageUrl: '/static/images/logo.png',
- success(res) {
- console.log('分享成功', res)
- },
- fail(err) {
- console.error('分享失败', err)
- }
- }
- },
- onShareTimeline() {
- return {
- title: '邀请你来观看直播:' + this.liveItem.liveName,
- query: 'companyId=-2&companyUserId=' + this.userData.userId + '&liveId=' + this.liveId
- }
- },
- computed: {
- appid() {
- return this.$store.state.appid
- },
- shouldShowIntegralPopup() {
- //只有当 showPoints 为 true 且 receiveList 有数据时才显示
- return this.showPoints;
- },
- countdownPercentage() {
- return this.getCountdownPercentage()
- },
- formattedCountdown() {
- return this.formatCountdown(this.pointsRemainingTime)
- },
- formattedWatchCount() {
- return this.formatNumber(this.liveUserTotal*2+50 || 0)
- },
- formattedLikeCount() {
- return this.formatNumber(this.liveViewData.like || 0)
- },
- filteredViewers() {
-
- // 从预设的头像数组中随机选择3个
- const avatarArray = this.fakeAvatar;
- const shuffled = [...avatarArray].sort(() => 0.5 - Math.random());
- const selected = shuffled.slice(0, 3);
- // 转换为包含avatar属性的对象数组
- return selected.map((avatar, index) => ({
- userId: `virtual_${index}`,
- avatar: avatar
- }));
- },
- isCurrentUserWon() {
- if (!Array.isArray(this.prizeInfo) || !this.userData?.userId) {
- return false
- }
- return this.prizeInfo.some((item) => {
- return String(item.userId) === String(this.userData.userId)
- })
- },
- getCurrentUserPrizeProductId() {
- if (!Array.isArray(this.prizeInfo) || !this.userData?.userId) {
- return null
- }
- const userPrize = this.prizeInfo.find(item => {
- return String(item.userId) == String(this.userData.userId)
- })
- return userPrize ? userPrize.productId : null
- },
- getCurrentUserPrizeRecordId() {
- if (!Array.isArray(this.prizeInfo) || !this.userData?.userId) {
- return null
- }
- const userPrize = this.prizeInfo.find(item => {
- return String(item.userId) == String(this.userData.userId)
- })
- return userPrize ? userPrize.recordId : null
- }
- },
- onHide() {
- if (this.talklist && this.talklist.length > 20) {
- this.talklist = this.talklist.slice(-20)
- }
- // 保存观看时长
- this.updateWatchDuration();
- this.stopCountdown();
- // 清理流量定时器
- if (this.$refs.liveVideo && this.$refs.liveVideo.clearAllTimers) {
- this.$refs.liveVideo.clearAllTimers()
- }
- },
- onUnload() {
- if (this.$refs.liveVideo && this.$refs.liveVideo.saveVideoProgress) {
- this.$refs.liveVideo.saveVideoProgress()
- }
- // 暂停视频
- if (this.$refs.liveVideo && this.$refs.liveVideo.pauseVideo) {
- this.$refs.liveVideo.pauseVideo()
- }
- // 清理流量定时器
- if (this.$refs.liveVideo && this.$refs.liveVideo.clearAllTimers) {
- this.$refs.liveVideo.clearAllTimers()
- }
- // 清理liveItem中的定时器
- if (this.liveItem && this.liveItem.timeTimer) {
- clearInterval(this.liveItem.timeTimer)
- this.liveItem.timeTimer = null
- }
- // 更新后端观看时长
- this.updateWatchDuration();
- this.stopCountdown();
- this.closeWebSocket(true);
- this.clearAllTimersEnhanced();
- const videoId = `myVideo_${this.liveId}`
- const videoContext = uni.createVideoContext(videoId, this)
- if (videoContext) {
- videoContext.pause();
- }
- try {
- uni.offNetworkStatusChange();
- } catch (err) {
- console.warn('移除网络状态监听失败:', err)
- }
- this.clearBigData();
- this.resetAllStates();
- },
- mounted() {
- this.systemInfo = uni.getSystemInfoSync()
- console.log('系统信息:', this.systemInfo.platform, this.systemInfo.model)
- // this.getCurrentActivities()
- this.getliveOrder()
- },
- watch: {
- 'orderUser.count': {
- handler(newVal, oldVal) {
- if (newVal !== this.prevOrderCount) {
- this.prevOrderCount = newVal
- this.showPurchaseMessage()
- }
- },
- immediate: true
- }
- },
- methods: { // 芳华币
- // 微信昵称授权相关方法
- shouquan() {
- if (this.user.nickname == '') {
- uni.showToast({
- icon: 'none',
- title: "请先授权微信昵称",
- });
- }
- },
- confimrname() {
- if (this.user.nickname == '') {
- uni.showToast({
- icon: 'none',
- title: "请授权微信昵称",
- });
- return
- }
- this.editUser();
- uni.setStorageSync('userInfo', this.userInfo);
- if (this.user.nickname) {
- this.userlogo = false;
- }
- },
- onNickNameInput(e) {
- this.user.nickname = e.detail.value;
- },
- editUser() {
- this.user.nickName = this.user.nickname;
- editUser(this.user).then(
- res => {
- if (res.code == 200) {
- uni.showToast({
- icon: 'success',
- title: "修改成功",
- });
- this.getUserInfo()
- } else {
- uni.showToast({
- icon: 'none',
- title: res.msg,
- });
- }
- },
- rej => {}
- );
- },
- // 静默登录
- goLogin(data) {
- let provider = 'weixin'
- uni.login({
- provider: provider,
- success: async loginRes => {
- uni.getUserInfo({
- provider: provider,
- success: (infoRes) => {
- uni.showToast({
- title: '登录中...',
- icon: 'loading'
- });
- loginByMp({
- code: loginRes.code,
- encryptedData: infoRes.encryptedData,
- iv: infoRes.iv,
- appId: this.appid
- }).then(res => {
- uni.hideLoading();
- if (res.code == 200) {
- uni.setStorageSync('AppToken', res
- .token);
- uni.setStorageSync('userInfo', JSON
- .stringify(res
- .user));
- if(!res.user.createTime){
- this.getUserInfo()
- }else{
- uni.setStorageSync('userData', JSON
- .stringify(res
- .user));
- }
-
- this.userInfo = uni.getStorageSync(
- 'userInfo');
- this.userData = uni.getStorageSync(
- 'userData');
- // uni.setStorageSync('auto_userInfo', JSON.stringify(res.user));
- // this.user = res.user
- this.$store.commit('setCoureLogin', 1);
- this.isLogin = true
- this.haveLogin()
- this.userlogo = true
- // console.log("TOKEN_KEYAuto",TOKEN_KEYAuto)
- if (this.urlOption.qwUserId) {
- this.getIsAddKf() //this.getIsAddKf()
- }
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- }
- }).catch(err => {
- uni.hideLoading();
- uni.showToast({
- icon: 'none',
- title: "登录失败,请重新登录",
- });
- });
- }
- });
- }
- })
- },
- async haveLogin() {
- // 防止重复执行
- if (this.isOnload) {
- return;
- }
- this.userInfo = uni.getStorageSync('userInfo');
- if (this.userInfo) {
- await this.getUserInfo();
- }
- if (this.liveId) {
- // 优先加载直播间信息(包含视频资源URL)
- this.isOnload = true;
- const userInfo = uni.getStorageSync('userInfo');
- if (userInfo) {
- await this.getliving(this.liveId);
- }
- Promise.all([
- this.getLiveMsg(this.liveItem),
- this.getliveViewData()
- ]).catch(err => {
- console.error('加载数据失败:', err);
- });
- // 其他非关键数据异步加载
- this.getCurrentActivities();
- this.getliveOrder();
- this.initSocket();
- this.getUserIntegralInfo();
- }
- },
- getUserIntegralInfo() {
- getUserIntegralInfo().then(res => {
- if (res.code == 200) {
- this.integralNum = res.data.integral
- }
- }).catch(error => {
- console.error("获取芳华币数据失败:", error);
- });
- },
- //礼物列表
- getActiveList() {
- activeList().then((res) => {
- if (res.code == 200) {
- this.giftList = res.data
- console.log('正常状态的礼物列表', res.data)
- }
- }).catch((error) => {})
- },
- // 送礼物
- sendliveGift(item) {
- if (!this.liveId) return
- const data = {
- liveId: this.liveId,
- giftId: item.giftId,
- // giftId: this.giftId,
- // cn: this.cn
- cn: 1
- }
- sendliveGift(data).then((res) => {
- if (res.code == 200) {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- console.log('用户送礼物', res)
- this.getUserIntegralInfo();
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- }
- }).catch((error) => {})
- },
- // 查询当前用户当前直播间领取积分的剩余时长
- getRemainingTime() {
- if (!this.liveId) return
- const data = {
- liveId: this.liveId
- }
- remainingTime(data).then((res) => {
- if (res.code == 200) {
- this.hasReceived = res.data.hasReceived
- this.videoDuration = res.data.videoDuration
- this.watchDuration = res.data.watchDuration
- this.remainingTime = res.data.remainingTime
- this.completionRate = res.data.completionRate
- console.log('查询当前用户当前直播间领取积分的剩余时长', res)
- }
- }).catch((error) => {})
- },
- // 查询用户积分领取记录
- // completionRecords() {
- // if (!this.liveId) return
- // const data = {
- // liveId: this.liveId
- // }
- // completionRecords(data).then((res) => {
- // if (res.code == 200) {
- // const targetData = res.data.find(item => item.liveId == this.liveId)
- // if (targetData) {
- // const receiveStatus = targetData.receiveStatus
- // this.receiveStatus = receiveStatus
- // } else {
- // console.log('未找到liveId为', this.liveId, '的数据')
- // this.receiveStatus = false
- // }
- // console.log('查询用户积分领取记录', res)
- // }
- // }).catch((error) => {})
- // },
- // 更新用户的看课时长
- updateWatchDuration() {
- if (!this.liveId) return;
- if (this.isPreview) return;
- //const watchDuration = Math.floor((Date.now() - this.liveBeginWatchTime) / 1000)
- const watchDuration = this.totalWatchTime - this.watchDuration;
- updateWatchDuration(this.liveId, watchDuration).then((res) => {
- if (res.code == 200) {
- console.log("更新用户的看课时长", res);
- this.receivePoints();
- }
- }).catch((error) => {
- });
- },
- // 用户领取看课积分 (传入直播间id)
- receivePoints(retryCount = 0) {
- if (!this.liveId) return;
- // const data = {
- // liveId: this.liveId
- // }
- receivePoints(this.liveId).then((res) => {
- if (res.code == 200) {
- console.log("用户领取看课积分", res);
- //清除重试定时器
- if (this.pointsRetryTimer) {
- clearTimeout(this.pointsRetryTimer);
- this.pointsRetryTimer = null;
- }
- }
- }).catch((error) => {
- console.log("用户领取积分失败error", error);
- // 增加重试机制:最多重试3次
- if (retryCount < 3) {
- const delay = (retryCount + 1) * 2000; // 递增延迟: 2s, 4s, 6s
- console.log(`领取积分失败,${delay}ms后进行第${retryCount + 1}次重试`);
- if (this.pointsRetryTimer) {
- clearTimeout(this.pointsRetryTimer);
- }
- this.pointsRetryTimer = setTimeout(() => {
- this.receivePoints(retryCount + 1);
- }, delay);
- }
- });
- },
- // 开始观看时长统计
- // startWatchDurationTracking() {
- // if (this.watchStartTime > 0) {
- // console.log('观看时长统计已启动,跳过')
- // return
- // }
- // this.watchStartTime = Date.now()
- // this.isPageVisible = true
- // console.log('开始观看时长统计', new Date(this.watchStartTime).toLocaleString())
- // this.initPageVisibilityListener()
- // },
- // getCurrentWatchDuration() {
- // if (this.watchStartTime === 0) {
- // return this.accumulatedWatchDuration
- // }
- // if (this.isPageVisible) {
- // const currentDuration = Math.floor((Date.now() - this.watchStartTime) / 1000)
- // return this.accumulatedWatchDuration + currentDuration
- // }
- // return this.accumulatedWatchDuration
- // },
- // pauseWatchDurationTracking() {
- // if (!this.isPageVisible || this.watchStartTime === 0) {
- // return
- // }
- // const currentSessionDuration = Math.floor((Date.now() - this.watchStartTime) / 1000)
- // this.accumulatedWatchDuration += currentSessionDuration
- // this.lastPauseTime = Date.now()
- // this.isPageVisible = false
- // console.log(`暂停观看统计: 本次=${currentSessionDuration}秒, 累计=${this.accumulatedWatchDuration}秒`)
- // },
- // resumeWatchDurationTracking() {
- // if (this.isPageVisible) {
- // return
- // }
- // this.watchStartTime = Date.now()
- // this.isPageVisible = true
- // const pauseDuration = this.lastPauseTime > 0 ? Math.floor((Date.now() - this.lastPauseTime) / 1000) : 0
- // console.log(`恢复观看统计: 暂停了${pauseDuration}秒, 当前累计=${this.accumulatedWatchDuration}秒`)
- // },
- // stopWatchDurationTracking() {
- // if (this.isPageVisible && this.watchStartTime > 0) {
- // const currentSessionDuration = Math.floor((Date.now() - this.watchStartTime) / 1000)
- // this.accumulatedWatchDuration += currentSessionDuration
- // }
- // console.log(`停止观看统计: 总时长=${this.accumulatedWatchDuration}秒`)
- // this.watchStartTime = 0
- // this.isPageVisible = true
- // this.lastPauseTime = 0
- // this.removePageVisibilityListener()
- // },
- // initPageVisibilityListener() {
- // uni.onAppShow(() => {
- // console.log('小程序回到前台')
- // this.resumeWatchDurationTracking()
- // })
- // uni.onAppHide(() => {
- // console.log('小程序切换到后台')
- // this.pauseWatchDurationTracking()
- // })
- // },
- removePageVisibilityListener() {},
- calculateLiveTimeDiff(timeStr, useServerTime = false) {
- // 0. 安全校验:防止 undefined/null 导致 crash
- if (!timeStr) {
- return 0;
- }
- // 1. 获取当前时间戳(毫秒)- 倒计时场景使用服务器时间
- const now = this.getServerTimeNow();
- // 2. 计算差值(毫秒 -> 秒)
- // 结果为:当前时间 - 直播开始时间
- const diffInSeconds = Math.floor((now - timeStr) / 1000);
- return diffInSeconds;
- },
- calculateLiveEndTime(startTime, duration) {
- if (!startTime) return '';
- // 计算结束时间戳
- const endTimeMs = startTime + (Number(duration) * 1000);
- const endDate = new Date(endTimeMs);
- // 格式化
- const year = endDate.getFullYear();
- const month = this.padZero(endDate.getMonth() + 1);
- const day = this.padZero(endDate.getDate());
- const hours = this.padZero(endDate.getHours());
- const minutes = this.padZero(endDate.getMinutes());
- const seconds = this.padZero(endDate.getSeconds());
- return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
- },
- startCountdown() {
- // 如果已经领取过积分,不启动倒计时
- if (this.hasReceived) {
- return;
- }
- if (!this.liveItem || Array.isArray(this.liveItem) || !this.liveItem.completionPointsEnabled) {
- return;
- }
- // 如果倒计时已经在运行,先清除旧的定时器
- if (this.countdownTimer) {
- clearInterval(this.countdownTimer);
- this.countdownTimer = null;
- }
- // 使用服务器时间重新计算初始状态,确保设备时间不一致时也能正确判断
- const liveStartTime = this.getLiveStartTime();
- if (!liveStartTime) {
- return;
- }
- this.diffLiveStartTime = this.calculateLiveTimeDiff(liveStartTime, true);
- // 如果直播已开始,确保 isPreview 为 false
- if (this.diffLiveStartTime >= 0) {
- this.isPreview = false;
- }
- this.isCountdownActive = true;
- // 立即执行一次更新,确保倒计时显示正确
- this.updateCountdown();
- this.countdownTimer = setInterval(() => {
- this.updateCountdown();
- }, 1000); // 每秒更新一次
- },
- updateCountdown() {
- // 如果已经领取过积分,停止倒计时
- if (this.hasReceived) {
- this.stopCountdown();
- return;
- }
- if (!this.liveItem || Array.isArray(this.liveItem)) {
- return;
- }
- // 使用服务器时间重新计算初始状态,确保设备时间不一致时也能正确判断
- const liveStartTime = this.getLiveStartTime();
- if (!liveStartTime) {
- return;
- }
- this.diffLiveStartTime = this.calculateLiveTimeDiff(liveStartTime, true);
- // 如果直播已开始,确保 isPreview 为 false
- if (this.diffLiveStartTime >= 0) {
- this.isPreview = false;
- }
- this.completionTime = this.liveItem.duration * this.completionRate * 0.01;
- // 已达成观看时间
- if (this.watchDuration > this.completionTime) {
- if (this.countdownTimer) {
- clearInterval(this.countdownTimer);
- this.countdownTimer = null;
- this.isPreview = true;
- return;
- }
- }
- console.log('this.liveItem.duration', this.liveItem.duration);
- console.log('this.completionRate', this.completionRate);
- console.log('this.completionTime', this.completionTime);
- // 倒计时已结束
- if (this.pointsRemainingTime < 0) {
- this.stopCountdown();
- return;
- }
- this.showPoints = false;
- // 使用服务器时间计算差值
- const serverTimeNow = this.getServerTimeNow();
- this.diffLiveStartTime = this.calculateLiveTimeDiff(liveStartTime, true);
- this.diffLiveEndTime = this.calculateLiveTimeDiff(liveStartTime, true) - this.liveItem.duration;
- if (!this.liveItem.finishTime) {
- this.liveItem.finishTime = this.calculateLiveEndTime(liveStartTime, this.liveItem.duration);
- }
- // 预告状态
- if (this.diffLiveStartTime < 0) {
- this.isPreview = true;
- return;
- } else {
- // 直播已开始(基于服务器时间),确保 isPreview 为 false
- this.isPreview = false;
- }
- if (this.diffLiveStartTime >= 0) {
- if (this.diffLiveEndTime >= 0) {
- // 直播回放中
- if (this.hasReplayGeneration) {
- // 经历过回放生成 回放生成后扣减掉经历回放生成的时间
- this.totalWatchTime = this.watchDuration + Math.floor((serverTimeNow - this
- .liveBeginWatchTime) / 1000) - this.diffReplayGenerationSeconds;
- } else {
- // 进入直播间时已过回放生成中
- this.totalWatchTime = this.watchDuration + Math.floor((serverTimeNow - this
- .liveBeginWatchTime) / 1000);
- }
- } else {
- // 直播中状态
- this.totalWatchTime = this.watchDuration + Math.floor((serverTimeNow - this.liveBeginWatchTime) /
- 1000);
- }
- // 积分领取满足条件
- if (this.totalWatchTime >= this.completionTime) {
- if (this.countdownTimer) {
- clearInterval(this.countdownTimer);
- this.countdownTimer = null;
- this.onCountdownComplete();
- return;
- }
- }
- this.isPreview = false;
- // 直播中或回放状态都计算剩余时间
- if (this.diffLiveStartTime >= 0) {
- if (this.diffLiveEndTime < 0) {
- // 直播中状态
- this.pointsRemainingTime = Math.max(0, this.completionTime - this.totalWatchTime);
- }
- }
- }
- // 更新显示
- this.updateCountdownDisplay();
- },
- stopCountdown() {
- if (this.countdownTimer) {
- clearInterval(this.countdownTimer)
- this.countdownTimer = null
- }
- this.isCountdownActive = false
- this.updateWatchDuration()
- },
- onCountdownComplete() {
- console.log('倒计时完成!')
- this.stopCountdown()
- this.pointsRemainingTime = -1
- this.triggerWatchComplete()
- setTimeout(() => {
- this.showToast = true
- setTimeout(() => {
- this.showToast = false
- }, 5000)
- }, 1000)
- },
- async triggerWatchComplete() {
- if (!this.userInfo?.userId || !this.liveId) return
- try {
- console.log('用户已完成观看')
- uni.removeStorageSync(this.watchProgressKey)
- } catch (error) {
- console.error('触发观看完成事件失败:', error)
- }
- },
- padZero(num) {
- return num < 10 ? `0${num}` : num.toString()
- },
- formatCountdown(seconds) {
- const totalSeconds = Math.max(0, Math.floor(Number(seconds) || 0))
- const hours = Math.floor(totalSeconds / 3600)
- const remainingAfterHours = totalSeconds % 3600
- const minutes = Math.floor(remainingAfterHours / 60)
- const secs = remainingAfterHours % 60
- return {
- hours: this.padZero(hours),
- minutes: this.padZero(minutes),
- seconds: this.padZero(secs),
- total: totalSeconds
- }
- },
- getCountdownPercentage() {
- if (!this.liveItem || !this.liveItem.duration) {
- return 0
- }
- if (this.hasReachedTarget || this.pointsRemainingTime <= 0) {
- console.log("这个比例是多少100",this.pointsRemainingTime)
- return 100
- }
- const completionTime = this.liveItem.duration * this.completionRate * 0.01;
- const watchedTime = this.totalWatchTime;
- if (watchedTime <= 0) {
- return 0
- }
- const percentage = (watchedTime / completionTime) * 100
- console.log("这个比例是多少计算",percentage)
- return Math.min(100, Math.max(0, percentage))
- },
- updateCountdownDisplay() {
- this.$forceUpdate()
- },
- initWatchTime() {
- const userId = this.userInfo?.userId || 'anonymous'
- this.watchTimeStorageKey = `watchTime_${userId}_${this.liveId}`
- try {
- const storedTime = uni.getStorageSync(this.watchTimeStorageKey)
- this.totalWatchTime = storedTime ? parseInt(storedTime) : 0
- console.log(`加载累计观看时间: ${this.totalWatchTime}秒`)
- } catch (error) {
- console.error('加载观看时间失败:', error)
- this.totalWatchTime = 0
- }
- },
- saveWatchTime() {
- if (!this.watchTimeStorageKey) return
- try {
- uni.setStorageSync(this.watchTimeStorageKey, this.totalWatchTime)
- console.log(`保存观看时间: ${this.totalWatchTime}秒`)
- } catch (error) {
- console.error('保存观看时间失败:', error)
- }
- },
- formatWatchTime(seconds) {
- const hours = Math.floor(seconds / 3600)
- const minutes = Math.floor((seconds % 3600) / 60)
- const secs = seconds % 60
- return {
- hours: this.padZero(hours),
- minutes: this.padZero(minutes),
- seconds: this.padZero(secs),
- total: seconds
- }
- },
- handleFullscreenChange(isFullscreen) {
- console.log('收到子组件全屏状态:', isFullscreen)
- this.isFullscreen = isFullscreen
- if (isFullscreen) {
- this.shopping = false
- this.isShowGift = false
- this.isMore = false
- this.showViewerList = false
- this.isShowLotteryPop = false
- this.winning = false
- this.isFocus = false
- }
- this.$nextTick(() => {
- this.$forceUpdate()
- })
- },
- onInputFocus(value) {
- this.isFocus = true
- console.log('输入框聚焦:', value)
- },
- onInputBlur(value) {
- this.isFocus = false
- console.log('输入框失焦:', value)
- },
- onSendMessage(message) {
- console.log('发送消息:', message)
- this.sendMsg()
- },
- onInputChange(value) {
- this.value = value
- },
- handleLiveStart() {
- console.log('直播开始')
- const userInfo = uni.getStorageSync('userInfo');
- const isLiveLogin = uni.getStorageSync('isLiveLogin')
- if (userInfo && isLiveLogin) {
- this.getliving(this.liveId)
- }
- },
- handleSearchInput(keyword) {
- this.inputInfo = keyword
- clearTimeout(this.searchTimer)
- this.searchTimer = setTimeout(() => {
- this.queryCollect()
- }, 500)
- },
- handleVideoError(error) {
- console.error('视频播放错误:', error)
- },
- handleLiveStateChange(state) {
- console.log('直播状态变化:', state)
- },
- handleNavigateToOrder() {
- this.navgetTo('/pages_shopping/live/order')
- },
- handleShowMore() {
- this.isMore = true
- this.shopping = false
- },
- handleFillAddress(data) {
- const {
- productId,
- recordId,
- liveId
- } = data
- this.winning = false
- this.navgetTo(
- `/pages_shopping/live/confirmCreateOrder?type=win&productId=${productId}&liveId=${liveId}&recordId=${recordId}`
- )
- },
- handleLotteryClose() {
- this.isShowLotteryPop = false
- },
- handleLotteryClaim() {
- this.onClaim()
- },
- handleGoShop(goodsData) {
- this.goShop(goodsData.productId, goodsData.goodsId)
- },
- handleCloseGoods() {
- this.isShowGoods = false
- },
- formatNumber(num) {
- if (typeof num !== 'number') {
- num = Number(num) || 0
- }
- if (num < 10000) {
- return num.toString()
- }
- const wan = num / 10000
- if (wan < 10) {
- const rounded = Math.round(wan * 100) / 100
- return rounded.toFixed(2).replace(/\.?0+$/, '') + 'w'
- } else if (wan < 10000) {
- const rounded = Math.round(wan * 10) / 10
- return rounded.toFixed(1).replace(/\.0$/, '') + 'w'
- } else {
- const yi = wan / 10000
- const rounded = Math.round(yi * 100) / 100
- return rounded.toFixed(2).replace(/\.?0+$/, '') + '亿'
- }
- },
- resetAllStates() {
- this.liveUserCalled = false
- this.talklist = []
- this.liveViewersData = []
- this.liveViewers = []
- this.products = []
- this.liveItem = null
- this.isSocketOpen = false
- this.isConnecting = false
- this.isManualClose = true
- this.reconnectCount = 0
- this.heartBeatRetryCount = 0
- this.lastHeartBeatTime = 0
- this.adaptiveHeartBeatInterval = this.heartBeatInterval
- this.isNetworkAvailable = true
- this.networkType = 'unknown'
- this.connectionStartTime = 0
- this.connectionLatency = 0
- this.messageCount = 0
- this.errorCount = 0
- this.lastPerformanceCheck = 0
- },
- getWebSocketPerformanceStats() {
- const now = Date.now()
- const uptime = this.connectionStartTime > 0 ? now - this.connectionStartTime : 0
- return {
- connectionLatency: this.connectionLatency,
- uptime: uptime,
- messageCount: this.messageCount,
- errorCount: this.errorCount,
- errorRate: this.messageCount > 0 ? (this.errorCount / this.messageCount * 100).toFixed(2) : 0,
- messagesPerSecond: uptime > 0 ? (this.messageCount / (uptime / 1000)).toFixed(2) : 0,
- networkType: this.networkType,
- isConnected: this.isSocketAvailable(),
- reconnectCount: this.reconnectCount
- }
- },
- performanceCheck() {
- const now = Date.now()
- if (now - this.lastPerformanceCheck > 300000) {
- const stats = this.getWebSocketPerformanceStats()
- console.log('WebSocket性能统计:', stats)
- this.lastPerformanceCheck = now
- if (stats.errorRate > 10) {
- console.warn(`WebSocket错误率过高: ${stats.errorRate}%`)
- }
- if (stats.connectionLatency > 5000) {
- console.warn(`WebSocket连接延迟过高: ${stats.connectionLatency}ms`)
- }
- }
- },
- startVideoCacheCleanup() {
- if (this.videoCleanupTimer) {
- clearInterval(this.videoCleanupTimer)
- }
- this.videoCleanupTimer = setInterval(() => {
- this.cleanupVideoCache()
- }, 30000)
- },
- cleanupVideoCache() {
- if (!this.liveItem || !this.liveId) return
- if (this.liveItem.liveType === 2 && this.liveItem.videoUrl) {
- this.reloadVideoPlayer()
- }
- },
- reloadVideoPlayer() {
- const videoId = `myVideo_${this.liveId}`
- const videoContext = uni.createVideoContext(videoId, this)
- if (videoContext) {
- const currentTime = this.videoCurrentTime
- videoContext.pause()
- setTimeout(() => {
- this.$set(this.liveItem, 'videoUrl', this.liveItem.videoUrl + '&t=' + Date.now())
- setTimeout(() => {
- if (videoContext.seek) {
- videoContext.seek(currentTime)
- }
- videoContext.play()
- }, 500)
- }, 100)
- }
- },
- startMemoryMonitoring() {
- if (this.memoryMonitorTimer) {
- clearInterval(this.memoryMonitorTimer)
- }
- this.memoryMonitorTimer = setInterval(() => {
- this.checkMemoryUsage()
- }, 15000)
- },
- checkMemoryUsage() {
- try {
- const timerCount = this.getActiveTimerCount()
- if (timerCount > 10) {
- console.warn(`检测到过多定时器: ${timerCount}个,可能存在内存泄漏`)
- this.cleanupUnusedTimers()
- }
- if (this.messageQueue && this.messageQueue.length > 100) {
- console.warn(`消息队列过长: ${this.messageQueue.length}条,清理旧消息`)
- this.messageQueue = this.messageQueue.slice(-50)
- }
- if (this.userRandomColors && Object.keys(this.userRandomColors).length > 500) {
- console.warn('用户颜色缓存过大,清理部分缓存')
- const keys = Object.keys(this.userRandomColors)
- const keysToRemove = keys.slice(0, keys.length - 200)
- keysToRemove.forEach(key => delete this.userRandomColors[key])
- }
- if (Date.now() - this.lastPerformanceCheck > 60000) {
- this.triggerGarbageCollection()
- this.lastPerformanceCheck = Date.now()
- }
- } catch (error) {
- console.error('内存检查失败:', error)
- }
- },
- forceMemoryCleanup() {
- console.log('执行强制内存清理')
- this.cleanupVideoPlayer()
- this.clearBigData()
- this.triggerGarbageCollection()
- },
- cleanupVideoPlayer() {
- const videoId = `myVideo_${this.liveId}`
- const videoContext = uni.createVideoContext(videoId, this)
- if (videoContext) {
- videoContext.stop()
- setTimeout(() => {
- this.$set(this.liveItem, 'videoUrl', '')
- setTimeout(() => {
- this.$set(this.liveItem, 'videoUrl', this.getFreshVideoUrl())
- if (this.$refs.liveVideo && this.$refs.liveVideo.playVideo) {
- this.$refs.liveVideo.playVideo()
- }
- }, 500)
- }, 100)
- }
- },
- getFreshVideoUrl() {
- if (!this.liveItem.originalVideoUrl) {
- this.liveItem.originalVideoUrl = this.liveItem.videoUrl
- }
- const separator = this.liveItem.originalVideoUrl.includes('?') ? '&' : '?'
- return this.liveItem.originalVideoUrl + separator + 't=' + Date.now()
- },
- clearBigData() {
- if (this.talklist && this.talklist.length > 50) {
- this.talklist = this.talklist.slice(-50)
- }
- if (this.liveViewersData && this.liveViewersData.length > 100) {
- this.liveViewersData = this.liveViewersData.slice(-100)
- }
- if (this.liveViewers && this.liveViewers.length > 100) {
- this.liveViewers = this.liveViewers.slice(-100)
- }
- if (this.products && this.products.length > 50) {
- this.products = this.products.slice(0, 50)
- }
- if (typeof gc === 'function') {
- gc()
- }
- },
- triggerGarbageCollection() {
- if (wx && wx.triggerGC) {
- wx.triggerGC()
- }
- },
- forceScrollToBottom() {
- console.log('执行强制滚动到底部')
- this.scrollTop = 999999
- this.$nextTick(() => {
- if (this.talklist && this.talklist.length > 0) {
- const lastMessage = this.talklist[this.talklist.length - 1]
- const targetId = `list_${lastMessage.uniqueId || (this.talklist.length - 1)}`
- console.log(
- `尝试滚动到元素: ${targetId}, 当前消息数量: ${this.talklist.length}, 最后消息ID: ${lastMessage.uniqueId}`
- )
- this.scrollIntoView = targetId
- setTimeout(() => {
- this.scrollIntoView = ''
- }, 200)
- }
- setTimeout(() => {
- this.scrollTop = 999999
- console.log('延迟设置scrollTop为999999')
- }, 100)
- setTimeout(() => {
- this.nativeScrollToBottom()
- }, 300)
- })
- },
- simpleScrollToBottom() {
- const now = Date.now()
- if (now - this.lastScrollTime < this.scrollDebounceDelay) {
- console.log('滚动防抖:忽略频繁调用')
- return
- }
- this.lastScrollTime = now
- console.log('执行可靠滚动到底部')
- if (this.scrollTimer) {
- clearTimeout(this.scrollTimer)
- this.scrollTimer = null
- }
- this.scrollTop = 999999999
- console.log('方案1: 设置scrollTop为999999999')
- if (this.talklist.length > 0) {
- const lastMessage = this.talklist[this.talklist.length - 1]
- if (lastMessage && lastMessage.uniqueId) {
- this.scrollIntoView = `msg-${lastMessage.uniqueId}`
- console.log(`方案2: 设置scrollIntoView为msg-${lastMessage.uniqueId}`)
- }
- }
- this.scrollTimer = setTimeout(() => {
- this.scrollTop = 999999999
- console.log('方案3: 延迟设置scrollTop为999999999')
- this.scrollTimer = null
- }, 50)
- },
- forceScrollToBottomOnSend() {
- console.log('执行强制滚动到底部(发送消息专用)')
- if (this.scrollTimer) {
- clearTimeout(this.scrollTimer)
- this.scrollTimer = null
- }
- this.lastScrollTime = Date.now()
- this.scrollIntoView = ''
- if (this.talklist.length > 0) {
- const lastMessage = this.talklist[this.talklist.length - 1]
- if (lastMessage && lastMessage.uniqueId) {
- this.scrollIntoView = `list_${lastMessage.uniqueId}`
- }
- }
- const targetScrollTop = Date.now()
- this.scrollTop = targetScrollTop
- this.nativeScrollToBottom()
- this.$nextTick(() => {
- this.scrollIntoView = ''
- this.scrollTop = targetScrollTop + 1
- setTimeout(() => {
- this.nativeScrollToBottom()
- }, 50)
- })
- this.scrollTimer = setTimeout(() => {
- this.checkAndForceScroll(targetScrollTop)
- this.scrollTimer = null
- }, 200)
- },
- checkAndForceScroll(targetScrollTop) {
- if (this.talklist.length > 0) {
- const lastMessage = this.talklist[this.talklist.length - 1]
- if (lastMessage && lastMessage.uniqueId) {
- this.scrollIntoView = `list_${lastMessage.uniqueId}`
- }
- }
- this.scrollTop = Date.now() + Math.random() * 1000
- this.nativeScrollToBottom()
- setTimeout(() => {
- this.nativeScrollToBottom()
- }, 100)
- },
- nativeScrollToBottom() {
- try {
- const query = uni.createSelectorQuery().in(this)
- query.select('#msgScroll').node((res) => {
- if (res && res.node) {
- console.log('找到msgScroll节点,执行原生滚动')
- const scrollHeight = res.node.scrollHeight
- res.node.scrollTop = scrollHeight
- setTimeout(() => {
- res.node.scrollTop = scrollHeight + 100
- }, 50)
- }
- }).exec()
- } catch (error) {
- console.error('原生滚动失败:', error)
- }
- },
- onScroll(e) {
- this.currentScrollTop = e.detail.scrollTop
- },
- stopMemoryMonitor() {
- if (this.memoryMonitorTimer) {
- clearInterval(this.memoryMonitorTimer)
- this.memoryMonitorTimer = null
- }
- },
- getActiveTimerCount() {
- const timers = [
- 'trafficTimer', 'pingTimeoutTimer', 'heartBeatTimer', 'liveViewDataTimer',
- 'reconnectTimer', 'scrollTimer', 'searchTimer', 'purchasePromptTimer',
- 'welcomeTimer', 'redTimer', 'liveStartTimer', 'lotteryTimer', 'noticeTimer',
- 'memoryMonitorTimer', 'networkStatusTimer', 'networkRetryTimer'
- ];
- return timers.filter(timer => this[timer] !== null).length
- },
- cleanupUnusedTimers() {
- const timers = [
- 'trafficTimer', 'pingTimeoutTimer', 'heartBeatTimer', 'liveViewDataTimer',
- 'reconnectTimer', 'scrollTimer', 'searchTimer', 'purchasePromptTimer',
- 'welcomeTimer', 'redTimer', 'liveStartTimer', 'lotteryTimer',
- 'networkStatusTimer', 'networkRetryTimer'
- ];
- timers.forEach(timerName => {
- if (this[timerName] && typeof this[timerName] === 'number') {
- if (timerName.includes('Interval')) {
- clearInterval(this[timerName])
- } else {
- clearTimeout(this[timerName])
- }
- this[timerName] = null
- console.log(`清理了可能泄漏的定时器: ${timerName}`)
- }
- })
- },
- clearAllTimersEnhanced() {
- this.clearAllTimers()
- if (this.networkRetryTimer) {
- clearTimeout(this.networkRetryTimer)
- this.networkRetryTimer = null
- }
- this.stopMemoryMonitor()
- this.userRandomColors = Object.create(null)
- this.shownEntryUsers.clear()
- this.messageCount = 0
- this.errorCount = 0
- this.connectionLatency = 0
- this.lastPerformanceCheck = 0
- console.log('增强清理完成:所有定时器和缓存已清理')
- },
- goOrder() {
- uni.navigateTo({
- url: '/pages_shopping/live/order'
- })
- },
- preventDoubleClick(e) {
- e.preventDefault();
- e.stopPropagation();
- return false
- },
- clearAllTimers() {
- const timers = [
- 'noticeTimer',
- 'scrollTimer',
- 'liveViewDataTimer',
- 'redTimer',
- 'liveStartTimer',
- 'lotteryTimer',
- 'welcomeTimer',
- 'trafficInterval',
- 'lookTimer',
- 'trafficTimer',
- 'intervalId',
- 'reconnectTimer',
- 'searchTimer',
- 'purchasePromptTimer',
- 'heartBeatTimer',
- 'pingTimeoutTimer'
- ]
- timers.forEach((timer) => {
- if (this[timer]) {
- if (timer.includes('Interval') || timer.includes('Timer')) {
- clearInterval(this[timer])
- } else {
- clearTimeout(this[timer])
- }
- this[timer] = null
- }
- })
- this.stayTime = 0
- this.startTime = 0
- this.totalTraffic = 0
- this.scrollPending = false
- this.reconnectCount = 0
- this.heartBeatRetryCount = 0
- },
- scrollToBottom() {
- const now = Date.now()
- if (now - this.lastScrollTime < this.scrollDebounceDelay) {
- console.log('滚动防抖:忽略频繁调用')
- return
- }
- this.lastScrollTime = now
- if (this.scrollTimer) {
- clearTimeout(this.scrollTimer)
- this.scrollTimer = null
- }
- this.scrollTop = 999999999
- },
- startMemoryMonitor() {
- if (this.memoryMonitorTimer) {
- clearInterval(this.memoryMonitorTimer)
- }
- this.memoryMonitorTimer = setInterval(() => {
- this.checkAndCleanMemory()
- }, 5 * 60 * 1000);
- },
- checkAndCleanMemory() {
- try {
- if (this.talklist && this.talklist.length > 25) {
- const keepCount = 20
- this.talklist.splice(0, this.talklist.length - keepCount)
- }
- if (this.userRandomColors && Object.keys(this.userRandomColors).length > 50) {
- const entries = Object.entries(this.userRandomColors)
- const keepEntries = entries.slice(-50)
- this.userRandomColors = Object.fromEntries(keepEntries)
- }
- if (this.shownEntryUsers && this.shownEntryUsers.size > 100) {
- const array = Array.from(this.shownEntryUsers)
- this.shownEntryUsers.clear()
- array.slice(-100).forEach((id) => this.shownEntryUsers.add(id))
- }
- console.log('内存清理完成')
- } catch (error) {
- console.error('内存清理失败:', error)
- }
- },
- async resumePageActivity() {
- if (this.liveItem) {
- const userInfo = uni.getStorageSync('userInfo');
- if (userInfo) {
- await this.getliving(this.liveId)
- }
- this.startTimeTimer(this.liveItem)
- }
- if (!this.isSocketAvailable()) {
- const userInfo = uni.getStorageSync('userInfo');
- if (userInfo) {
- this.initSocket()
- }
- }
- },
- getUserRandomColor(userId) {
- if (!userId) {
- return '#8978e2'
- }
- if (this.userRandomColors[userId]) {
- return this.userRandomColors[userId]
- }
- const color = this.generateStableColor(userId)
- this.userRandomColors[userId] = color
- this.saveUserColorsToStorage()
- return color
- },
- generateStableColor(userId) {
- let seed = 0
- for (let i = 0; i < userId.length; i++) {
- seed = (seed * 31 + userId.charCodeAt(i)) % 1000000
- }
- const colorPool = [
- '#FF6B6B',
- '#4ECDC4',
- '#45B7D1',
- '#96CEB4',
- '#FFEAA7',
- '#DDA0DD',
- '#98D8C8',
- '#F7DC6F',
- '#BB8FCE',
- '#85C1E9',
- '#F8C471',
- '#82E0AA',
- '#F1948A',
- '#85C1E9',
- '#D7BDE2'
- ]
- return colorPool[seed % colorPool.length]
- },
- saveUserColorsToStorage() {
- try {
- uni.setStorageSync('userRandomColors', this.userRandomColors)
- } catch (e) {
- console.warn('保存用户颜色缓存失败:', e)
- }
- },
- loadUserColorsFromStorage() {
- try {
- const cached = uni.getStorageSync('userRandomColors')
- if (cached) {
- this.userRandomColors = cached
- }
- } catch (e) {
- console.warn('加载用户颜色缓存失败:', e)
- }
- },
- getNicknameInitial(nickName) {
- if (!nickName || typeof nickName !== 'string') return '未'
- if (/^[\u4e00-\u9fa5]/.test(nickName[0])) {
- return nickName[0]
- }
- return nickName[0].toUpperCase()
- },
- async getUserInfo() {
- await getUserInfo().then((res) => {
- if (res.code == 200) {
- this.userData = res.user
- uni.setStorageSync('userData', res.user)
- } else {
- uni.showToast({
- icon: 'none',
- title: '请求失败'
- })
- }
- },
- (rej) => {}
- )
- },
- /**
- * 获取当前服务器时间戳(毫秒)
- * 如果存在 serviceTime,则基于服务器时间计算;否则使用本地时间
- */
- getServerTimeNow() {
- if (!this.liveItem || !this.liveItem.serviceTime) {
- return Date.now();
- }
- const localTimeWhenReceived = this.liveItem._localTimeWhenReceived;
- if (!localTimeWhenReceived) {
- // 如果没有记录接收时间,使用本地时间
- return Date.now();
- }
- let serverTimeWhenReceived;
- const serviceTime = this.liveItem.serviceTime;
- //如果 serviceTime 是数字类型(毫秒级时间戳)
- if (typeof serviceTime === 'number') {
- serverTimeWhenReceived = serviceTime;
- }
- //如果 serviceTime 是字符串格式的数字时间戳
- else if (typeof serviceTime === 'string' && /^\d+$/.test(serviceTime)) {
- // 纯数字字符串,转换为数字
- const numTime = Number(serviceTime);
- // 判断是秒级还是毫秒级时间戳(13位及以上为毫秒级)
- serverTimeWhenReceived = numTime < 1000000000000 ? numTime * 1000 : numTime;
- }
- //如果 serviceTime 是时间字符串
- else {
- const safeTimeStr = String(serviceTime).replace(/-/g, '/');
- serverTimeWhenReceived = Date.parse(safeTimeStr);
- if (isNaN(serverTimeWhenReceived)) {
- return Date.now();
- }
- }
- //计算服务器时间与本地时间的差值(毫秒)
- const timeDiff = serverTimeWhenReceived - localTimeWhenReceived;
- // 当前服务器时间 = 当前本地时间 + 时间差
- return Date.now() + timeDiff;
- },
- /**
- * 获取直播开始时间,优先使用 serviceStartTime,如果不存在则使用 startTime
- */
- getLiveStartTime() {
- if (!this.liveItem) {
- return null;
- }
- // 优先使用 serviceStartTime(服务器返回的直播开始时间)
- if (this.liveItem.serviceStartTime) {
- return this.liveItem.serviceStartTime;
- }
- // 如果不存在,回退到 startTime
- return this.liveItem.startTime || null;
- },
- handleAgreement() {
- const templateId = this.templateId
- if (this.hasSubscribed) return;
- uni.requestSubscribeMessage({
- tmplIds: [templateId],
- success: (res) => {
- if (res[templateId] === 'accept') {
- uni.showToast({
- title: '订阅成功,开播将提醒您',
- icon: 'success',
- duration: 2500 // 成功提示延长到2.5秒
- })
- this.hasSubscribed = true;
- uni.setStorageSync('subscribe_status_' + this.liveId, true);
- this.callSendMessageApi()
- } else if (res[templateId] === 'reject') {
- uni.showToast({
- title: '您已拒绝订阅,将无法收到提醒',
- icon: 'none',
- duration: 2500 // 成功提示延长到2.5秒
- })
- } else if (res[templateId] === 'ban') {
- uni.showToast({
- title: '您已关闭所有订阅权限,请在设置中开启',
- icon: 'none',
- duration: 2500 // 成功提示延长到2.5秒
- })
- }
- },
- fail: (err) => {
- console.error('订阅消息失败', err)
- uni.showToast({
- title: '订阅失败,请重试',
- icon: 'none',
- duration: 2500 // 成功提示延长到2.5秒
- })
- }
- })
- },
- async callSendMessageApi() {
- if (!this.userData.userId) return
- const templateData = {
- liveId: this.liveId,
- userId: this.userData.userId,
- templateId: this.templateId || '',
- maOpenId: this.userData.maOpenId || '',
- appid: this.appid || '',
- data: {
- thing6: this.liveItem.liveName,
- date7: this.liveItem.startTime
- }
- }
- subNotifyLive(templateData).then(
- (res) => {
- if (res.code == 200) {
- this.isAgreement = true
- uni.setStorageSync('isAgreement', true)
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- }
- },
- (rej) => {}
- )
- },
- sendHeartBeat() {
- if (!this.isSocketAvailable() || !this.isNetworkAvailable) {
- console.warn('网络不可用或Socket连接异常,跳过心跳发送')
- return
- }
- this.lastHeartBeatTime = Date.now()
- try {
- const heartBeatMsg = JSON.stringify({
- cmd: 'heartbeat',
- msg: 'ping',
- userId: this.userData.userId || '',
- liveId: this.liveId,
- timestamp: this.lastHeartBeatTime,
- networkType: this.networkType
- })
- this.socket.send({
- data: heartBeatMsg,
- success: () => {
- this.heartBeatRetryCount = 0
- this.adjustHeartBeatInterval(true)
- this.startPingTimeout()
- },
- fail: (err) => {
- console.error('心跳包发送失败:', err)
- this.heartBeatRetryCount++
- this.adjustHeartBeatInterval(false)
- const retryDelay = this.getRetryDelay()
- if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
- setTimeout(() => this.sendHeartBeat(), retryDelay)
- } else {
- this.heartBeatRetryCount = 0
- this.handleReconnect()
- }
- }
- })
- } catch (err) {
- console.error('心跳发送异常:', err)
- this.heartBeatRetryCount++
- const retryDelay = this.getRetryDelay()
- if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
- setTimeout(() => this.sendHeartBeat(), retryDelay)
- } else {
- this.heartBeatRetryCount = 0
- this.handleReconnect()
- }
- }
- },
- getRetryDelay() {
- const baseDelay = 2000
- const retryMultiplier = Math.pow(1.5, this.heartBeatRetryCount)
- let networkMultiplier = 1
- switch (this.networkType) {
- case '2g':
- networkMultiplier = 3
- break
- case '3g':
- networkMultiplier = 2
- break
- case '4g':
- case '5g':
- networkMultiplier = 1
- break
- case 'wifi':
- networkMultiplier = 0.8
- break
- default:
- networkMultiplier = 1.5
- }
- return Math.min(baseDelay * retryMultiplier * networkMultiplier, 10000)
- },
- adjustHeartBeatInterval(isSuccess) {
- if (isSuccess) {
- this.adaptiveHeartBeatInterval = Math.min(this.adaptiveHeartBeatInterval * 1.1, 30000)
- } else {
- this.adaptiveHeartBeatInterval = Math.max(this.adaptiveHeartBeatInterval * 0.9, 10000)
- }
- },
- startPingTimeout() {
- if (this.pingTimeoutTimer) {
- clearTimeout(this.pingTimeoutTimer)
- this.pingTimeoutTimer = null
- }
- this.pingTimeoutTimer = setTimeout(() => {
- console.warn('心跳超时,触发重连')
- this.pingTimeoutTimer = null
- this.heartBeatRetryCount++
- if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
- console.log(`心跳超时,尝试重发 (${this.heartBeatRetryCount}/${this.maxHeartBeatRetries})`)
- setTimeout(() => this.sendHeartBeat(), 1000)
- } else {
- console.log('心跳重试次数用尽,触发重连')
- this.heartBeatRetryCount = 0
- this.handleReconnect()
- }
- }, this.pingTimeout)
- },
- stopHeartBeat() {
- if (this.heartBeatTimer) {
- clearInterval(this.heartBeatTimer)
- this.heartBeatTimer = null
- }
- if (this.pingTimeoutTimer) {
- clearTimeout(this.pingTimeoutTimer)
- this.pingTimeoutTimer = null
- }
- },
- isSocketAvailable() {
- return this.socket && this.isSocketOpen && this.socket.readyState === 1
- },
- handleReconnect() {
- if (this.isManualClose) {
- console.log('手动关闭连接,不进行重连')
- return
- }
- if (this.reconnectTimer) {
- console.log('重连已在进行中,跳过重复重连')
- return
- }
- this.stopHeartBeat()
- if (!this.isNetworkAvailable) {
- console.warn('网络不可用,延迟重连')
- this.reconnectTimer = setTimeout(() => {
- this.reconnectTimer = null
- this.handleReconnect()
- }, 5000)
- return
- }
- if (this.reconnectCount < this.maxReconnectAttempts) {
- this.reconnectCount++
- const baseDelay = 1000
- const exponentialDelay = baseDelay * Math.pow(2, this.reconnectCount - 1)
- const jitter = Math.random() * 1000
- const totalDelay = Math.min(exponentialDelay + jitter, 30000)
- console.log(`第${this.reconnectCount}次重连,延迟${Math.round(totalDelay)}ms,网络类型:${this.networkType}`)
- this.reconnectTimer = setTimeout(() => {
- this.reconnectTimer = null
- if (this.isNetworkAvailable && !this.isManualClose && !this.isSocketAvailable()) {
- console.log('开始执行重连...')
- this.initSocket()
- } else if (this.isSocketAvailable()) {
- console.log('连接已恢复,取消重连')
- this.reconnectCount = 0
- } else {
- console.warn('重连时网络不可用或已手动关闭')
- this.handleReconnect()
- }
- }, totalDelay)
- } else {
- console.log(`已达最大重连次数(${this.maxReconnectAttempts}),停止重连`)
- this.showReconnectFailedMessage()
- }
- },
- showReconnectFailedMessage() {
- uni.showToast({
- title: '网络连接异常,请检查网络后重新进入',
- icon: 'none',
- duration: 3000
- })
- },
- handleConnectionError(errorType, error) {
- console.error(`WebSocket ${errorType}:`, error)
- if (errorType === '连接请求失败') {
- if (!this.isNetworkAvailable) {
- console.warn('网络不可用,等待网络恢复后重连')
- return
- }
- }
- this.handleReconnect()
- },
- resetReconnectState() {
- this.reconnectCount = 0
- this.heartBeatRetryCount = 0
- if (this.reconnectTimer) {
- clearTimeout(this.reconnectTimer)
- this.reconnectTimer = null
- }
- this.adaptiveHeartBeatInterval = this.heartBeatInterval
- },
- initNetworkStatusListener() {
- uni.getNetworkType({
- success: (res) => {
- this.networkType = res.networkType
- this.isNetworkAvailable = res.networkType !== 'none'
- console.log('当前网络类型:', res.networkType)
- }
- })
- uni.onNetworkStatusChange((res) => {
- const oldNetworkType = this.networkType
- const oldNetworkAvailable = this.isNetworkAvailable
- this.networkType = res.networkType
- this.isNetworkAvailable = res.isConnected
- console.log(`网络状态变化: ${oldNetworkType} -> ${res.networkType}, 连接状态: ${res.isConnected}`)
- if (!oldNetworkAvailable && res.isConnected) {
- console.log('网络恢复,尝试重连WebSocket')
- this.resetReconnectState()
- setTimeout(() => {
- if (!this.isSocketAvailable()) {
- this.initSocket()
- }
- }, 1000)
- }
- if (oldNetworkType !== res.networkType && res.isConnected) {
- this.adjustHeartBeatForNetworkType(res.networkType)
- }
- if (!res.isConnected) {
- console.warn('网络断开,停止心跳')
- this.stopHeartBeat()
- }
- })
- },
- adjustHeartBeatForNetworkType(networkType) {
- let newInterval = this.heartBeatInterval
- switch (networkType) {
- case '2g':
- newInterval = 30000
- break
- case '3g':
- newInterval = 20000
- break
- case '4g':
- case '5g':
- newInterval = 15000
- break
- case 'wifi':
- newInterval = 10000
- break
- default:
- newInterval = 15000
- }
- if (newInterval !== this.adaptiveHeartBeatInterval) {
- this.adaptiveHeartBeatInterval = newInterval
- console.log(`根据网络类型(${networkType})调整心跳间隔为${newInterval}ms`)
- if (this.heartBeatTimer && this.isSocketAvailable()) {
- this.startHeartBeat()
- }
- }
- },
- inputFocus() {
- this.isFocus = true
- this.isKeyboardShow = true
- },
- inputBlur() {
- this.isFocus = false
- },
- onRed() {
- if (!this.liveId) return
- if (!this.redInfo?.redId) return
- if (this.redTimer) {
- clearInterval(this.redTimer)
- this.redTimer = null
- }
- let data = {
- liveId: this.liveId,
- userId: this.userData.userId,
- redId: this.redInfo.redId
- }
- liveRed(data).then(
- (res) => {
- this.isShowRed = false
- this.redCard = res
- this.isShowRedCard = true
- },
- (rej) => {}
- )
- },
- onCoupon() {
- if (!this.couponInfo.couponIssueId) return
- let data = {
- goodsId: this.couponInfo.goodsId,
- couponIssueId: this.couponInfo.couponIssueId,
- liveId: this.liveId
- }
- coupon(data).then((res) => {
- this.isShowCoupon = false
- if (res.code == 200) {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- }
- }).catch((rej) => {})
- },
- getMyLottery() {
- this.winning = true
- myLottery()
- .then((res) => {
- if (res.code == 200) {
- this.prizeAll = res.data.list || {}
- } else {}
- })
- .catch((rej) => {})
- },
- onLottery() {
- if (!this.lotteryInfo) return
- let data = {
- lotteryId: this.lotteryInfo.lotteryId
- }
- liveLottery(data)
- .then((res) => {
- if (res.code == 200) {
- const resData = res.data || {}
- this.lotteryList = Array.isArray(resData) ? resData : []
- this.lotteryProducts = Array.isArray(resData.products) ? resData.products : []
- if (resData.duration) {
- this.isShowLotteryPop = true
- }
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- this.lotteryList = []
- this.lotteryProducts = []
- }
- })
- .catch((rej) => {
- uni.showToast({
- title: '获取抽奖信息失败',
- icon: 'none'
- })
- this.lotteryList = []
- this.lotteryProducts = []
- })
- },
- onClaim() {
- let data = {
- liveId: this.liveId,
- lotteryId: this.lotteryInfo.lotteryId
- }
- claim(data).then(
- (res) => {
- if (res.code == 200) {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- this.isShowLotteryPop = false
- this.havePrize = true
- uni.setStorageSync('havePrize', this.havePrize)
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- }
- },
- (rej) => {}
- )
- },
- confirm() {
- this.isShowPrize = false
- this.havePrize = false
- uni.setStorageSync('havePrize', this.havePrize)
- },
- onGoodsCollect(item) {
- if (!item || item.length === 0 || !item.goodsId) {
- return
- }
- collectGoods(item.goodsId).then(
- (res) => {
- if (res.code == 200) {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- item.isFavorite = !item.isFavorite
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- }
- },
- (rej) => {}
- )
- },
- handleGoShopFromCart(item) {
- this.goShop(item.productId, item.goodsId)
- },
- getliveOrder(item) {
- if (!this.liveId) {
- return
- }
- liveOrderUser(this.liveId).then(
- (res) => {
- if (res.code == 200) {
- this.orderUser = res
- } else {
- console.log('获取正在购买用户失败')
- }
- },
- (rej) => {}
- )
- },
- onLiveStateChange(e, liveItem) {
- const stateCode = e.detail.code
- if (e.detail.code == -2301 || e.detail.code == -2302) {
- if (this.$refs.liveVideo && this.$refs.liveVideo.playVideo) {
- this.$refs.liveVideo.playVideo()
- }
- } else if (e.detail.code == 2004) {
- this.calculateTimeDiff(this.liveItem)
- if (this.$refs.liveVideo && this.$refs.liveVideo.startTrafficCalculation) {
- this.$refs.liveVideo.startTrafficCalculation()
- }
- }
- },
- onLiveError(e, liveItem) {
- this.videoError(e, liveItem)
- console.log('错误')
- },
- getCurrentActivities() {
- if (!this.liveId) return
- currentActivities(this.liveId).then(
- (res) => {
- if (res.code === 200) {
- this.redInfo = (Array.isArray(res.red) ? res.red : [])[0] || {}
- this.lotteryInfo = (Array.isArray(res.lottery) ? res.lottery : [])[0] || {}
- this.goodsCard = res.goods || {}
- this.notice = res.topMsg || {}
- this.isShowGoods = this.goodsCard && this.goodsCard.status == 1
- this.isShowRed = this.redInfo && this.redInfo.redStatus == 1
- this.isShowLottery = this.lotteryInfo && this.lotteryInfo.lotteryStatus == 1
- if (this.isShowRed) {
- this.redTimer = setInterval(() => {
- const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo
- .duration)
- if (!redCountdown) {
- this.isShowRed = false
- clearInterval(this.redTimer)
- }
- }, 1000)
- }
- if (this.notice.msg) {
- this.noticeTimer = setInterval(() => {
- const noticeCountdown = this.handleTime(this.notice.endTime, 0)
- console.log('出现1>>>', noticeCountdown)
- if (!noticeCountdown) {
- this.isShowNotice = false
- clearInterval(this.noticeTimer)
- } else {
- this.isShowNotice = true
- }
- }, 1000)
- }
- if (this.isShowLottery) {
- this.lotteryTimer = setInterval(() => {
- this.countdown = this.handleTime(this.lotteryInfo.updateTime, this
- .lotteryInfo.duration)
- }, 1000)
- }
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- }
- },
- (rej) => {}
- )
- },
- calculateTimeDiff(item) {
- if (!item.startTime) return
- let timeStr = item.startTime
- const time = new Date(timeStr.replace(/-/g, '/'))
- if (isNaN(time.getTime())) {
- return
- }
- const now = new Date()
- let diffMs = Math.max(0, now.getTime() - time.getTime())
- const totalSeconds = Math.floor(diffMs / 1000)
- const hours = this.padZero(Math.floor(totalSeconds / 3600))
- const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60))
- const seconds = this.padZero(totalSeconds % 60)
- this.diffTotalTime = `${hours}:${minutes}:${seconds}`
- },
- padZero(num) {
- return num < 10 ? `0${num}` : num
- },
- startTimeTimer(item) {
- if (!item) return
- const totalTime = this.calculateTimeDiff(item)
- item.timeTimer = setInterval(() => {
- const totalTime = this.calculateTimeDiff(item)
- }, 1000);
- },
-
-
- async getLiveMsg(liveItem) {
- if (!liveItem || !this.liveId) {
- console.error('getLiveMsg 错误:无效的 liveItem')
- return
- }
- try {
- const res = await liveMsg(this.liveId, 30, 1)
- if (res.code == 200) {
- const rows = Array.isArray(res.rows) ? res.rows : []
- const reversedTalkList = [...rows].reverse()
- this.talklist = Array.isArray(reversedTalkList) ? reversedTalkList : []
- this.$nextTick(() => {
- this.scrollToBottom()
- })
- } else {
- this.talklist = []
- }
- } catch (error) {
- this.talklist = []
- console.error('获取聊天记录失败:', error)
- }
- },
- generateRandomChineseName() {
- const prefixes = [
- '幸福', '快乐', '安康', '吉祥', '如意', '平安', '健康', '长寿', '福气', '美满',
- '和谐', '团圆', '富贵', '荣华', '宁静', '淡泊', '知足', '常乐', '悠然', '自在',
- '夕阳', '晚霞', '金秋', '银发', '老顽童', '开心', '笑口常开', '岁月静好', '云淡风轻', '海阔天空'
- ]
- const suffixes = [
- '老人', '大爷', '大妈', '爷爷', '奶奶', '伯伯', '阿姨', '前辈', '先生', '女士',
- '长者', '翁', '婆', '哥', '姐', '友', '客', '迷', '粉丝', '达人',
- '爱好者', '之家', '之人', '之心', '之情', '之乐', '之旅', '之梦', '之歌', '之韵'
- ]
- const specialNames = [
- '老有所乐', '知足常乐', '笑看人生', '云淡风轻', '岁月如歌', '夕阳红', '金色年华', '老当益壮',
- '鹤发童颜', '老骥伏枥', '闲云野鹤', '淡泊明志', '宁静致远', '随遇而安', '顺其自然',
- '老来俏', '开心果', '老宝贝', '不老松', '常青树'
- ]
- if (Math.random() < 0.3) {
- return specialNames[Math.floor(Math.random() * specialNames.length)]
- } else {
- const prefix = prefixes[Math.floor(Math.random() * prefixes.length)]
- const suffix = suffixes[Math.floor(Math.random() * suffixes.length)]
- return prefix + suffix
- }
- },
- async getliveUser(isLoadMore = false) {
- if (!isLoadMore) {
- this.liveViewers = []
- this.viewPageNum = 1
- }
- this.viewLoading = true;
- try {
- const res = await watchUserList(this.liveId, this.viewPageSize, this.viewPageNum, false);
- console.log("qxj watchUserList res", res);
- if (res.code === 200) {
- const newRows = Array.isArray(res.rows) ? res.rows : []
- const newViewers = newRows.map((item) => ({
- avatar: item.avatar || '',
- userId: item.userId || '',
- nickName: item.nickName || '未命名'
- }));
- let virtualData = [];
- // 计算虚拟总数
- let virtualTotal = res.total * 2 + 50;
- // 计算需要生成的虚拟数据数量
- let totalVirtualNeeded = virtualTotal - res.total;
- totalVirtualNeeded = Math.max(0, Math.min(totalVirtualNeeded, 90)); // 最多生成90条虚拟数据
- if (!isLoadMore) {
- // 首次加载时,生成第一批虚拟数据(与真实数据合计不超过10个)
- let firstBatchVirtualCount = Math.max(0, 10 - newRows.length);
- for (let i = 0; i < firstBatchVirtualCount; i++) {
- let data = {
- avatar: '',
- userId: '8565' + i,
- nickName: this.generateRandomChineseName()
- }
- virtualData.push(data);
- }
- this.liveViewersData = [...newViewers, ...virtualData];
- } else {
- // 后续加载时,计算已加载的虚拟数据数量
- let loadedVirtualCount = this.liveViewers.filter(v => String(v.userId).startsWith('8565'))
- .length;
- // 计算还需要加载的虚拟数据数量
- let remainingVirtualCount = totalVirtualNeeded - loadedVirtualCount;
- // 本次加载的虚拟数据数量(最多10个)
- let currentBatchVirtualCount = Math.min(remainingVirtualCount, this.viewPageSize);
- // 生成本次加载的虚拟数据
- for (let i = 0; i < currentBatchVirtualCount; i++) {
- let data = {
- avatar: '',
- userId: '8565' + (loadedVirtualCount + i),
- nickName: this.generateRandomChineseName()
- }
- virtualData.push(data);
- }
- }
- // 过滤掉旧列表中的虚拟数据,保留真实用户
- let currentRealViewers = isLoadMore ? this.liveViewers.filter(v => !String(v.userId)
- .startsWith('8565')) : [];
- // 合并真实用户
- let allRealViewers = [...currentRealViewers, ...newViewers];
- // 合并虚拟用户
- let currentVirtualViewers = isLoadMore ? this.liveViewers.filter(v => String(v.userId)
- .startsWith('8565')) : [];
- let allVirtualViewers = [...currentVirtualViewers, ...virtualData];
- // 合并所有用户
- let mergedViewers = [...allRealViewers, ...allVirtualViewers];
- // 确保观众列表不超过100个
- if (mergedViewers.length > 100) {
- mergedViewers = mergedViewers.slice(0, 100);
- }
- this.liveViewers = mergedViewers;
- // 检查虚拟数据是否还有剩余
- let totalLoaded = allRealViewers.length + allVirtualViewers.length;
- let remainingVirtualCount = totalVirtualNeeded - allVirtualViewers.length;
- // 计算是否还有更多数据
- // 1. 如果真实用户还有更多
- // 2. 或者虚拟数据还有剩余
- // 3. 但不超过100个
- let hasMore = ((newRows.length >= this.viewPageSize) || (remainingVirtualCount > 0)) && (
- totalLoaded < 100);
- // 确保即使真实用户数据加载完毕,只要虚拟数据还有剩余且未超过100个,就继续加载
- if (remainingVirtualCount > 0 && totalLoaded < 100) {
- hasMore = true;
- }
- if (totalLoaded >= virtualTotal || totalLoaded >= 100) {
- hasMore = false;
- this.lookAudsCount = Math.max(0, virtualTotal - 100);
- } else {
- this.lookAudsCount = 0;
- }
- if (this.$refs.viewer) {
- this.$refs.viewer.endSuccess(newRows.length + virtualData.length, hasMore);
- }
- } else {
- if (this.$refs.viewer) this.$refs.viewer.endErr();
- }
- } catch (error) {
- console.error('获取观众列表失败:', error)
- if (this.$refs.viewer) this.$refs.viewer.endErr();
- } finally {
- this.viewLoading = false
- }
- },
- async getliveUserInit(isLoadMore = false) {
- try {
- const res = await watchUserList(this.liveId, this.viewPageSize, 1, false);
- console.log("qxj watchUserList res", res);
- if (res.code === 200) {
- const userRows = Array.isArray(res.rows) ? res.rows : []
- let array = userRows.map((item) => ({
- avatar: item.avatar || '',
- userId: item.userId || '',
- nickName: item.nickName || '未命名'
- }));
- // let virtualTotal = res.total * 2 + 50;
- // // 使用虚拟的观众总数
- // this.liveUserTotal = virtualTotal || 0;
- this.liveUserTotal = res.total;
- this.liveTopViewersData = [...array];
- }
- } catch (error) {
- console.error('获取观众列表失败:', error)
- } finally {}
- },
- showPurchaseMessage() {
- if (this.purchasePromptTimer) {
- clearTimeout(this.purchasePromptTimer)
- }
- this.showPurchasePrompt = true
- this.purchasePromptTimer = setTimeout(() => {
- this.showPurchasePrompt = false
- }, 2000)
- },
- truncateString(str, maxLength) {
- if (typeof str !== 'string' || str.length <= maxLength) {
- return str
- }
- return str.slice(0, maxLength) + '...'
- },
- navgetTo(url) {
- uni.navigateTo({
- url: url
- })
- },
- async getliving(liveId) {
- if (!liveId) return
- const param = {
- id: liveId
- }
- try {
- const res = await getlive(param)
- if (res.code !== 200) {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- return
- }
- this.liveItem = Object.assign({}, this.liveItem, res.data)
- // 保存服务器时间对应的本地时间,用于计算服务器时间差值
- if (res.serviceTime) {
- this.liveItem._localTimeWhenReceived = Date.now();
- this.$set(this.liveItem, 'serviceTime', res.serviceTime);
- }
- if (res.serviceStartTime) {
- this.$set(this.liveItem, 'serviceStartTime', res.serviceStartTime);
- }
- this.startTimeTimer(this.liveItem)
- if (this.liveStartTimer) {
- clearInterval(this.liveStartTimer)
- this.liveStartTimer = null
- }
- if (res.data.status == 1) {
- this.liveStartTimer = setInterval(async () => {
- this.liveCountdown = this.handleTime(res.data.startTime, 0)
- if (!this.liveCountdown) {
- uni.removeStorageSync('isAgreement')
- const userInfo = uni.getStorageSync('userInfo');
- if (userInfo) {
- await this.getliving(this.liveId)
- }
- clearInterval(this.liveStartTimer)
- }
- }, 1000)
- this.$set(this.liveItem, 'previewUrl', res.data.previewUrl)
- this.$set(this.liveItem, 'livingUrl', '')
- this.$set(this.liveItem, 'videoUrl', '')
- } else if (res.data.status == 2) {
- if (res.data.liveType == 1) {
- let cTime = Math.floor(Math.random() * 10000) + 1
- let livingUrl = res.data.flvHlsUrl + '&t=' + cTime
- this.$set(this.liveItem, 'livingUrl', livingUrl)
- this.$set(this.liveItem, 'videoUrl', '')
- } else if (res.data.liveType === 2) {
- this.$set(this.liveItem, 'videoUrl', res.data.videoUrl)
- this.$set(this.liveItem, 'livingUrl', '')
- }
- } else if (res.data.status == 4 && res.data.liveType == 3) {
- this.$set(this.liveItem, 'videoUrl', res.data.videoUrl)
- this.$set(this.liveItem, 'livingUrl', '')
- } else {
- this.$set(this.liveItem, 'livingUrl', '')
- this.$set(this.liveItem, 'videoUrl', '')
- }
-
- this.$set(this.liveItem, 'autoplay', res.data.liveType !== 0)
- this.$set(this.liveItem, 'showType', res.data.showType)
- this.storeId = res.storeId
- this.diffLiveStartTime = this.calculateLiveTimeDiff(this.liveItem.startTime);
- if (this.diffLiveStartTime < 0) { //预告
- this.isPreview = true;
- this.liveBeginWatchTime = this.getServerTimeNow();
- } else {
- if (!this.hasLiveEnd) { //没经历过直播结束
- this.liveBeginWatchTime = this.getServerTimeNow();
- }
- }
- console.log("是否调用积分列表", this.liveItem.completionPointsEnabled)
- if (this.liveItem.completionPointsEnabled) {
- this.getRemainingTime()
- }
- // 初始化累计观看时间
- this.initWatchTime();
- this.startLiveViewDataTimer()
- if (this.$refs.liveVideo && this.$refs.liveVideo.playVideo) {
- this.$refs.liveVideo.playVideo()
- }
- } catch (err) {
- console.error('获取直播信息失败:', err)
- uni.showToast({
- title: '获取直播信息失败',
- icon: 'none'
- })
- }
- },
- getPureDecimal(num, precision = 6) {
- const decimalPart = Math.abs(num).toFixed(precision).split('.')[1]
- return decimalPart?.replace(/0+$/, '') || ''
- },
- goBack() {
- if (this.liveItem) {
- if (this.$refs.liveVideo && this.$refs.liveVideo.pauseVideo) {
- this.$refs.liveVideo.pauseVideo()
- }
- }
- this.closeWebSocket(true)
- const pages = getCurrentPages()
- if (pages.length > 1) {
- uni.navigateBack()
- } else {
- uni.reLaunch({
- url: '/pages_course/livingList'
- })
- }
- },
- async onLike() {
- if (!this.liveId) return
- try {
- const res = await liveDataLike(this.liveId)
- if (res?.like) {
- this.liveViewData.like++
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- })
- }
- } catch (error) {
- console.error('点赞失败:', error)
- }
- },
- getliveViewData() {
- if (!this.liveId) return
- getLiveViewData(this.liveId).then((res) => {
- if (res.code == 200) {
- this.liveViewData = res
- }
- }).catch((error) => {
- console.error('获取直播间数据失败:', error)
- this.liveViewData = {
- like: 0,
- watchCount: 0
- }
- })
- },
- startLiveViewDataTimer() {
- if (this.liveViewDataTimer) {
- clearInterval(this.liveViewDataTimer)
- this.liveViewDataTimer = null
- }
- this.getliveViewData()
- this.liveViewDataTimer = setInterval(() => {
- if (this.liveId) {
- this.getliveViewData()
- }
- }, 20000)
- },
- goShop(productId, goodsId) {
- if (!this.liveId) return
- uni.navigateTo({
- url: '/pages_shopping/live/goods?productId=' + productId + '&liveId=' + this.liveId +
- '&goodsId=' + goodsId + '&storeId=' + this.storeId
- })
- },
- async queryCollect() {
- this.loadingProducts = true
- if (!this.liveId) return
- if (this.inputInfo == null) this.inputInfo = ''
- uni.showLoading({
- title: '加载中'
- })
- try {
- const res = await liveStore(this.liveId, this.inputInfo)
- uni.hideLoading()
- this.shopping = true
- if (res.code === 200) {
- this.products = Array.isArray(res.data) ? res.data : []
- }
- } catch (error) {
- console.error('获取小黄车商品失败:', error)
- } finally {
- this.loadingProducts = false
- }
- },
- initTime() {
- const now = new Date()
- this.timestamp = now.getTime()
- },
- showGift() {
- this.isShowGift = true
- },
- clearChatInput() {
- this.$refs.chatInput.clearInput()
- },
- openCart() {
- this.queryCollect()
- },
- closeGift() {
- this.isShowGift = false
- },
- closeShop() {
- this.shopping = false
- },
- closeMore() {
- this.isMore = false
- },
- closeWin() {
- this.winning = false
- },
- closeWebSocket(isManual = true) {
- if (!this.socket || !this.isSocketOpen) {
- console.warn('WebSocket 任务不存在或未打开,无需关闭')
- return
- }
- console.log(`WebSocket连接关闭 - ${isManual ? '手动' : '自动'}`)
- this.isManualClose = isManual
- this.cleanupAllResources()
- try {
- const socketToClose = this.socket
- this.socket = null
- this.isSocketOpen = false
- this.isConnecting = false
- socketToClose.close({
- code: 1000,
- reason: isManual ? '主动关闭' : '异常关闭'
- })
- console.log('WebSocket连接已发起关闭')
- } catch (err) {
- console.error('关闭WebSocket失败:', err)
- this.socket = null
- this.isSocketOpen = false
- this.isConnecting = false
- }
- },
- cleanupAllResources() {
- this.stopHeartBeat()
- if (this.pingTimeoutTimer) {
- clearTimeout(this.pingTimeoutTimer)
- this.pingTimeoutTimer = null
- }
- if (this.networkStatusTimer) {
- clearTimeout(this.networkStatusTimer)
- this.networkStatusTimer = null
- }
- this.resetReconnectState()
- this.heartBeatRetryCount = 0
- this.lastHeartBeatTime = 0
- this.adaptiveHeartBeatInterval = this.heartBeatInterval
- },
- startHeartBeat() {
- this.stopHeartBeat()
- this.heartBeatTimer = setInterval(() => {
- this.sendHeartBeat()
- }, this.adaptiveHeartBeatInterval)
- },
- initSocket() {
- if (this.isConnecting) {
- console.log('WebSocket正在连接中,跳过重复连接')
- return
- }
- if (!this.isNetworkAvailable) {
- console.warn('网络不可用,延迟WebSocket连接')
- if (!this.networkRetryTimer) {
- this.networkRetryTimer = setTimeout(() => {
- this.networkRetryTimer = null
- this.initSocket()
- }, 3000)
- }
- return
- }
- if (this.socket && this.socket.readyState === 1) {
- console.log('WebSocket连接已存在且正常,无需重新连接')
- this.reconnectCount = 0
- return
- }
- if (this.socket && (this.socket.readyState === 0 || this.socket.readyState === 1)) {
- console.log('关闭现有WebSocket连接,创建新连接')
- this.closeWebSocket(false)
- setTimeout(() => {
- this.createWebSocketConnection()
- }, 100)
- return
- }
- this.createWebSocketConnection()
- },
- createWebSocketConnection() {
- if (!this.liveId) {
- console.error('缺失直播间ID,无法初始化WebSocket')
- return
- }
- if (!this.userData || !this.userData.userId) {
- console.error('用户信息缺失,无法初始化WebSocket')
- return
- }
- this.isConnecting = true
- this.isSocketOpen = false
- this.connectionStartTime = Date.now()
- this.resetReconnectState()
- setTimeout(() => {
- this.getliveUserInit(false)
- }, 200)
- const now = new Date()
- this.timestamp = now.getTime()
- const signature = CryptoJS.HmacSHA256(
- `${this.liveId}${this.userData.userId}${this.userType}${this.timestamp}`, this.timestamp.toString()
- ).toString(CryptoJS.enc.Hex)
- try {
- const baseWsUrl = 'wss://im.fhhx.runtzh.com/ws/app/webSocket'
- let wsUrl =
- `${baseWsUrl}?userId=${this.userData.userId}&liveId=${this.liveId}&userType=${this.userType}×tamp=${this.timestamp}&signature=${signature}`
- if (this.qrFrom) {
- wsUrl += this.qrFrom
- }
- console.log('qxj wsUrl', wsUrl)
- const socketTask = uni.connectSocket({
- url: wsUrl,
- success: () => {
- console.log('WebSocket连接请求发送成功')
- },
- fail: (err) => {
- console.error('WebSocket连接请求失败:', err)
- this.isConnecting = false
- this.handleConnectionError('连接请求失败', err)
- }
- })
- socketTask.onOpen((res) => {
- console.log('WebSocket连接已打开')
- this.socket = socketTask
- this.isConnecting = false
- this.isSocketOpen = true
- if (this.connectionStartTime > 0) {
- this.connectionLatency = Date.now() - this.connectionStartTime
- console.log(`WebSocket连接延迟: ${this.connectionLatency}ms`)
- }
- this.reconnectCount = 0
- this.resetReconnectState()
- this.heartBeatRetryCount = 0
- this.shownEntryUsers.clear()
- if (this.reconnectCount === 0) {
- console.log('WebSocket连接建立成功')
- } else {
- console.log(`WebSocket重连成功(第${this.reconnectCount}次尝试)`)
- }
- this.startHeartBeat()
- })
- socketTask.onMessage((res) => {
- this.messageCount++
- try {
- const data = JSON.parse(res.data)
- if (!!data.data && data.data.cmd === 'heartbeat') {
- if (this.pingTimeoutTimer) {
- clearTimeout(this.pingTimeoutTimer)
- this.pingTimeoutTimer = null
- }
- this.heartBeatRetryCount = 0
- this.adjustHeartBeatInterval(true)
- return
- }
- this.handleSocketMessage(res)
- } catch (err) {
- console.error('消息解析异常:', err)
- this.errorCount++
- }
- })
- socketTask.onError((err) => {
- console.error('WebSocket连接错误:', err)
- this.errorCount++
- this.isSocketOpen = false
- this.isConnecting = false
- this.stopHeartBeat()
- this.handleConnectionError('连接错误', err)
- })
- socketTask.onClose((res) => {
- console.log('WebSocket连接关闭:', res)
- this.isSocketOpen = false
- this.isConnecting = false
- this.stopHeartBeat()
- if (!this.isManualClose) {
- if (res.code === 1000) {
- console.log('WebSocket正常关闭,不进行重连')
- } else {
- console.warn(`WebSocket异常关闭 (code: ${res.code}, reason: ${res.reason})`)
- this.handleReconnect()
- }
- } else {
- console.log('WebSocket手动关闭,不进行重连')
- }
- })
- } catch (e) {
- console.error('创建WebSocket异常:', e)
- this.handleReconnect()
- }
- },
- handleTime(time, duration) {
- let timeStamp
- if (typeof time === 'number' && time > 0 && time < 9999999999999) {
- timeStamp = time
- } else if (typeof time === 'string' && time.trim() !== '') {
- const match = time.match(/^(\w{3}) (\w{3}) (\d{1,2}) (\d{1,2}):(\d{2}):(\d{2}) CST (\d{4})$/)
- if (match) {
- const [, day, month, date, hours, minutes, seconds, year] = match
- const monthMap = {
- 'Jan': 0,
- 'Feb': 1,
- 'Mar': 2,
- 'Apr': 3,
- 'May': 4,
- 'Jun': 5,
- 'Jul': 6,
- 'Aug': 7,
- 'Sep': 8,
- 'Oct': 9,
- 'Nov': 10,
- 'Dec': 11
- }
- const jsDate = new Date(
- parseInt(year),
- monthMap[month],
- parseInt(date),
- parseInt(hours),
- parseInt(minutes),
- parseInt(seconds)
- )
- timeStamp = jsDate.getTime()
- } else {
- let normalizedTime = time
- if (normalizedTime.includes(' ')) {
- normalizedTime = normalizedTime.replace(' ', 'T')
- }
- const date = new Date(normalizedTime)
- if (!isNaN(date.getTime())) {
- timeStamp = date.getTime()
- } else {
- console.error('无效的日期格式:', time)
- return false
- }
- }
- } else {
- console.error('time参数必须是有效的时间戳(数字)或日期字符串')
- return false
- }
- const targetTimestamp = timeStamp + duration * 60 * 1000
- const currentTimestamp = Date.now()
- const timeDiffMs = targetTimestamp - currentTimestamp
- if (timeDiffMs <= 0) {
- return false
- }
- const hours = Math.floor(timeDiffMs / (1000 * 60 * 60))
- const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60))
- const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000)
- const formatNum = (num) => num.toString().padStart(2, '0')
- return {
- hours: formatNum(hours),
- minutes: formatNum(minutes),
- seconds: formatNum(seconds)
- }
- },
- addToTalkList(message) {
- const MAX_TALK_ITEMS = 30
- if (!Array.isArray(this.talklist)) {
- this.talklist = []
- }
- const wasAtLimit = this.talklist.length >= MAX_TALK_ITEMS
- const isMyMessage = message.userId === this.userData.userId
- try {
- message.uniqueId = ++this.messageIdCounter
- let msgdata = {}
- try {
- msgdata = JSON.parse(message.data)
- } catch (e) {
- console.warn('JSON解析失败:', e)
- msgdata = {}
- }
- message.msgId = msgdata.msgId || Date.now()
- this.talklist.push(message)
- } catch (error) {
- console.error('处理消息时出错:', error)
- }
- if (this.talklist.length > MAX_TALK_ITEMS) {
- const removeCount = this.talklist.length - MAX_TALK_ITEMS
- this.talklist.splice(0, removeCount)
- }
- this.$forceUpdate()
- this.$nextTick(() => {
- this.forceScrollToBottomOnSend()
- })
- },
- async handleSocketMessage(message) {
- try {
- let data = JSON.parse(message.data)
- const socketMessage = data.data
- if (data.code == 200) {
- const messageData = {
- ...socketMessage,
- cmd: socketMessage.cmd || '',
- ts: Date.now()
- }
- if (socketMessage.cmd == 'sendMsg') {
- if (!this.isSocketAvailable()) {
- uni.showToast({
- title: '连接已断开,正在重试...',
- icon: 'none'
- })
- this.handleReconnect()
- return
- }
- this.addToTalkList(messageData)
- } else if (socketMessage.cmd == 'red') {
- const redData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
- this.redInfo = redData || {}
- this.isShowRed = socketMessage.status === 1
- if (this.isShowRed) {
- this.redTimer = setInterval(() => {
- const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo
- .duration)
- if (!redCountdown) {
- this.isShowRed = false
- clearInterval(this.redTimer)
- }
- }, 1000)
- }
- } else if (socketMessage.cmd == 'goods') {
- try {
- const goodsData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
- this.goodsCard = goodsData || {}
- this.isShowGoods = Number(socketMessage.status) === 1
- console.log('商品卡片数据:', {
- goodsData,
- status: socketMessage.status,
- isShowGoods: this.isShowGoods
- });
- } catch (err) {
- console.error('解析商品卡片数据失败:', err);
- this.goodsCard = {};
- this.isShowGoods = false;
- }
- // 确保在所有平台上都能正确显示商品卡片
- this.$nextTick(() => {
- if (this.isShowGoods) {
- console.log('商品卡片显示状态已更新:', this.isShowGoods);
- }
- });
- } else if (socketMessage.cmd == 'coupon') {
- const couponData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
- this.couponInfo = couponData || {}
- this.isShowCoupon = socketMessage.status === 1
- } else if (socketMessage.cmd == 'likeDetail') {
- this.liveViewData.like = socketMessage.data
- } else if (socketMessage.cmd == 'lottery') {
- const lotteryData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
- this.lotteryInfo = lotteryData || {}
- this.isShowLottery = socketMessage.status === 1
- if (socketMessage.status != 1) {
- this.isShowLotteryPop = false
- }
- clearTimeout(this.lotteryTimer)
- if (this.isShowLottery) {
- this.lotteryTimer = setInterval(() => {
- this.countdown = this.handleTime(this.lotteryInfo.updateTime, this
- .lotteryInfo.duration)
- if (!this.countdown) {
- console.log('倒计时', this.countdown)
- this.isShowLottery = false
- this.isShowLotteryPop = false
- clearInterval(this.lotteryTimer)
- }
- }, 1000)
- } else {
- this.isShowLottery = false
- }
- } else if (socketMessage.cmd == 'deleteMsg') {
- const index = this.talklist.findIndex(item => item.msgId == socketMessage.msg)
- if (index !== -1) {
- this.talklist.splice(index, 1)
- }
- } else if (socketMessage.cmd == 'globalVisible') {} else if (socketMessage.cmd ==
- 'singleVisible') {} else if (socketMessage.cmd == 'entry') {
- try {
- //if (!this.liveUserCalled) {
- await this.getliveUserInit(false)
- this.liveUserCalled = true;
- //}
- const userIdToEntry = socketMessage.userId
- const existingIndex = this.liveViewersData.findIndex((item) => item.userId ===
- userIdToEntry);
- if (existingIndex === -1) {
- const liveViewers = {
- userId: socketMessage.userId,
- nickName: socketMessage.nickName,
- avatar: socketMessage.avatar
- }
- this.liveViewersData.push(liveViewers)
- this.liveUserTotal++
- }
- const userData = JSON.parse(socketMessage.data || '{}')
- const userId = userData.userId || socketMessage.userId
- if (!userId) return
- if (!this.shownEntryUsers.has(userId)) {
- this.inAndOut = socketMessage;
- this.showWelcomeMessage = true;
- this.shownEntryUsers.add(userId);
- if (this.welcomeTimer) clearTimeout(this.welcomeTimer)
- this.welcomeTimer = setTimeout(() => {
- this.showWelcomeMessage = false
- }, 3000)
- }
- } catch (err) {
- console.error('解析entry用户数据失败:', err)
- }
- } else if (socketMessage.cmd == 'out') {
- if (this.liveUserTotal > 0) {
- const userIdToRemove = socketMessage.userId
- const index = this.liveViewersData.findIndex((item) => item.userId === userIdToRemove)
- if (index !== -1) {
- this.liveViewersData.splice(index, 1)
- this.liveUserTotal--
- }
- }
- this.inAndOut = socketMessage
- this.showWelcomeMessage = true
- if (this.welcomeTimer) clearTimeout(this.welcomeTimer)
- this.welcomeTimer = setTimeout(() => {
- this.showWelcomeMessage = false
- }, 3000)
- } else if (socketMessage.cmd == 'sendTopMsg') {
- clearInterval(this.noticeTimer)
- console.log('公告消息>>>>', socketMessage)
- const noticeData = socketMessage.data ? JSON.parse(socketMessage.data) : {}
- this.notice = noticeData || {}
- this.isShowNotice = true
- if (this.isShowNotice) {
- this.noticeTimer = setInterval(() => {
- const noticeCountdown = this.handleTime(this.notice.endTime, 0)
- if (!noticeCountdown) {
- this.isShowNotice = false
- clearInterval(this.noticeTimer)
- }
- }, 1000)
- }
- } else if (socketMessage.cmd == 'live_start' || socketMessage.cmd == 'live_end') {
- if (this.liveStartTimer) {
- clearInterval(this.liveStartTimer)
- this.liveStartTimer = null
- }
- if (this.redTimer) {
- clearInterval(this.redTimer)
- this.redTimer = null
- }
- const userInfo = uni.getStorageSync('userInfo');
- if (userInfo) {
- await this.getliving(this.liveId)
- }
- } else if (socketMessage.cmd == 'Integral') {
- this.integral = {
- msg: socketMessage.msg,
- status: true
- }
- } else if (socketMessage.cmd == 'userCount') {
- this.liveUserTotal = socketMessage.data
- }else if (socketMessage.cmd == 'LotteryDetail') {
- try {
- this.prizeInfo = Array.isArray(JSON.parse(socketMessage.data || '[]')) ? JSON.parse(
- socketMessage.data || '[]') : []
- } catch (err) {
- console.error('解析抽奖结果失败:', err)
- this.prizeInfo = []
- }
- this.isShowPrize = true
- this.isShowLottery = false
- this.isShowLotteryPop = false
- } else if (socketMessage.cmd == 'blockUser') {
- uni.removeStorage({
- key: 'AppToken',
- success: () => {
- uni.reLaunch({
- url: '/pages/auth/login'
- })
- }
- })
- }
- } else {
- uni.showToast({
- title: data.msg,
- icon: 'none'
- })
- }
- } catch (error) {
- console.error('Socket消息处理失败:', error)
- }
- },
- onBarrage(item) {
- if (this.isSending) return
- this.isSending = true
- setTimeout(() => {
- this.isSending = false
- }, 800)
- const text = (item || '').trim()
- if (!text) {
- uni.showToast({
- title: '不能发送空消息',
- icon: 'none'
- })
- return
- }
- if (!this.isSocketAvailable()) {
- if (retries > 0) {
- uni.showToast({
- title: `连接不稳定,正在重试(${retries}次)...`,
- icon: 'none'
- })
- setTimeout(() => this.sendMsg(retries - 1), 500)
- } else {
- uni.showToast({
- title: '连接已断开,发送失败',
- icon: 'none'
- })
- }
- return
- }
- const liveId = this.liveId
- const data = {
- liveId,
- userId: this.userData.userId,
- userType: 0,
- cmd: 'sendMsg',
- msg: text,
- nickName: this.userData.nickname || '未命名',
- avatar: this.userData.avatar || '/static/images/avatar.png'
- }
- try {
- this.socket.send({
- data: JSON.stringify(data),
- success: () => {
- this.forceScrollToBottomOnSend()
- },
- fail: (err) => {
- console.error('消息发送失败:', err)
- if (retries > 0) {
- uni.showToast({
- title: `发送失败,正在重试(${retries}次)`,
- icon: 'none'
- })
- setTimeout(() => this.sendMsg(retries - 1), 500)
- } else {
- uni.showToast({
- title: '发送失败,请稍后再试',
- icon: 'none'
- })
- }
- }
- })
- } catch (err) {
- console.error('发送消息异常:', err)
- if (retries > 0) {
- setTimeout(() => this.sendMsg(retries - 1), 500)
- } else {
- uni.showToast({
- title: '发送失败,请稍后再试',
- icon: 'none'
- })
- }
- }
- },
- sendMsg(retries = 1) {
- if (this.isSending) return
- this.isSending = true
- setTimeout(() => {
- this.isSending = false
- }, 800)
- const text = (this.value || '').trim()
- if (!text) {
- uni.showToast({
- title: '不能发送空消息',
- icon: 'none'
- })
- return
- }
- if (!this.isSocketAvailable()) {
- if (retries > 0) {
- uni.showToast({
- title: `连接不稳定,正在重试(${retries}次)...`,
- icon: 'none'
- })
- setTimeout(() => this.sendMsg(retries - 1), 500)
- } else {
- uni.showToast({
- title: '连接已断开,发送失败',
- icon: 'none'
- })
- this.value = text
- }
- return
- }
- const liveId = this.liveId
- this.value = ''
- const data = {
- liveId,
- userId: this.userData.userId,
- userType: 0,
- cmd: 'sendMsg',
- msg: text,
- nickName: this.userData.nickname || '未命名',
- avatar: this.userData.avatar || '/static/images/avatar.png'
- }
- try {
- this.socket.send({
- data: JSON.stringify(data),
- success: () => {
- this.value = ''
- this.forceScrollToBottomOnSend()
- },
- fail: (err) => {
- console.error('消息发送失败:', err)
- if (retries > 0) {
- uni.showToast({
- title: `发送失败,正在重试(${retries}次)`,
- icon: 'none'
- })
- setTimeout(() => this.sendMsg(retries - 1), 500)
- } else {
- uni.showToast({
- title: '发送失败,请稍后再试',
- icon: 'none'
- })
- this.value = text
- }
- }
- })
- } catch (err) {
- console.error('发送消息异常:', err)
- if (retries > 0) {
- setTimeout(() => this.sendMsg(retries - 1), 500)
- } else {
- uni.showToast({
- title: '发送失败,请稍后再试',
- icon: 'none'
- })
- this.value = text
- }
- }
- }
- }
- }
- </script>
- <style scoped lang="scss">
- // 弹窗
- .custom-toast {
- position: fixed;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- z-index: 999999;
- }
- .toast-content {
- background-color: rgba(0, 0, 0, 0.7);
- color: white;
- padding: 20rpx 40rpx;
- border-radius: 16rpx;
- max-width: 80vw;
- text-align: center;
- line-height: 1.5;
- font-weight: 500;
- font-size: 32rpx;
- }
- .swiper-wrapper {
- position: relative;
- width: 100%;
- height: 100vh;
- overflow: hidden;
- background-color: #000000;
- .live-bg {
- position: absolute;
- top: 0;
- width: 100%;
- height: 100%;
- }
- .container {
- width: 100%;
- height: 100%;
- position: relative;
- transition: opacity 0.3s ease;
- transform: translateZ(0);
- will-change: opacity;
- &.fullscreen {
- .content-top,
- .side-group,
- .chat-area-container,
- .shop-popup,
- .lottery-popup,
- .more-popup,
- .shop-card,
- .gift-popup,
- .coupon-pop,
- .prize-popup,
- .winning-popup,
- .integral-popup,
- .red-card-popup,
- .viewer-popup {
- display: none !important;
- visibility: hidden !important;
- opacity: 0 !important;
- pointer-events: none !important;
- }
- .live-video {
- position: fixed !important;
- top: 0 !important;
- left: 0 !important;
- width: 100vw !important;
- height: 100vh !important;
- z-index: 99999 !important;
- background: #000 !important;
- }
- }
- }
- }
- .content {
- position: relative;
- z-index: 2;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- display: flex;
- flex-direction: column;
- justify-content: space-between;
- .progress-countdown {
- margin-top: 24rpx;
- z-index: 9000;
- width: 180rpx;
- display: flex;
- flex-direction: column;
- align-items: center;
- background: rgba(0, 0, 0, 0.3);
- border-radius: 16rpx;
- padding: 16rpx;
- flex-direction: column;
- &.progress-vertical {
- top: 15%;
- left: 24rpx;
- }
- .title {
- width: 148rpx;
- height: 28rpx;
- }
- .progress-bar-bg {
- width: 148rpx;
- height: 8rpx;
- margin-top: 16rpx;
- background: #ffffff;
- border-radius: 6rpx;
- overflow: hidden;
- margin-bottom: 16rpx;
- .progress-bar-fill {
- height: 100%;
- background: #face15;
- border-radius: 6rpx;
- transition: width 1s linear;
- }
- }
- .progress-text {
- color: #fff;
- font-size: 20rpx;
- }
- }
- }
- .content-top {
- width: 100%;
- display: flex;
- justify-content: space-between;
- padding: 0 24rpx;
- box-sizing: border-box;
- position: fixed;
- margin-top: 88rpx;
- top: 0;
- z-index: 5;
- will-change: transform;
- color: #FFFFFF;
- .x-f {
- display: flex;
- align-items: center;
- .avatar-container {
- padding: 6rpx 8rpx;
- height: 64rpx;
- background: rgba(0, 0, 0, 0.5);
- border-radius: 32rpx;
- display: flex;
- align-items: center;
- }
- }
- .end {
- display: flex;
- flex-direction: column;
- align-items: flex-end;
- .viewer-preview {
- margin-top: 120rpx;
- display: flex;
- align-items: center;
- .sum {
- width: 80rpx;
- height: 52rpx;
- background: rgba(0, 0, 0, 0.5);
- border-radius: 26rpx;
- font-size: 30rpx;
- color: #ffffff;
- text-align: center;
- line-height: 52rpx;
- }
- }
- .complaint-box {
- width: 140rpx;
- margin-top: 20rpx;
- display: flex;
- align-items: center;
- justify-content: center;
- background: rgba(0, 0, 0, 0.3);
- padding: 16rpx 0;
- color: #fff;
- border-radius: 28rpx;
- z-index: 999;
- }
- }
- }
- .side-group {
- position: absolute;
- top: 52%;
- right: 24rpx;
- z-index: 1000;
- display: flex;
- flex-direction: column;
- align-items: center;
- will-change: transform;
- &.top2 {
- top: 65%;
- }
- &.top3 {
- top: 55%;
- }
- .side-item {
- font-weight: 500;
- font-size: 22rpx;
- color: #ffffff;
- margin-bottom: 26rpx;
- text-align: center;
- .button-reset {
- background-color: transparent !important;
- padding: 0 !important;
- line-height: 1 !important;
- margin: 0 !important;
- width: auto !important;
- font-weight: 500 !important;
- border-radius: none !important;
- &::after {
- border: none !important;
- padding: 0 !important;
- margin: 0 !important;
- }
- }
- .image {
- width: 72rpx;
- height: auto;
- }
- .txt {
- font-size: 30rpx;
- margin-top: 4rpx;
- }
- }
- }
- .chat-area-container {
- position: fixed;
- width: 100%;
- bottom: 0;
- z-index: 100;
- transform: translateZ(0);
- will-change: transform;
- backface-visibility: hidden;
- &.chat-area-focused {
- transform: translateY(calc(-1 * var(--keyboard-height, 0rpx))) translateZ(0);
- // z-index: 1000;
- }
- }
- .chat-content {
- height: 36vh;
- overflow: hidden;
- padding-left: 20rpx;
- transform: translateZ(0);
- will-change: height;
- display: flex;
- flex-direction: column;
- &.chat-content-preview {
- height: 20vh;
- }
- &.chat-content-focused {
- height: 64rpx;
- }
- }
- .shop-prompt {
- width: auto;
- display: inline-flex !important;
- max-width: max-content;
- padding: 6rpx 20rpx;
- background: rgba(230, 154, 34, 0.7);
- border-radius: 24rpx;
- z-index: 9;
- font-weight: 500;
- color: #ffffff;
- transition: opacity 0.3s ease;
- margin-bottom: 20rpx;
- }
- .welcome-message {
- width: 100%;
- color: white;
- border-radius: 20rpx;
- z-index: 10;
- transition: opacity 0.3s ease;
- }
- .notice-message {
- max-width: 80%;
- padding: 24rpx;
- background: linear-gradient(135deg,
- rgba(255, 220, 41, 0.8) 0%,
- rgba(218, 187, 30, 0.4) 100%);
- margin-bottom: 10rpx;
- border-radius: 20rpx;
- color: #ffffff;
- }
- .scrolly {
- width: calc(100% - 20rpx);
- -webkit-overflow-scrolling: touch;
- }
- .list {
- width: 80%;
- margin-bottom: 20rpx;
- animation: simpleFade 0.2s;
- .talk-list {
- will-change: transform;
- contain: layout style paint;
- backface-visibility: hidden;
- transform: translateZ(0);
- max-width: 100%;
- border-radius: 30rpx;
- background: rgba(0, 0, 0, 0.3);
- padding: 10rpx 30rpx;
- .talk-item {
- line-height: 1.4;
- word-break: break-all;
- word-wrap: break-word;
- overflow-wrap: break-word;
- .nickname {
- color: #ffda73;
- }
- .message {
- color: #ffffff;
- }
- }
- }
- }
- .barrage {
- background: rgba(0, 0, 0, 0.3);
- padding: 12rpx 20rpx;
- color: #fff;
- margin: 30rpx 20rpx 0 20rpx;
- border-radius: 30rpx;
- white-space: nowrap;
- }
- .prize-card {
- width: 504rpx;
- padding: 40rpx 40rpx 30rpx;
- box-sizing: border-box;
- display: flex;
- flex-direction: column;
- border-radius: 20rpx;
- align-items: center;
- background: linear-gradient(180deg, #f7823f 0%, #ffd4be 27%, #ffffff 100%);
- position: relative;
- .nav-img {
- width: 311rpx;
- position: absolute;
- top: -122rpx;
- left: 50%;
- transform: translateX(-50%);
- }
- .title {
- color: #c32008;
- font-size: 34rpx;
- font-weight: 600;
- margin: 20rpx 0 40rpx;
- }
- .prize-content {
- width: 100%;
- display: flex;
- justify-content: space-between;
- align-items: center;
- font-size: 28rpx;
- margin: 10rpx 0;
- .txt {
- font-weight: 600;
- }
- }
- .tip {
- font-size: 28rpx;
- color: #414141;
- margin: 40rpx 0;
- }
- .button {
- width: 200rpx;
- height: 70rpx;
- line-height: 70rpx;
- background: linear-gradient(180deg, #ff7c30 0%, #ff3a1e 100%);
- border-radius: 28rpx;
- font-weight: 500;
- font-size: 32rpx;
- color: #ffffff;
- text-align: center;
- }
- }
- .no-prize-card {
- width: 504rpx;
- padding: 40rpx 40rpx 30rpx;
- box-sizing: border-box;
- display: flex;
- flex-direction: column;
- border-radius: 20rpx;
- align-items: center;
- position: relative;
- .img {
- margin-top: 40rpx;
- width: 300rpx;
- height: 300rpx;
- }
- .tip {
- font-size: 36rpx;
- color: #414141;
- margin: 40rpx 0;
- }
- .button {
- width: 220rpx;
- height: 80rpx;
- line-height: 80rpx;
- background: linear-gradient(180deg, #fdfbb8 0%, #b79243 100%);
- border-radius: 28rpx;
- font-weight: 500;
- font-size: 32rpx;
- color: #ffffff;
- text-align: center;
- }
- }
- .red-card {
- width: 550rpx;
- height: 636rpx;
- position: relative;
- .img {
- position: absolute;
- width: 100%;
- height: 100%;
- }
- .red-content {
- position: relative;
- z-index: 5;
- display: flex;
- flex-direction: column;
- align-items: center;
- .title {
- font-size: 36rpx;
- color: #ff3a1e;
- margin: 180rpx 0 90rpx;
- }
- .txt {
- font-size: 28rpx;
- color: #ffecc3;
- margin: 80rpx 0 40rpx;
- }
- .button {
- width: 392rpx;
- height: 96rpx;
- line-height: 96rpx;
- background: linear-gradient(180deg, #fff4d5 0%, #ffe5b1 100%);
- border-radius: 48rpx;
- font-weight: 600;
- font-size: 36rpx;
- color: #c32008;
- text-align: center;
- }
- }
- }
- .integral-box {
- min-width: 400rpx;
- max-width: 600rpx;
- display: flex;
- flex-direction: column;
- align-items: center;
- border-radius: 20rpx;
- overflow: hidden;
- .top {
- width: 100%;
- position: relative;
- .title {
- width: 100%;
- font-weight: 600;
- font-size: 40rpx;
- color: #ffffff;
- text-shadow: 0px 4rpx 8rpx rgba(255, 89, 2, 0.8);
- position: absolute;
- top: 50rpx;
- text-align: center;
- }
- .photo {
- width: 100%;
- }
- }
- .item {
- padding: 20rpx;
- .title {
- font-weight: 500;
- font-size: 32rpx;
- text-align: center;
- }
- .button {
- font-size: 32rpx;
- margin-top: 20rpx;
- background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
- color: #fff;
- text-align: center;
- padding: 18rpx 60rpx;
- border-radius: 10rpx;
- font-weight: 500;
- }
- }
- }
- .coupon-pop {
- position: fixed;
- bottom: 140rpx;
- right: 100rpx;
- z-index: 5;
- border-radius: 20rpx;
- width: 320rpx;
- .coupon-block {
- width: 100%;
- position: relative;
- .bg {
- height: 452rpx;
- width: 100%;
- }
- .nav {
- position: absolute;
- height: 120rpx;
- top: -120rpx;
- left: 0;
- width: 100%;
- z-index: 6;
- }
- .close {
- position: absolute;
- right: 10rpx;
- top: 10rpx;
- z-index: 99;
- }
- .item {
- width: 100%;
- position: absolute;
- top: 20rpx;
- display: flex;
- flex-direction: column;
- align-items: center;
- color: #fff;
- .title {
- font-weight: 500;
- font-size: 30rpx;
- margin: 16rpx 0 12rpx;
- }
- .price {
- font-size: 40rpx;
- .bold {
- font-size: 56rpx;
- font-weight: 600;
- }
- }
- .txt {
- font-weight: 500;
- font-size: 30rpx;
- margin: 5rpx 0;
- }
- .button {
- background: linear-gradient(270deg, #fffce1 0%, #ffeaaf 100%);
- color: #ff0004;
- text-align: center;
- padding: 16rpx 0;
- border-radius: 40rpx;
- font-weight: 500;
- font-size: 30rpx;
- width: 70%;
- margin-top: 26rpx;
- }
- }
- }
- }
- .more-block {
- border-radius: 20rpx 0 0 20rpx;
- padding: 70rpx 30rpx;
- display: flex;
- justify-content: space-between;
- .item {
- text-align: center;
- }
- }
- .integral-popup {
- min-width: 400rpx;
- max-width: 600rpx;
- display: flex;
- flex-direction: column;
- align-items: center;
- border-radius: 20rpx;
- overflow: hidden;
- .integral-header {
- width: 100%;
- position: relative;
- .integral-title {
- width: 100%;
- font-weight: 600;
- font-size: 40rpx;
- color: #ffffff;
- text-shadow: 0px 4rpx 8rpx rgba(255, 89, 2, 0.8);
- position: absolute;
- top: 50rpx;
- text-align: center;
- }
- .integral-background-image {
- width: 100%;
- }
- }
- .integral-content {
- padding: 20rpx;
- .integral-message {
- font-weight: 500;
- font-size: 32rpx;
- text-align: center;
- }
- .integral-confirm-button {
- font-size: 32rpx;
- margin-top: 20rpx;
- background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
- color: #fff;
- text-align: center;
- padding: 18rpx 60rpx;
- border-radius: 10rpx;
- font-weight: 500;
- }
- }
- }
- .gift {
- padding: 32rpx 24rpx;
- color: #ffffff;
- .gift-top {
- margin-bottom: 32rpx;
- display: flex;
- justify-content: space-between;
- align-items: center;
- .left {
- font-weight: 600;
- font-size: 28rpx;
- .orange {
- color: #f4a007;
- }
- }
- }
- .gift-block {
- display: flex;
- justify-content: space-between;
- flex-wrap: wrap;
- .item {
- width: 162rpx;
- height: 212rpx;
- text-align: center;
- margin-bottom: 20rpx;
- border: 1rpx solid transparent;
- .name {
- font-size: 24rpx;
- color: rgba(255, 255, 255, 0.8);
- margin: 16rpx 0 12rpx;
- }
- .number {
- font-size: 18rpx;
- color: rgba(255, 255, 255, 0.4);
- }
- .button {
- font-size: 24rpx;
- width: 100%;
- height: 56rpx;
- line-height: 56rpx;
- background: linear-gradient(270deg, #ff5701 0%, #ffb501 100%);
- }
- }
- .active {
- overflow: hidden;
- background: #333333;
- border-radius: 16rpx;
- border: 1rpx solid rgba(255, 255, 255, 0.1);
- .name {
- margin: 4rpx 0 14rpx;
- }
- }
- }
- }
- .view-box {
- position: relative;
- height: 40vh;
- padding: 40rpx 0rpx;
- box-sizing: border-box;
- display: flex;
- flex-direction: column;
- .scroll-content {
- flex: 1;
- margin-top: 50rpx;
- overflow-y: auto;
- padding: 0 40rpx;
- }
- .bottom {
- padding: 20rpx 40rpx;
- position: absolute;
- bottom: 0;
- width: 100%;
- box-shadow: 0rpx -4rpx 10rpx 0rpx rgba(195, 195, 195, 0.3);
- background: #fff;
- }
- }
- @keyframes simpleFade {
- from {
- opacity: 0;
- }
- to {
- opacity: 1;
- }
- }
- .skeleton-item {
- display: flex;
- padding: 20rpx;
- background: #fff;
- margin-bottom: 16rpx;
- border-radius: 16rpx;
- }
- .skeleton-img {
- width: 200rpx;
- height: 200rpx;
- background: #f0f0f0;
- border-radius: 8rpx;
- margin-right: 24rpx;
- animation: pulse 1.5s ease-in-out infinite;
- }
- .skeleton-content {
- flex: 1;
- }
- .skeleton-line {
- height: 20rpx;
- background: #f0f0f0;
- margin-bottom: 16rpx;
- border-radius: 4rpx;
- animation: pulse 1.5s ease-in-out infinite;
- &.short {
- width: 60%;
- }
- &.medium {
- width: 80%;
- }
- &.long {
- width: 95%;
- }
- }
- @keyframes pulse {
- 0% {
- opacity: 1;
- }
- 50% {
- opacity: 0.5;
- }
- 100% {
- opacity: 1;
- }
- }
- .text-white {
- color: #ffffff;
- }
- .text-xs {
- font-size: 18rpx;
- }
- .text-sm {
- font-size: 24rpx;
- }
- .w52,
- .w72 {
- display: flex;
- align-items: center;
- justify-content: center;
- }
- .w52.h52.mr4 {
- border-radius: 26rpx;
- }
- .x-f {
- display: flex;
- align-items: center;
- }
- .align-center {
- display: flex;
- align-items: center;
- }
- .justify-start {
- display: flex;
- justify-content: flex-start;
- }
- .flex-1 {
- flex: 1;
- }
- .column {
- flex-direction: column;
- }
- .colorf {
- color: #ffffff;
- }
- .orange {
- color: #f4a007;
- }
- ::v-deep .u-icon--right {
- justify-content: flex-end !important;
- }
- /* 微信昵称授权弹窗样式 */
- .userlogo {
- padding: 36rpx 40rpx;
- color: #000000;
- .mt42 {
- margin-top: 42rpx;
- }
- .boxweixin {
- width: 44rpx;
- height: 44rpx;
- border-radius: 50%;
- text-align: center;
- line-height: 34rpx;
- color: #0a0;
- }
- .button-container {
- position: relative;
- margin: auto;
- .hidden-input {
- width: calc(100vw - 80rpx);
- text-align: center;
- height: 104rpx;
- background: #07C160;
- padding: 30rpx 0;
- box-sizing: border-box;
- border-radius: 12rpx;
- font-size: 32rpx !important;
- color: #FFFFFF !important;
- /* 输入文字大小 */
- }
- /* 针对 placeholder 的样式 */
- .hidden-input::placeholder {
- font-size: 44rpx !important;
- color: #FFFFFF !important;
- }
- /* 兼容微信小程序的 placeholder 样式 */
- .hidden-input .placeholder {
- font-size: 44rpx !important;
- color: #FFFFFF !important;
- }
- }
- .submitname {
- height: 104rpx;
- line-height: 104rpx;
- background: #F2F2F2;
- border-radius: 12rpx;
- font-size: 32rpx;
- color: #07C160;
- margin-top: 32rpx;
- text-align: center;
- }
- }
- </style>
|