living.vue 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540
  1. <template>
  2. <view class="swiper-wrapper">
  3. <view class="container">
  4. <view class="content">
  5. <view style="position: fixed;top: 0;z-index: 5;" class="content-top">
  6. <view class="x-f">
  7. <image v-if="!scene" @click="goBack" class="w60 h64 mr26" src="/static/images/return3.png" />
  8. <view class="align-center"
  9. style="padding: 6rpx 8rpx;height: 64rpx;background: rgba(0,0,0,0.5);border-radius: 32rpx;">
  10. <u-avatar :src="liveItem.liveImgUrl||'/static/images/avatar.png'" :size="32"></u-avatar>
  11. <view class="colorf ml10 mr6">
  12. <view>{{liveItem.liveName?truncateString(liveItem.liveName,8):"未命名"}}</view>
  13. </view>
  14. </view>
  15. </view>
  16. <view v-if="Array.isArray(filteredViewers)" class=" align-center" @click="toggleViewerList"
  17. style="margin-top: 120rpx;">
  18. <view v-for="(item,viewerIndex) in filteredViewers" :key="viewerIndex">
  19. <image v-if="item.avatar" class="w52 h52 mr4" style="border-radius: 26rpx;"
  20. :src="item.avatar" />
  21. <view v-else class="w52 h52 mr4"
  22. :style="{backgroundColor: getUserRandomColor(item.userId), borderRadius:'50%'}">
  23. <text class="text-white text-xs">{{getNicknameInitial(item.nickName)}}</text>
  24. </view>
  25. </view>
  26. <view class="sum">{{liveUserTotal||0}}</view>
  27. </view>
  28. </view>
  29. <!-- 右边的side -->
  30. <view class="side-group">
  31. <view class="side-item" @click="onLike">
  32. <LikeButton :initialCount="100" :heartsPerClick="5" @like="onLike" />
  33. <view>{{liveViewData && liveViewData.like||0}}</view>
  34. </view>
  35. <view class="side-item">
  36. <button open-type="share" class="button">
  37. <image class="image" src="/static/images/weixin.png" mode="widthFix" />
  38. </button>
  39. <view>分享</view>
  40. </view>
  41. </view>
  42. <view class="activity-box">
  43. <view class="item-box" @click="onRed()" v-if="isShowRed">
  44. <view class="x-f">
  45. <view class="tip">领红包</view>
  46. <view class="item">
  47. <image class="w70 img" src="/static/images/redbag.png" mode="widthFix" />
  48. </view>
  49. </view>
  50. </view>
  51. <view class="item-box" @click="onLottery()" v-if="isShowLottery&&countdown">
  52. <view class="x-f">
  53. <view class="tip">抽奖</view>
  54. <view class="item">
  55. <image class="w60" src="/static/images/lottery.png" mode="widthFix" />
  56. </view>
  57. </view>
  58. </view>
  59. <!-- v-if="isShowCoupon" -->
  60. <!-- <view class="item-box" @click="isShowCoupon=true">
  61. <view class="x-f">
  62. <view class="tip">优惠券</view>
  63. <view class="item">
  64. <image class="w60" src="/static/images/coupon.png" mode="widthFix" />
  65. </view>
  66. </view>
  67. </view> -->
  68. </view>
  69. <view class="shop-prompt f30 x-f"
  70. v-if="showPurchasePrompt&&orderUser&&orderUser.count&&liveItem.status==2">
  71. <image class="w32 h32 mr8" src="/static/images/shopping.png" />
  72. <text>{{ orderUser.count || 0 }}人正在去购买</text>
  73. </view>
  74. <view class="videolist" v-if="liveItem.status==2">
  75. <view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
  76. <!-- 视频组件 -->
  77. <live-player v-if="liveItem.livingUrl && liveItem.liveType == 1" :id="'myLivePlayer_' + liveId"
  78. :src="liveItem.livingUrl" autoplay mode="live" object-fit="contain" :muted="false"
  79. orientation="vertical" :enable-play-gesture="true" min-cache="1" max-cache="3"
  80. @statechange="onLiveStateChange($event, liveItem)" @error="onLiveError($event, liveItem)"
  81. class="item"></live-player>
  82. <!-- 录播 -->
  83. <video v-if="liveItem.videoUrl&&liveItem.liveType==2" :id="`myVideo_${liveId}`" class="item"
  84. :src="liveItem.videoUrl" :controls="false" object-fit="contain" :custom-cache="false"
  85. :enable-progress-gesture="false" vslide-gesture-in-fullscreen="true"
  86. :show-center-play-btn="false" :http-cache="false" loop @error="videoError"
  87. @timeupdate="onVideoTimeUpdate" @loadeddata="onVideoLoaded"
  88. @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause" @play="onVideoPlay">
  89. </video>
  90. <!-- 直播回放 -->
  91. <video v-if="liveItem.videoUrl&&liveItem.liveType==3" :id="`myVideo_${liveId}`" class="item"
  92. :src="liveItem.videoUrl" :controls="true" object-fit="contain" :custom-cache="false"
  93. :enable-progress-gesture="liveItem.isSpeedAllowed" vslide-gesture-in-fullscreen="true"
  94. :show-center-play-btn="true" :http-cache="false" loop @error="videoError"
  95. @timeupdate="onVideoTimeUpdate" @loadeddata="onVideoLoaded"
  96. @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause" @play="onVideoPlay"
  97. @seek="onVideoSeek">
  98. </video>
  99. <view v-if="liveItem.videoUrl&&liveItem.liveType==2" class="time">{{liveItem.totalTime}}
  100. </view>
  101. <view v-if="liveItem.videoUrl&&liveItem.liveType==3" class="lable">直播回放</view>
  102. </view>
  103. </view>
  104. <view class="trailer-box" v-if="liveItem.status==1">
  105. <video v-if="liveItem.previewUrl" :id="`myVideo_${liveId}`" class="item" :src="liveItem.previewUrl"
  106. :autoplay="true" :controls="false" object-fit="contain" :custom-cache="false"
  107. :enable-progress-gesture="false" vslide-gesture-in-fullscreen="false"
  108. :show-center-play-btn="false" :http-cache="false" loop @error="videoError"
  109. @loadeddata="onVideoLoaded" @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause"
  110. @play="onVideoPlay" :disable-progress="true">
  111. </video>
  112. <image v-if="liveItem.status==1&&!liveItem.previewUrl" class="img" src="/static/images/no_live.png">
  113. </image>
  114. <view class="countdown-item mt30 mb30" v-if="liveItem.status==1&&liveCountdown">
  115. 开播倒计时
  116. <view class="x-f">
  117. <view class="white">
  118. {{liveCountdown.hours||"00"}}
  119. </view>
  120. <view class="white">
  121. {{ liveCountdown.minutes||"00"}}
  122. </view>
  123. <view class="white">
  124. {{ liveCountdown.seconds||"00" }}
  125. </view>
  126. </view>
  127. </view>
  128. <view class="name"> {{liveItem.liveName}}</view>
  129. <view class="title" v-if="liveCountdown">暂未开播</view>
  130. <view class="button" v-if="!isAgreement" @click="handleAgreement">预约直播</view>
  131. <view class="button ash" v-if="isAgreement">已预约</view>
  132. <view class="title" v-if="!liveCountdown">主播还在来的路上</view>
  133. </view>
  134. <view class="trailer-box" v-if="!liveItem">
  135. <image class="img" src="/static/images/no_live.png">
  136. </image>
  137. <view class="title">暂无直播</view>
  138. </view>
  139. <!-- 底部聊天区域 -->
  140. <view :style="{position: 'fixed',width: '100%',bottom: chatHeight + 'rpx',zIndex:999}">
  141. <view class="mt20" :style="{ height: chatHeight ? '64rpx' : '30vh' }">
  142. <scroll-view v-if="Array.isArray(talklist)" enable-flex scroll-y="true"
  143. class="pl20 scrolly flex-1 column" style="width: calc(100% - 20rpx); height: 100%;"
  144. :scroll-top="scrollTop" ref="scrollView">
  145. <!-- 聊天消息列表 -->
  146. <view class="list justify-start" v-for="(item,talkIndex) in (talklist||[])" :key="talkIndex"
  147. :id="`list_${talkIndex}`" v-show="item.cmd!='red'&&item.cmd!='out'&&item.cmd!='entry'">
  148. <view class="talk-list justify-start">
  149. <view class="fs30" style="max-width: 100%;">
  150. <text style="color: #FFDA73;">{{item.nickName||"未命名"}}:</text>
  151. <text class='colorf'>{{item.msg}}</text>
  152. </view>
  153. </view>
  154. </view>
  155. <!-- 欢迎消息 -->
  156. <view v-if="showWelcomeMessage" class="welcome-message" style="max-width: 100%;">
  157. <view class="list justify-start" v-show="inAndOut.cmd=='entry'||inAndOut.cmd=='out'">
  158. <view class="talk-list justify-start">
  159. <view class="fs30">
  160. <text style="color: #ff89d6;">{{inAndOut.nickName||"未命名"}} </text>
  161. <text class='colorf'>{{inAndOut.msg}}直播间</text>
  162. </view>
  163. </view>
  164. </view>
  165. </view>
  166. </scroll-view>
  167. </view>
  168. <!-- 底部输入框和操作按钮 -->
  169. <view class="justify-between p24">
  170. <view class="x-f"
  171. :style="{background:'#393939' ,padding: '10rpx 14rpx 10rpx 32rpx',boxSizing: 'border-box',borderRadius: '36rpx',width: isFocus ? '100%' : '580rpx'}">
  172. <u-input :placeholder="placeholderText" border="none" customStyle='font-size:24rpx;'
  173. v-model="value" shape='circle' color="#ffffff" placeholderStyle="color:#e7e7e7"
  174. :adjust-position="false" :scroll-with-animation="false" class="ml20" @focus="inputFocus"
  175. @blur="inputBlur">
  176. </u-input>
  177. <view class="send" @click="sendMsg()">发送</view>
  178. </view>
  179. <view class="justify-between mr15 align-center" v-if="!isFocus">
  180. <view class="icon-bg ml20" @click="openCart()">
  181. <image src="/static/images/shopping.png" class="w58 h58" />
  182. </view>
  183. </view>
  184. </view>
  185. </view>
  186. </view>
  187. <view class="goods" v-if="isShowGoods">
  188. <view class="top">
  189. <view class="left">
  190. <image class="w30 h30 mr8" src="/static/images/signal.png" />讲解中
  191. </view>
  192. <image @click="isShowGoods=false" class="w40 h40 " src="/static/images/del2.png" />
  193. </view>
  194. <image class="photo" :src="goodsCard.imgUrl" />
  195. <view class="item">
  196. <view class="price"><text class="red">¥{{goodsCard.price}} </text><text
  197. class="del">¥{{goodsCard.otPrice}}</text></view>
  198. <view class="title oneline-hide">{{goodsCard.productName}}</view>
  199. <view class="button" @click="goShop(goodsCard.productId,goodsCard.goodsId)">
  200. 立即抢购
  201. </view>
  202. </view>
  203. </view>
  204. <u-popup :show="isShowLotteryPop&&countdown" round='40rpx'>
  205. <view class="prize-box" style="border-radius: 40rpx;height: fit-content;">
  206. <image class="nav-img " src="/static/images/red_head.png" mode="widthFix" />
  207. <image class="bg-img " src="/static/images/red_bg.png" />
  208. <view class="prize-content">
  209. <view class=" mr20">
  210. <u-icon class="x-end" name="close" color="#fff" size="20"
  211. @click="isShowLotteryPop=false"></u-icon>
  212. </view>
  213. <view class="column align-center ">
  214. <image class="w446 h80" src="/static/images/red_title.png" />
  215. <view class="fs24 colorf x-f mt30 mb30">
  216. 开奖倒计时
  217. <view class="x-f">
  218. <view class="white-item">
  219. {{countdown.hours||"00"}}
  220. </view>
  221. <view class="white-item">
  222. {{ countdown.minutes||"00" }}
  223. </view>
  224. <view class="white-item">
  225. {{ countdown.seconds||"00" }}
  226. </view>
  227. </view>
  228. </view>
  229. <view class="item-group">
  230. <ThreeItemSwiper :products="lotteryProducts"></ThreeItemSwiper>
  231. </view>
  232. <view class="point-group" v-for="(item,index) in lotteryProducts" :key="index">
  233. </view>
  234. <view class="colorf fs28">
  235. 观看直播参与抽奖
  236. </view>
  237. <view class="button" @click="onClaim">参与抽奖</view>
  238. </view>
  239. </view>
  240. </view>
  241. </u-popup>
  242. <u-popup :show="!!integral.status" round='20rpx' mode="center" bgColor='#ffffff' zIndex='10076'>
  243. <view class="integral-box">
  244. <view class="top">
  245. <view class="title">观看视频领芳华币</view>
  246. <image class="photo" src="/static/images/integral_bg.png" mode="widthFix" />
  247. </view>
  248. <view class="item">
  249. <view class="title ">{{integral.msg}}</view>
  250. <view class="button" @click="integral.status=false">确认</view>
  251. </view>
  252. </view>
  253. </u-popup>
  254. <u-popup :show="isShowRedCard" round='20rpx' mode="center" bgColor='transparent' zIndex='10076'>
  255. <view class="red-card">
  256. <image class="img" src="/static/images/red_card.png" />
  257. <view class="red-content">
  258. <view class="title">{{redCard.msg}}</view>
  259. <view class="txt ">直播惊喜芳华币</view>
  260. <view class="button" @click="isShowRedCard=false">确认</view>
  261. </view>
  262. </view>
  263. </u-popup>
  264. <!-- 中奖和未中奖 -->
  265. <u-popup :show="isShowPrize" round='20rpx' mode="center" bgColor='#fff' zIndex='10076'>
  266. <view class="prize-card" v-if="isCurrentUserWon">
  267. <image class="nav-img " src="/static/images/red_head.png" mode="widthFix" />
  268. <view class="title">{{prizeInfo.length}}位幸运观众</view>
  269. <view class="prize-content" v-for="(item,index) in (prizeInfo||[])" :key="index">
  270. <view>{{item.userName}}</view>
  271. <view>{{item.userId}}</view>
  272. <view class="txt">{{item.prizeLevel}}等奖</view>
  273. </view>
  274. <view class="tip">请截图联系客服领取奖品</view>
  275. <view class="button" @click="isShowPrize=false">确认</view>
  276. </view>
  277. <view class="no-prize-card" v-else>
  278. <image class="img" src="/static/images/no-prize.png" mode="widthFix" />
  279. <view class="tip">很遗憾 您未中奖</view>
  280. <view class="button" @click="isShowPrize=false">确认</view>
  281. </view>
  282. </u-popup>
  283. <!-- 观众列表弹窗 -->
  284. <u-popup :show="showadd" @close="close" @open="openViews" round='20rpx' bgColor='#ffffff' zIndex='10077'>
  285. <view class="view-box">
  286. <view class="fs32" style="text-align: center;">在线观众</view>
  287. <scroll-view v-if="Array.isArray(liveViewers)" scroll-y class="scroll-content"
  288. :style="{height: scrollHeight + 'px'}" @scrolltolower="handleScrollToLower">
  289. <view class="fs28 x-f mb20 mt20" v-for="(item,index) in (liveViewers||[])" :key="index">
  290. <view
  291. :style="{color: index === 0 ? '#FF3B30' : index === 1 ? '#FF9500' : index === 2 ? '#FFCC00' : '#8E8E93',fontWeight: index < 3 ? 'bold' : 'normal',width: '50rpx'}"
  292. class="mr10">{{index+1}}</view>
  293. <u-avatar v-if="item.avatar" :src="item.avatar" :size="36"></u-avatar>
  294. <view v-else class="w72 h72"
  295. :style="{backgroundColor: getUserRandomColor(item.userId), borderRadius:'50%'}">
  296. <text class="text-white text-xs">{{getNicknameInitial(item.nickName)}}</text>
  297. </view>
  298. <text class="ml16 f30">{{item.nickName||"未命名"}}</text>
  299. </view>
  300. </scroll-view>
  301. </view>
  302. </u-popup>
  303. <!-- 商品弹窗 -->
  304. <u-popup :show="shopping" @close="closeShop" round='20rpx' bgColor='#f3f5f9' zIndex='10075'>
  305. <view class="shoppop">
  306. <view class="shoppop-top">
  307. <view class="search-input x-f">
  308. <image class="w24 mr16" src="/static/images/search.png" mode="widthFix" />
  309. <input placeholder="请搜索商品" v-model="inputInfo" @input="handleSearchInput" />
  310. </view>
  311. <view class=" search-top" @click="goOrderList()">
  312. <image class="w48 h48" src="/static/images/order.png" />
  313. <view>订单</view>
  314. </view>
  315. </view>
  316. <scroll-view enable-flex scroll-y class="shop-list" :style="{ height: boxHeight + 'px' }">
  317. <view class="list-item" v-for="(item,index) in products" :key="index">
  318. <view class="goods-img">
  319. <image class="img" :src="item.imgUrl" mode="widthFix" />
  320. <view class="goods-label">{{index+1}}</view>
  321. </view>
  322. <view class="goods-right">
  323. <view class="goods-title">{{item.productName}}</view>
  324. <view class="goods-people">{{item.sales}} 人已购</view>
  325. <view class="goods-shop">
  326. <text class="nummber"><text style="font-size: 20rpx;font-weight: 600;">¥</text><text
  327. style="font-size: 36rpx;font-weight: bold;">{{Math.trunc(item.price)}}</text>.{{getPureDecimal(item.price)?getPureDecimal(item.price):'00'}}</text>
  328. <view class="btn-group x-f">
  329. <view class="collect-btn">
  330. <image v-if="item.isFavorite" @click="onGoodsCollect(item)" class="w36 h36"
  331. style="vertical-align: middle;"
  332. src="/static/images/collect_select.png" />
  333. <image v-else @click="onGoodsCollect(item)" class="w36 h36"
  334. style="vertical-align: middle;" src="/static/images/collect.png" />
  335. </view>
  336. <view v-if="item.status==1" class="shop-btn"
  337. @click="goShop(item.productId,item.goodsId)">去购买 </view>
  338. <view v-else-if="item.status==0" class="shop-btn">
  339. 已下架</view>
  340. </view>
  341. </view>
  342. </view>
  343. </view>
  344. </scroll-view>
  345. </view>
  346. </u-popup>
  347. <!-- 优惠券弹窗 -->
  348. <view class="coupon-pop" v-if="isShowCoupon">
  349. <view class="coupon-block">
  350. <image class="bg" src="/static/images/coupon_bg.png" />
  351. <image class="nav" src="/static/images/coupon_top.png" />
  352. <image @click="isShowCoupon=false" class="w40 h40 close" src="/static/images/close1.png" />
  353. <view class="item">
  354. <view class="title">{{couponInfo.couponName}}</view>
  355. <view class="price">¥<text class="bold">{{couponInfo.couponPrice}}</text></view>
  356. <view class="txt">满{{couponInfo.useMinPrice}}元可用</view>
  357. <view class="txt" style="margin-top: 26rpx;">指定商品可用</view>
  358. <view class="txt">自领取起{{couponInfo.couponTime}}天内有效</view>
  359. <view class="button" @click="onCoupon()">
  360. 立即领券
  361. </view>
  362. </view>
  363. </view>
  364. </view>
  365. </view>
  366. </view>
  367. </template>
  368. <script>
  369. import LikeButton from '@/pages_course/components/like.vue'
  370. import ThreeItemSwiper from '@/pages_course/components/ThreeItemSwiper.vue'
  371. import CryptoJS from 'crypto-js'
  372. import {
  373. coupon, //领取优惠券
  374. liveLottery, // 抽奖查询
  375. claim, //抽奖
  376. liveRed, // 点击领红包
  377. liveDataLike, // 点赞
  378. collectStore, // 店铺收藏/取消收藏
  379. collectGoods, // 商品收藏/取消收藏
  380. watchUserList, //获取直播间用户(展示在线用户)
  381. liveMsg, //获取最近聊天记录
  382. // 小黄车
  383. liveStore, //店铺展示,
  384. liveOrderUser, //正在购买
  385. getLiveInfo, //获取直播间信息接口
  386. getLiveViewData, //直播间点赞、关注、在线人数数据
  387. currentActivities, //红包 卡片 抽奖
  388. getlive,
  389. subNotifyLive,
  390. internetTraffic // 流量(缓冲百分比)
  391. } from '@/api/living.js'
  392. import {
  393. getUserInfo
  394. } from '@/api/user'
  395. import {
  396. generateRandomString
  397. } from "@/utils/common.js"
  398. import dayjs from 'dayjs';
  399. import {
  400. nextTick
  401. } from "vue"
  402. // var wsUrl = "wss://live.test.ylrztop.com/ws/live-api/app/webSocket"; //余红奇
  403. // var pingpangTimes = null;
  404. // var initTimes = null;
  405. var isSocketOpen = false;
  406. var socket = null;
  407. export default {
  408. components: {
  409. ThreeItemSwiper,
  410. LikeButton
  411. },
  412. data() {
  413. return {
  414. stayTime: 0,
  415. startTime: 0,
  416. scrollTop: 0,
  417. isOnload: false,
  418. isConnecting: false, // 是否正在连接中
  419. previousToken: null,
  420. hasInitialized: false,
  421. couponsList: [],
  422. liveViewersData: [],
  423. liveUserCalled: false, //调用过watchUserList没
  424. liveViewDataTimer: null,
  425. userRandomColors: {}, // 缓存用户ID -> 随机色的映射
  426. randomColor: '#8978e2',
  427. heartBeatRetryCount: 0, // 心跳发送重试次数(避免一次失败就重连)
  428. maxHeartBeatRetries: 2, // 心跳最大重试次数
  429. pingTimeout: 20000, // 心跳超时时间从10s延长到20s(应对网络波动)
  430. shownEntryUsers: new Set(), // 存储已显示过「进入提示」的用户ID
  431. isPageUnloading: false, // 标记页面是否正在卸载(区分主动离开vs重连out)
  432. templateId: 'fxYJu817lxHNKXl0hJypb54UnGRCNAoI72Qf-xjKCik',
  433. isAgreement: false,
  434. socket: null, // WebSocket 实例
  435. isSocketOpen: false, // 连接是否已打开
  436. heartBeatTimer: null, // 心跳定时器
  437. heartBeatInterval: 15000, // 心跳发送间隔(15秒)
  438. reconnectTimer: null, // 重连定时器
  439. reconnectCount: 0, // 当前重连次数
  440. maxReconnectAttempts: 3, // 最大重连次数
  441. isManualClose: false, // 是否手动关闭(用于区分主动关闭和异常断开)
  442. pingTimeoutTimer: null, // 心跳超时定时器
  443. // wsNewUrl: 'wss://api.fhhx.runtzh.com/app/webSocket',
  444. wsNewUrl: 'wss://api.fhhx.runtzh.com/ws/app/webSocket',
  445. // wsNewUrl: 'ws://192.168.10.166:7114/ws/app/webSocket',
  446. // wsNewUrl:'ws://192.168.10.166:7014/app/webSocket',
  447. qrFrom: null,
  448. scene: '',
  449. liveCountdown: {}, //直播倒计时
  450. countdown: {}, //抽奖倒计时
  451. liveViewData: {},
  452. chatHeight: 0,
  453. keyboardHeight: 0,
  454. videoCurrentTime: 0, // 当前视频播放时间
  455. isVideoPlaying: false, // 视频是否正在播放
  456. videoProgressKey: '', // 存储进度的key
  457. inAndOut: {},
  458. isShowPrize: false,
  459. isShowCoupon: false,
  460. prizeInfo: [],
  461. timeData: {},
  462. countDownKey: 0,
  463. lotteryProducts: [],
  464. lotteryList: [],
  465. talklist: [],
  466. isShowLotteryPop: false,
  467. liveItem: {},
  468. isSending: false,
  469. welcomeTimer: null,
  470. redTimer: null,
  471. liveStartTimer: null,
  472. lotteryTimer: null,
  473. isShowLottery: false,
  474. isShowRedCard: false,
  475. redCard: null, //点击红包出现弹窗
  476. integral: {},
  477. lotteryInfo: {},
  478. goodsCard: {},
  479. couponInfo: {},
  480. redInfo: {},
  481. storeId: null,
  482. isFocus: false,
  483. shopping: false,
  484. inputInfo: '',
  485. showWelcomeMessage: false,
  486. scrollIntoView: '',
  487. isShowGoods: false,
  488. isShowRed: false,
  489. lastClickTime: 0,
  490. clickDelay: 300, // 300ms内只响应一次点击
  491. videoRetryCounts: {}, // 记录每个直播间的视频重试次数,格式: { liveId: 次数 }
  492. placeholderText: '说点什么...',
  493. liveUserTotal: 0,
  494. viewPageSize: 10, // 每页数量
  495. viewPageNum: 1, // 当前页码
  496. viewLoading: false, // 是否正在加载
  497. scrollHeight: 0,
  498. scrollTimer: null, // 滚动防抖定时器
  499. showRed: true,
  500. searchTimer: null,
  501. isCollect: false,
  502. showPurchasePrompt: false,
  503. purchasePromptTimer: null,
  504. prevOrderCount: 0, // 用于记录上一次的购买人数
  505. videoUrl: null,
  506. showType: 1, //横屏1 竖屏2
  507. boxHeight: 300, //小黄车高度
  508. liveViewers: [], //观众
  509. likeName: 0,
  510. hlsPlayer: null, // HLS播放器实例,
  511. livingUrl: "",
  512. products: [],
  513. store: {},
  514. orderUser: {}, //正在购买
  515. userType: 0,
  516. timestamp: '',
  517. liveId: null,
  518. userinfo: '', //用户信息
  519. // path: 'http://192.168.10.166/dev-api', //余红奇
  520. // path: 'http://v56c9b8e.natappfree.cc', //余红奇
  521. // path: 'live.test.ylrztop.com/prod-api', //余红奇
  522. value: '',
  523. talkdisabled: false, //输入框是否禁用
  524. autoplay: false, //视频自动播放
  525. showadd: false,
  526. videoContext: '',
  527. livedata: {}, //直播间点赞、关注、在线人数数据
  528. userData: {},
  529. //流量
  530. uuId: "",
  531. };
  532. },
  533. onLoad(options) {
  534. if (options.liveId) {
  535. this.liveId = options.liveId;
  536. }
  537. this.getUserInfo()
  538. this.previousToken = uni.getStorageSync('AppToken')
  539. this.initTime();
  540. this.userinfo = uni.getStorageSync("userInfo")
  541. this.userData = uni.getStorageSync("userData")
  542. console.log("全部参数", options)
  543. //获取键盘高度
  544. this.keyboardListener = uni.onKeyboardHeightChange(res => {
  545. console.log('键盘高度', res.height);
  546. this.keyboardHeight = res.height * 2;
  547. });
  548. // 扫码传来的参数
  549. if (options.scene) {
  550. this.scene = options.scene;
  551. const decodedScene = decodeURIComponent(this.scene);
  552. const params = {};
  553. decodedScene.split('&').forEach(item => {
  554. const [key, value] = item.split('=');
  555. params[key] = value;
  556. this.liveId = params.a;
  557. })
  558. if (params.b && params.c) {
  559. this.qrFrom = `&companyId=${params.b}&companyUserId=${params.c}`;
  560. }
  561. }
  562. if (options.companyId && options.companyUserId) {
  563. this.qrFrom = `&companyId=${options.companyId}&companyUserId=${options.companyUserId}`;
  564. }
  565. // 初始化直播间列表
  566. this.$nextTick(() => {
  567. if (this.liveId) {
  568. this.getliving(this.liveId);
  569. this.isOnload = true
  570. } else {
  571. console.error("直播间 ID(liveId)未获取到");
  572. }
  573. })
  574. // if (!this.previousToken) {
  575. // console.log("未检测到AppToken,跳转到登录页");
  576. // // let backUrl = '/pages_course/living?liveId=' + (this.liveId || '');
  577. // uni.navigateTo({
  578. // url: '/pages/auth/login?&isLive=ture'
  579. // });
  580. // return;
  581. // }
  582. },
  583. onPullDownRefresh() {
  584. this.getLiveMsg(this.liveId)
  585. this.getliveUser()
  586. setTimeout(() => {
  587. uni.stopPullDownRefresh()
  588. }, 1000)
  589. },
  590. async onShow() {
  591. if (this.liveId && !this.isOnload) {
  592. await this.getLiveMsg(this.liveItem);
  593. }
  594. if (!this.userData) {
  595. await this.getUserInfo()
  596. }
  597. this.uuId = generateRandomString(16)
  598. const currentToken = await uni.getStorageSync('AppToken')
  599. console.log("token在这里", currentToken)
  600. const isLiveLogin = uni.getStorageSync('isLiveLogin')
  601. this.share = uni.getStorageSync('share')
  602. this.scene = uni.getStorageSync('scene')
  603. console.log("onshow分享", this.share)
  604. console.log("onshow扫码", this.scene)
  605. if (this.share && this.share.length > 0) {
  606. this.liveId = this.share.liveId
  607. this.qrFrom = `&companyId=${this.share.companyId}&companyUserId=${this.share.companyUserId}`;
  608. uni.removeStorageSync('share')
  609. }
  610. if (this.scene) {
  611. console.log("有扫码")
  612. const decodedScene = decodeURIComponent(this.scene);
  613. console.log("有扫码decodedScene", decodedScene)
  614. const params = {};
  615. decodedScene.split('&').forEach(item => {
  616. const [key, value] = item.split('=');
  617. params[key] = value;
  618. console.log("扫码参数", params)
  619. this.liveId = params.a;
  620. })
  621. if (params.b && params.c) {
  622. this.qrFrom = `&companyId=${params.b}&companyUserId=${params.c}`;
  623. }
  624. uni.removeStorageSync('scene')
  625. }
  626. if (isLiveLogin) {
  627. console.log("登录了")
  628. if (this.liveId) {
  629. await this.getliving(this.liveId)
  630. this.getCurrentActivities()
  631. this.getliveOrder()
  632. this.initSocket()
  633. }
  634. this.hasInitialized = true
  635. uni.removeStorageSync('isLiveLogin');
  636. }
  637. // 恢复播放和连接
  638. await this.resumePageActivity()
  639. this.userinfo = JSON.parse(uni.getStorageSync("userInfo"))
  640. // this.userData =await uni.getStorageSync("userData")
  641. this.isAgreement = uni.getStorageSync('isAgreement')
  642. this.previousToken = currentToken
  643. this.randomColor = this.getRandomHexColor()
  644. this.$nextTick(() => {
  645. this.setVideoProgress();
  646. });
  647. console.log("预约liveiD", this.liveId)
  648. if (this.lookTimer) {
  649. clearInterval(this.lookTimer)
  650. this.lookTimer = null;
  651. this.stayTime = 0;
  652. this.startTime = 0;
  653. }
  654. this.startTimer()
  655. },
  656. //分享给好友
  657. onShareAppMessage() {
  658. return {
  659. title: '邀请你来观看直播:' + this.liveItem.liveName,
  660. path: '/pages_course/living?companyId=-2&companyUserId=' + this.userData.userId + '&liveId=' + this.liveId,
  661. imageUrl: '/static/images/logo.png',
  662. success(res) {
  663. console.log("分享成功", res);
  664. },
  665. fail(err) {
  666. console.error("分享失败", err);
  667. }
  668. };
  669. },
  670. computed: {
  671. filteredViewers() {
  672. // 1. 强制兜底:若 liveViewers 不是数组(如 null/undefined),直接返回空数组
  673. const safeLiveViewers = Array.isArray(this.liveViewersData) ? this.liveViewersData : [];
  674. // 2. 截取前3项(空数组 slice 不会报错)
  675. return safeLiveViewers.slice(0, 3);
  676. },
  677. isCurrentUserWon() {
  678. // 兜底条件:确保prizeInfo是数组、当前用户ID存在
  679. if (!Array.isArray(this.prizeInfo) || !this.userData?.userId) {
  680. return false;
  681. }
  682. // 匹配逻辑:检查prizeInfo中是否有userId与当前用户一致的项
  683. return this.prizeInfo.some(item => {
  684. // 兼容item.userId可能是数字/字符串的情况,统一转为字符串比较
  685. return String(item.userId) === String(this.userData.userId);
  686. });
  687. }
  688. },
  689. onHide() {
  690. },
  691. onUnload() {
  692. this.suspendPageActivity()
  693. this.liveUserCalled = false
  694. // if (this.liveItem) {
  695. // this.pauseVideo();
  696. // this.clearTimeTimer();
  697. // }
  698. this.loadUserColorsFromStorage();
  699. if (this.liveViewDataTimer) {
  700. clearInterval(this.liveViewDataTimer);
  701. this.liveViewDataTimer = null;
  702. }
  703. // console.log('页面卸载,清理资源');
  704. this.isPageUnloading = true; // 标记为主动离开
  705. // 1. 先关闭WebSocket
  706. this.closeWebSocket(true);
  707. // 2. 清除所有定时器
  708. this.clearAllTimers();
  709. // 3. 暂停视频
  710. const videoId = `myVideo_${this.liveId}`;
  711. const videoContext = uni.createVideoContext(videoId, this);
  712. if (videoContext) {
  713. videoContext.pause();
  714. }
  715. // 4. 移除事件监听
  716. // 5. 清除特定定时器
  717. if (this.redTimer) {
  718. clearInterval(this.redTimer);
  719. this.redTimer = null;
  720. }
  721. if (this.liveStartTimer) {
  722. clearInterval(this.liveStartTimer);
  723. this.liveStartTimer = null;
  724. }
  725. if (this.lotteryTimer) {
  726. clearInterval(this.lotteryTimer);
  727. this.lotteryTimer = null;
  728. }
  729. if (this.welcomeTimer) {
  730. clearInterval(this.welcomeTimer);
  731. this.welcomeTimer = null;
  732. }
  733. if (this.trafficInterval != null) {
  734. clearInterval(this.trafficInterval)
  735. }
  736. if (this.lookTimer) {
  737. clearInterval(this.lookTimer)
  738. this.lookTimer = null;
  739. this.stayTime = 0;
  740. this.startTime = 0;
  741. }
  742. },
  743. mounted() {
  744. this.getCurrentActivities();
  745. this.getliveOrder()
  746. },
  747. watch: {
  748. // 新增:监听liveItem.status的变化
  749. 'liveItem.status': {
  750. // status变化时执行的逻辑
  751. handler(newStatus, oldStatus) {
  752. // 1. 过滤无效场景:避免初始值/空值触发无效请求
  753. if (newStatus === undefined || oldStatus === undefined) return;
  754. // 2. 过滤相同状态:仅当状态真的变化时才请求(避免重复调用)
  755. if (newStatus === oldStatus) return;
  756. // 3. 确保liveId存在(getliving依赖liveId)
  757. if (!this.liveId) {
  758. console.warn("liveId不存在,无法触发getliving请求");
  759. return;
  760. }
  761. // 4. 状态变化时,调用getliving更新直播间数据
  762. console.log(`liveItem.status从${oldStatus}变为${newStatus},触发getliving请求`);
  763. this.getliving(this.liveId);
  764. },
  765. deep: true,
  766. // immediate: true(若需页面初始化时就触发一次,根据需求决定是否开启)
  767. },
  768. // 监听orderUser.count的变化
  769. 'orderUser.count': {
  770. handler(newVal, oldVal) {
  771. if (newVal !== this.prevOrderCount) {
  772. this.prevOrderCount = newVal;
  773. this.showPurchaseMessage();
  774. }
  775. },
  776. immediate: true
  777. }
  778. },
  779. methods: {
  780. startTimer() {
  781. this.startTime = Date.now()
  782. this.lookTimer = setInterval(() => {
  783. this.stayTime = Math.floor((Date.now() - this.startTime) / 1000)
  784. }, 1000)
  785. },
  786. // 缓冲
  787. getInternetTraffic() {
  788. if (!this.liveItem.videoId ||!this.liveItem.videoType) return;
  789. if (!this.liveId) return;
  790. const currentTime = this.stayTime / this.liveItem.duration * 100;
  791. const param = {
  792. companyId: this.companyId || '',
  793. companyUserId: this.companyUserId || '',
  794. userId: this.userData.userId || '',
  795. liveId: this.liveId || '',
  796. videoType: this.liveItem.videoType,
  797. videoId: this.liveItem.videoId,
  798. uuId: dayjs().format('YYYYMMDD') + this.uuId,
  799. duration: this.liveItem.duration,
  800. bufferRate: currentTime,
  801. }
  802. internetTraffic(param)
  803. },
  804. scrollToBottom() {
  805. this.$nextTick(() => {
  806. setTimeout(() => {
  807. const query = uni.createSelectorQuery().in(this);
  808. // 获取 scroll-view 和内容的高度
  809. query.select('.scrolly').boundingClientRect(scrollRect => {
  810. query.select('.scrolly').scrollOffset(scrollOffset => {
  811. // 计算新的滚动位置
  812. const newScrollTop = scrollOffset.scrollHeight - scrollRect
  813. .height;
  814. this.scrollTop = newScrollTop;
  815. }).exec();
  816. }).exec();
  817. }, 100);
  818. });
  819. },
  820. // 恢复页面活动
  821. async resumePageActivity() {
  822. console.log("恢复了")
  823. if (this.liveItem) {
  824. this.playVideo()
  825. this.startTimeTimer(this.liveItem)
  826. }
  827. if (!this.isSocketAvailable()) {
  828. this.initSocket()
  829. }
  830. },
  831. // 暂停页面活动
  832. suspendPageActivity() {
  833. this.stopHeartBeat()
  834. this.saveVideoProgress()
  835. if (this.liveItem) {
  836. this.pauseVideo()
  837. this.clearTimeTimer()
  838. }
  839. },
  840. // 获取用户专属随机色(缓存机制:同一用户始终用同一颜色)
  841. getUserRandomColor(userId) {
  842. if (!userId) {
  843. return '#8978e2'; // 默认颜色
  844. }
  845. //如果缓存中已有该用户的颜色,直接返回
  846. if (this.userRandomColors[userId]) {
  847. return this.userRandomColors[userId];
  848. }
  849. //为新用户生成固定颜色(基于用户ID生成,不是完全随机)
  850. const color = this.generateStableColor(userId);
  851. this.userRandomColors[userId] = color;
  852. // 存储到本地缓存,确保页面刷新后颜色不变
  853. this.saveUserColorsToStorage();
  854. return color;
  855. }, // 基于用户ID生成稳定颜色(不是完全随机)
  856. generateStableColor(userId) {
  857. // 将用户ID转换为数字种子
  858. let seed = 0;
  859. for (let i = 0; i < userId.length; i++) {
  860. seed = (seed * 31 + userId.charCodeAt(i)) % 1000000;
  861. }
  862. const colorPool = [
  863. '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
  864. '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9',
  865. '#F8C471', '#82E0AA', '#F1948A', '#85C1E9', '#D7BDE2'
  866. ];
  867. return colorPool[seed % colorPool.length];
  868. }, // 保存颜色映射到本地存储
  869. saveUserColorsToStorage() {
  870. try {
  871. uni.setStorageSync('userRandomColors', this.userRandomColors);
  872. } catch (e) {
  873. console.warn('保存用户颜色缓存失败:', e);
  874. }
  875. },
  876. // 从本地存储加载颜色映射
  877. loadUserColorsFromStorage() {
  878. try {
  879. const cached = uni.getStorageSync('userRandomColors');
  880. if (cached) {
  881. this.userRandomColors = cached;
  882. }
  883. } catch (e) {
  884. console.warn('加载用户颜色缓存失败:', e);
  885. }
  886. },
  887. //头像名字
  888. getNicknameInitial(nickName) {
  889. if (!nickName || typeof nickName !== 'string') return '未';
  890. if (/^[\u4e00-\u9fa5]/.test(nickName[0])) {
  891. return nickName[0];
  892. }
  893. return nickName[0].toUpperCase();
  894. },
  895. // 引入前面的随机颜色方法
  896. getRandomHexColor() {
  897. const getValidValue = () => Math.floor(Math.random() * 130) + 100;
  898. const red = getValidValue().toString(16).padStart(2, '0');
  899. const green = getValidValue().toString(16).padStart(2, '0');
  900. const blue = getValidValue().toString(16).padStart(2, '0');
  901. return `#${red}${green}${blue}`;
  902. },
  903. async getUserInfo() {
  904. await getUserInfo().then(
  905. res => {
  906. if (res.code == 200) {
  907. console.log("用户信息>>", res)
  908. this.userData = res.user;
  909. } else {
  910. uni.showToast({
  911. icon: 'none',
  912. title: "请求失败",
  913. });
  914. }
  915. },
  916. rej => {}
  917. );
  918. }, // 检查WebSocket连接状态
  919. getSocketState() {
  920. if (!this.socket) return 'CLOSED';
  921. const states = {
  922. 0: 'CONNECTING',
  923. 1: 'OPEN',
  924. 2: 'CLOSING',
  925. 3: 'CLOSED'
  926. };
  927. return states[this.socket.readyState] || 'UNKNOWN';
  928. },
  929. // 在控制台输出连接状态(调试用)
  930. logSocketState() {
  931. console.log('WebSocket状态:', {
  932. socket: !!this.socket,
  933. isSocketOpen: this.isSocketOpen,
  934. readyState: this.getSocketState(),
  935. reconnectCount: this.reconnectCount
  936. });
  937. },
  938. handleAgreement() {
  939. const templateId = this.templateId; // 先保存到局部变量
  940. uni.requestSubscribeMessage({
  941. tmplIds: [templateId],
  942. success: (res) => { // 使用箭头函数保持this指向
  943. console.log("订阅结果", res);
  944. console.log("模板订阅状态", res[templateId]);
  945. if (res[templateId] === "accept") {
  946. uni.showToast({
  947. title: '订阅成功,开播将提醒您',
  948. icon: 'success'
  949. });
  950. this.callSendMessageApi()
  951. } else if (res[templateId] === 'reject') {
  952. uni.showToast({
  953. title: '您已拒绝订阅,将无法收到提醒',
  954. icon: 'none'
  955. });
  956. } else if (res[templateId] === 'ban') {
  957. uni.showToast({
  958. title: '您已关闭所有订阅权限,请在设置中开启',
  959. icon: 'none'
  960. });
  961. }
  962. },
  963. fail: (err) => {
  964. console.error('订阅消息失败', err);
  965. uni.showToast({
  966. title: '订阅失败,请重试',
  967. icon: 'none'
  968. });
  969. }
  970. });
  971. },
  972. // 调用后端发送订阅消息的接口
  973. async callSendMessageApi() {
  974. if (!this.userData.userId) return;
  975. console.log("订阅在这里", this.userData.userId)
  976. const templateData = {
  977. taskName: this.liveId,
  978. userId: this.userData.userId,
  979. templateId: this.templateId, // 你的模板ID
  980. data: {
  981. thing6: this.liveItem.liveName,
  982. date7: this.liveItem.startTime,
  983. }
  984. };
  985. // 调用后端接口(后端负责调用微信订阅消息发送接口)
  986. subNotifyLive(templateData).then(res => {
  987. if (res.code == 200) {
  988. this.isAgreement = true;
  989. uni.setStorageSync('isAgreement', true);
  990. console.log("订阅消息", res)
  991. } else {
  992. uni.showToast({
  993. title: res.msg,
  994. icon: 'none'
  995. });
  996. }
  997. },
  998. rej => {}
  999. );
  1000. },
  1001. sendHeartBeat() {
  1002. if (!this.isSocketAvailable()) return;
  1003. try {
  1004. const heartBeatMsg = JSON.stringify({
  1005. cmd: "heartbeat",
  1006. msg: "ping",
  1007. userId: this.userData.userId || '',
  1008. liveId: this.liveId
  1009. });
  1010. this.socket.send({
  1011. data: heartBeatMsg,
  1012. success: () => {
  1013. this.heartBeatRetryCount = 0; // 成功后重置重试次数
  1014. this.startPingTimeout(); // 启动超时检测
  1015. },
  1016. fail: (err) => {
  1017. console.error("心跳包发送失败:", err);
  1018. this.heartBeatRetryCount++;
  1019. // 心跳失败先重试,重试次数用完再重连
  1020. if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
  1021. setTimeout(() => this.sendHeartBeat(), 2000); // 2秒后重试
  1022. } else {
  1023. this.heartBeatRetryCount = 0;
  1024. this.handleReconnect(); // 重试用完才重连
  1025. }
  1026. }
  1027. });
  1028. } catch (err) {
  1029. console.error("心跳发送异常:", err);
  1030. this.heartBeatRetryCount++;
  1031. if (this.heartBeatRetryCount < this.maxHeartBeatRetries) {
  1032. setTimeout(() => this.sendHeartBeat(), 2000);
  1033. } else {
  1034. this.heartBeatRetryCount = 0;
  1035. this.handleReconnect();
  1036. }
  1037. }
  1038. }, // 启动心跳超时检测
  1039. startPingTimeout() {
  1040. // 清除之前的超时定时器
  1041. if (this.pingTimeoutTimer) {
  1042. clearTimeout(this.pingTimeoutTimer);
  1043. this.pingTimeoutTimer = null;
  1044. }
  1045. // 超时后触发重连
  1046. this.pingTimeoutTimer = setTimeout(() => {
  1047. // console.error("心跳响应超时,连接异常");
  1048. this.handleReconnect();
  1049. }, this.pingTimeout);
  1050. },
  1051. stopHeartBeat() {
  1052. if (this.heartBeatTimer) {
  1053. clearInterval(this.heartBeatTimer);
  1054. this.heartBeatTimer = null;
  1055. }
  1056. if (this.pingTimeoutTimer) {
  1057. clearTimeout(this.pingTimeoutTimer);
  1058. this.pingTimeoutTimer = null;
  1059. }
  1060. }, // 封装通用的连接状态校验方法
  1061. isSocketAvailable() {
  1062. // WebSocket readyState:0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED
  1063. return this.socket && this.isSocketOpen && this.socket.readyState === 1;
  1064. },
  1065. // 处理重连逻辑
  1066. handleReconnect() {
  1067. this.resetReconnectState();
  1068. this.stopHeartBeat();
  1069. if (this.reconnectCount < this.maxReconnectAttempts) {
  1070. this.reconnectCount++;
  1071. const delay = 1000;
  1072. console.log(`第${this.reconnectCount}次重连,延迟${delay}ms`);
  1073. this.reconnectTimer = setInterval(() => {
  1074. this.initSocket();
  1075. }, delay);
  1076. } else {
  1077. console.log(`停止重连(手动关闭/已达最大次数)`);
  1078. this.closeWebSocket(true);
  1079. }
  1080. },
  1081. // 重置重连状态
  1082. resetReconnectState() {
  1083. this.reconnectCount = 0;
  1084. if (this.reconnectTimer) {
  1085. clearInterval(this.reconnectTimer);
  1086. this.reconnectTimer = null;
  1087. }
  1088. },
  1089. //输入框
  1090. inputFocus() {
  1091. this.chatHeight = this.keyboardHeight;
  1092. this.isFocus = true;
  1093. },
  1094. inputBlur() {
  1095. this.chatHeight = 0;
  1096. this.isFocus = false
  1097. },
  1098. getTimeDifferenceInSeconds(createTimeStr) {
  1099. const createTime = new Date(createTimeStr.replace(/-/g, '/'));
  1100. const now = new Date();
  1101. const timeDiffMs = now - createTime;
  1102. const timeDiffSeconds = Math.floor(timeDiffMs / 1000);
  1103. return Math.max(0, timeDiffSeconds);
  1104. },
  1105. // 录播时间点
  1106. onVideoMetaLoaded(e) {
  1107. this.videoProgressKey = `videoProgress_${this.liveId}`;
  1108. this.setVideoProgress();
  1109. },
  1110. setVideoProgress() {
  1111. // 只有录播和回放需要设置进度
  1112. if (this.liveItem.liveType !== 2 && this.liveItem.liveType !== 3) {
  1113. return;
  1114. }
  1115. let currentTime = 0;
  1116. if (this.liveItem.liveType === 2) {
  1117. // 录播:计算当前时间与开始时间的差值,对视频总时长取模
  1118. const diff = this.getTimeDifferenceInSeconds(this.liveItem.startTime);
  1119. currentTime = diff % this.liveItem.duration;
  1120. } else if (this.liveItem.liveType === 3) {
  1121. // 回放:从存储中获取进度
  1122. const storedProgress = uni.getStorageSync(this.videoProgressKey);
  1123. currentTime = storedProgress || 0;
  1124. }
  1125. const videoId = `myVideo_${this.liveId}`;
  1126. const videoContext = uni.createVideoContext(videoId, this);
  1127. if (videoContext) {
  1128. videoContext.seek(currentTime);
  1129. console.log(`设置视频播放位置: ${currentTime}秒`);
  1130. }
  1131. },
  1132. // 视频数据加载完成
  1133. onVideoLoaded(e) {
  1134. console.log('视频数据加载完成');
  1135. },
  1136. // 视频时间更新
  1137. onVideoTimeUpdate(e) {
  1138. // 获取当前播放时间
  1139. this.videoCurrentTime = e.detail.currentTime;
  1140. // 每隔5秒保存一次进度(避免频繁存储)
  1141. if (Math.floor(this.videoCurrentTime) % 5 === 0) {
  1142. this.saveVideoProgress();
  1143. }
  1144. },
  1145. // 视频暂停
  1146. onVideoPause(e) {
  1147. // this.isVideoPlaying = false;
  1148. // 暂停时保存进度
  1149. this.saveVideoProgress();
  1150. },
  1151. // 视频播放
  1152. onVideoPlay(e) {
  1153. // this.isVideoPlaying = true;
  1154. },
  1155. // 设置视频当前时间
  1156. // setVideoCurrentTime(time) {
  1157. // if (!time) return;
  1158. // const videoId = `myVideo_${this.liveId}`;
  1159. // const videoContext = uni.createVideoContext(videoId, this);
  1160. // if (videoContext) {
  1161. // videoContext.seek(time);
  1162. // console.log(`设置视频播放位置: ${time}秒`);
  1163. // }
  1164. // },
  1165. // 保存视频进度
  1166. saveVideoProgress() {
  1167. if (this.videoProgressKey) {
  1168. uni.setStorage({
  1169. key: this.videoProgressKey,
  1170. data: this.videoCurrentTime,
  1171. success: () => {},
  1172. fail: (err) => {
  1173. console.error('保存视频进度失败:', err);
  1174. }
  1175. });
  1176. }
  1177. },
  1178. // 点击红包
  1179. onRed() {
  1180. if (!this.liveId) return;
  1181. if (!this.redInfo?.redId) return;
  1182. if (this.redTimer) {
  1183. clearInterval(this.redTimer);
  1184. this.redTimer = null;
  1185. }
  1186. let data = {
  1187. liveId: this.liveId,
  1188. userId: this.userData.userId,
  1189. redId: this.redInfo.redId,
  1190. }
  1191. liveRed(data).then(res => {
  1192. this.isShowRed = false
  1193. this.redCard = res
  1194. this.isShowRedCard = true
  1195. },
  1196. rej => {}
  1197. );
  1198. },
  1199. //领取优惠券
  1200. onCoupon() {
  1201. if (!this.couponInfo.couponIssueId) return;
  1202. let data = {
  1203. goodsId: this.couponInfo.goodsId,
  1204. couponIssueId: this.couponInfo.couponIssueId,
  1205. liveId: this.liveId
  1206. };
  1207. coupon(data)
  1208. .then(res => {
  1209. if (res.code == 200) {
  1210. uni.showToast({
  1211. title: res.msg,
  1212. icon: 'none'
  1213. });
  1214. this.isShowCoupon = false
  1215. // const couponData = res.data || {};
  1216. } else {
  1217. uni.showToast({
  1218. title: res.msg,
  1219. icon: 'none'
  1220. });
  1221. }
  1222. })
  1223. .catch(rej => {});
  1224. },
  1225. // 抽奖
  1226. onLottery() {
  1227. if (!this.lotteryInfo) return;
  1228. let data = {
  1229. lotteryId: this.lotteryInfo.lotteryId
  1230. };
  1231. liveLottery(data)
  1232. .then(res => {
  1233. if (res.code == 200) {
  1234. const resData = res.data || {}; // 兜底 res.data 为对象,避免访问 res.data.products 报错
  1235. this.lotteryList = Array.isArray(resData) ? resData : [];
  1236. // 兜底 products 为数组
  1237. this.lotteryProducts = Array.isArray(resData.products) ? resData.products : [];
  1238. if (resData.duration) {
  1239. this.isShowLotteryPop = true;
  1240. }
  1241. } else {
  1242. uni.showToast({
  1243. title: res.msg,
  1244. icon: 'none'
  1245. });
  1246. this.lotteryList = [];
  1247. this.lotteryProducts = [];
  1248. }
  1249. })
  1250. .catch(rej => {
  1251. uni.showToast({
  1252. title: '获取抽奖信息失败',
  1253. icon: 'none'
  1254. });
  1255. // 失败时强制重置为数组
  1256. this.lotteryList = [];
  1257. this.lotteryProducts = [];
  1258. });
  1259. },
  1260. // 参与抽奖
  1261. onClaim() {
  1262. let data = {
  1263. liveId: this.liveId,
  1264. lotteryId: this.lotteryInfo.lotteryId,
  1265. }
  1266. claim(data).then(res => {
  1267. if (res.code == 200) {
  1268. uni.showToast({
  1269. title: res.msg,
  1270. icon: 'none'
  1271. });
  1272. this.isShowLotteryPop = false
  1273. } else {
  1274. uni.showToast({
  1275. title: res.msg,
  1276. icon: 'none'
  1277. });
  1278. }
  1279. },
  1280. rej => {}
  1281. );
  1282. },
  1283. // 商品收藏
  1284. onGoodsCollect(item) {
  1285. if (!item || item.length === 0 || !item.goodsId) {
  1286. return;
  1287. }
  1288. collectGoods(item.goodsId).then(res => {
  1289. if (res.code == 200) {
  1290. uni.showToast({
  1291. title: res.msg,
  1292. icon: 'none'
  1293. });
  1294. item.isFavorite = !item.isFavorite
  1295. } else {
  1296. uni.showToast({
  1297. title: res.msg,
  1298. icon: 'none'
  1299. });
  1300. }
  1301. },
  1302. rej => {}
  1303. );
  1304. },
  1305. //正在购买
  1306. getliveOrder(item) {
  1307. if (!this.liveId) {
  1308. return;
  1309. }
  1310. liveOrderUser(this.liveId).then(res => {
  1311. // console.log("正在购买", res)
  1312. if (res.code == 200) {
  1313. this.orderUser = res;
  1314. } else {
  1315. console.log('获取正在购买用户失败');
  1316. }
  1317. },
  1318. rej => {}
  1319. );
  1320. },
  1321. onLiveStateChange(e, liveItem) {
  1322. // console.log('直播状态变化:', e.detail.code, e.detail);
  1323. // 可以根据状态码处理不同的直播状态
  1324. const stateCode = e.detail.code;
  1325. // 2001: 已经连接服务器
  1326. // 2002: 已经连接服务器,开始拉流
  1327. // 2003: 网络接收到首个视频数据包(IDR)
  1328. // 2004: 视频播放开始
  1329. // 2005: 视频播放进度
  1330. // 2006: 视频播放结束
  1331. // 2007: 视频播放Loading
  1332. // 2008: 解码器启动
  1333. // -2301: 网络断连,且经多次重连抢救无效,更多重试请自行重启播放
  1334. // -2302: 获取加速拉流地址失败
  1335. }, // 直播错误事件
  1336. onLiveError(e, liveItem) {
  1337. this.videoError(e, liveItem);
  1338. },
  1339. // 红包 卡片 抽奖
  1340. getCurrentActivities() {
  1341. if (!this.liveId) return;
  1342. currentActivities(this.liveId).then(res => {
  1343. if (res.code === 200) {
  1344. // 提取数据(默认空数组/对象避免报错)
  1345. this.redInfo = (res.red || [])[0];
  1346. this.lotteryInfo = (res.lottery || [])[0];
  1347. this.goodsCard = res.goods || {};
  1348. this.isShowGoods = this.goodsCard && this.goodsCard.status == 1;
  1349. this.isShowRed = this.redInfo && this.redInfo.redStatus == 1;
  1350. this.isShowLottery = this.lotteryInfo && this.lotteryInfo.lotteryStatus == 1;
  1351. if (this.isShowRed) {
  1352. this.redTimer = setInterval(() => {
  1353. const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo
  1354. .duration)
  1355. if (!redCountdown) {
  1356. this.isShowRed = false
  1357. clearInterval(this.redTimer)
  1358. }
  1359. }, 1000);
  1360. }
  1361. // 处理抽奖定时器
  1362. if (this.isShowLottery) {
  1363. this.lotteryTimer = setInterval(() => {
  1364. this.countdown = this.handleTime(this.lotteryInfo.updateTime, this
  1365. .lotteryInfo
  1366. .duration)
  1367. }, 1000);
  1368. }
  1369. } else {
  1370. uni.showToast({
  1371. title: res.msg,
  1372. icon: 'none'
  1373. });
  1374. }
  1375. }, rej => {});
  1376. },
  1377. // 计算当前时间与 liveItem.startTime 的差值,并更新 totalTime
  1378. calculateTimeDiff(item) {
  1379. // 防御1:item 不存在直接返回
  1380. if (!item.startTime) return;
  1381. // 步骤1:提取对应场景的时间字符串(直播用startTime,抽奖用updateTime)
  1382. let timeStr = item.startTime;
  1383. // 转换时间格式(适配iOS,将 "-" 替换为 "/")
  1384. const iosCompatibleTime = timeStr.replace(/-/g, "/");
  1385. const time = new Date(iosCompatibleTime);
  1386. if (isNaN(time.getTime())) {
  1387. return;
  1388. }
  1389. const now = new Date();
  1390. let diffMs = Math.max(0, now - time); // 直播:已播放时长(现在-开始时间)
  1391. // 步骤4:转换为 时:分:秒(补零处理)
  1392. const totalSeconds = Math.floor(diffMs / 1000);
  1393. const hours = this.padZero(Math.floor(totalSeconds / 3600));
  1394. const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
  1395. const seconds = this.padZero(totalSeconds % 60);
  1396. this.$set(this.liveItem, "totalTime", `${hours}:${minutes}:${seconds}`);
  1397. this.$set(this.liveItem, "totalSeconds", totalSeconds);
  1398. },
  1399. padZero(num) {
  1400. return num < 10 ? `0${num}` : num;
  1401. },
  1402. // 启动当前直播间的时间差值定时器
  1403. startTimeTimer(item) {
  1404. // 防御:若 item 不存在,直接返回
  1405. if (!item) return;
  1406. // 立即计算一次(避免等待1秒才显示)
  1407. const totalTime = this.calculateTimeDiff(item);
  1408. item.timeTimer = setInterval(() => {
  1409. const totalTime = this.calculateTimeDiff(item);
  1410. }, 1000);
  1411. },
  1412. // 清除指定直播间的时间定时器
  1413. clearTimeTimer() {
  1414. if (this.liveItem.timeTimer) {
  1415. clearInterval(this.liveItem.timeTimer);
  1416. this.liveItem.timeTimer = null; // 清空定时器标识
  1417. }
  1418. },
  1419. toggleViewerList() {
  1420. const now = Date.now();
  1421. if (now - this.lastClickTime > this.clickDelay) {
  1422. this.showadd = !this.showadd;
  1423. if (this.showadd) {
  1424. this.getliveUser(false); // 加载第一页观众
  1425. }
  1426. this.lastClickTime = now;
  1427. }
  1428. },
  1429. closeAllWebSockets() {
  1430. this.isManualClose = true;
  1431. this.isSocketOpen = false; // 应该是 this.isSocketOpen
  1432. this.closeWebSocket(true);
  1433. },
  1434. // 清理所有定时器
  1435. clearAllTimers() {
  1436. if (this.intervalId) {
  1437. clearInterval(this.intervalId);
  1438. this.intervalId = null;
  1439. }
  1440. // if (this.pingpangTimes) {
  1441. // clearInterval(this.pingpangTimes);
  1442. // this.pingpangTimes = null;
  1443. // }
  1444. if (this.reconnectTimer) {
  1445. clearInterval(this.reconnectTimer);
  1446. this.reconnectTimer = null;
  1447. }
  1448. if (this.scrollTimer) {
  1449. clearTimeout(this.scrollTimer);
  1450. this.scrollTimer = null;
  1451. }
  1452. if (this.searchTimer) {
  1453. clearTimeout(this.searchTimer);
  1454. this.searchTimer = null;
  1455. }
  1456. if (this.purchasePromptTimer) {
  1457. clearTimeout(this.purchasePromptTimer);
  1458. this.purchasePromptTimer = null;
  1459. }
  1460. },
  1461. // 播放视频
  1462. playVideo() {
  1463. if (!this.liveItem) {
  1464. console.log('liveItem 为空,无法播放视频');
  1465. return;
  1466. }
  1467. try {
  1468. // 直播流使用live-player
  1469. if (this.liveItem.liveType === 1 && this.liveItem.livingUrl && this.liveItem.status == 2) {
  1470. const livePlayerId = `myLivePlayer_${this.liveId}`;
  1471. const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  1472. if (livePlayerContext) {
  1473. livePlayerContext.play();
  1474. }
  1475. } else if (this.liveItem.status == 1 && this.liveItem.previewUrl) {
  1476. const videoId = `myVideo_${this.liveId}`;
  1477. const videoContext = uni.createVideoContext(videoId, this);
  1478. if (videoContext) {
  1479. videoContext.play();
  1480. }
  1481. }
  1482. // 回放视频使用video
  1483. else if (this.liveItem.liveType === 2 && this.liveItem.videoUrl && this.liveItem.status == 2) {
  1484. const videoId = `myVideo_${this.liveId}`;
  1485. const videoContext = uni.createVideoContext(videoId, this);
  1486. if (videoContext) {
  1487. videoContext.play();
  1488. }
  1489. } else if (this.liveItem.liveType === 3 && this.liveItem.videoUrl && this.liveItem.status == 2) {
  1490. const videoId = `myVideo_${this.liveId}`;
  1491. const videoContext = uni.createVideoContext(videoId, this);
  1492. if (videoContext) {
  1493. videoContext.play();
  1494. }
  1495. }
  1496. } catch (error) {
  1497. console.error("播放视频失败:", error);
  1498. }
  1499. },
  1500. pauseVideo() {
  1501. if (!this.liveItem) return;
  1502. try {
  1503. // 直播流使用live-player
  1504. if (this.liveItem.status == 1) {
  1505. const videoId = `myVideo_${this.liveId}`;
  1506. const videoContext = uni.createVideoContext(videoId, this);
  1507. if (videoContext) {
  1508. videoContext.pause();
  1509. }
  1510. } else if (this.liveItem.status == 2) {
  1511. if (this.liveItem.liveType === 1) {
  1512. const livePlayerId = `myLivePlayer_${this.liveId}`;
  1513. const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  1514. if (livePlayerContext) {
  1515. livePlayerContext.pause();
  1516. }
  1517. } else if (this.liveItem.liveType === 2) {
  1518. const videoId = `myVideo_${this.liveId}`;
  1519. const videoContext = uni.createVideoContext(videoId, this);
  1520. if (videoContext) {
  1521. videoContext.pause();
  1522. }
  1523. }
  1524. }
  1525. } catch (error) {
  1526. console.error("暂停视频失败:", error);
  1527. }
  1528. },
  1529. // 视频错误处理
  1530. videoError(e, liveItem) {
  1531. if (!liveItem || !this.liveId) return;
  1532. // 初始化重试计数
  1533. if (this.videoRetryCounts[liveItem.liveId] === undefined) {
  1534. this.videoRetryCounts[liveItem.liveId] = 0;
  1535. }
  1536. // 限制重试次数
  1537. if (this.videoRetryCounts[liveItem.liveId] >= 3) {
  1538. console.error(`直播间 ${this.liveId} 视频加载失败,停止重试`);
  1539. // 显示错误提示
  1540. uni.showToast({
  1541. title: "视频加载失败,请检查网络",
  1542. icon: 'none',
  1543. duration: 2000
  1544. });
  1545. return;
  1546. }
  1547. this.videoRetryCounts[this.liveId]++;
  1548. // 延迟重试
  1549. setTimeout(() => {
  1550. if (this.liveId === this.liveId) {
  1551. console.log(`第${this.videoRetryCounts[this.liveId]}次重试播放视频`);
  1552. this.playVideo();
  1553. }
  1554. }, 2000);
  1555. },
  1556. openViews() {
  1557. // 计算scroll-view高度
  1558. this.$nextTick(() => {
  1559. const query = uni.createSelectorQuery().in(this);
  1560. query.select('.view-box').boundingClientRect(data => {
  1561. if (data) {
  1562. // 减去标题和底部固定区域的高度
  1563. this.scrollHeight = data.height - 80 - 120; // 80是标题高度,120是底部高度
  1564. }
  1565. }).exec();
  1566. });
  1567. },
  1568. // 滚动到底部触发
  1569. handleScrollToLower() {
  1570. // 清除上一次未执行的定时器,避免重复请求
  1571. if (this.scrollTimer) {
  1572. clearTimeout(this.scrollTimer);
  1573. }
  1574. // 延迟0.5秒(500毫秒)执行接口请求
  1575. this.scrollTimer = setTimeout(() => {
  1576. this.getliveUser(true); // 加载更多数据
  1577. }, 1000); // 延迟时间:500毫秒
  1578. },
  1579. async getLiveMsg(liveItem) {
  1580. if (!liveItem || !this.liveId) {
  1581. console.error('getLiveMsg 错误:无效的 liveItem');
  1582. return;
  1583. }
  1584. try {
  1585. const res = await liveMsg(this.liveId, 30, 1);
  1586. if (res.code == 200) {
  1587. const rows = Array.isArray(res.rows) ? res.rows : [];
  1588. const reversedTalkList = [...rows].reverse();
  1589. this.talklist = Array.isArray(reversedTalkList) ? reversedTalkList : [];
  1590. // 获取历史消息后也滚动到底部
  1591. this.$nextTick(() => {
  1592. this.scrollToBottom();
  1593. });
  1594. } else {
  1595. this.talklist = [];
  1596. }
  1597. } catch (error) {
  1598. this.talklist = [];
  1599. console.error("获取聊天记录失败:", error);
  1600. }
  1601. },
  1602. // 获取直播间用户
  1603. // getliveUser(isLoadMore = false) {
  1604. // this.viewLoading = true;
  1605. // watchUserList(this.liveId, this.viewPageSize, this.viewPageNum, false)
  1606. // .then(res => {
  1607. // if (res.code === 200) {
  1608. // const userRows = Array.isArray(res.rows) ? res.rows : [];
  1609. // this.liveViewersData = userRows.map(item => ({
  1610. // avatar: item.avatar || '',
  1611. // userId: item.userId || '',
  1612. // nickName: item.nickName || '未命名'
  1613. // }));
  1614. // console.log("请求到了",this.liveViewersData)
  1615. // this.liveUserTotal = res.total || 0;
  1616. // const newRows = Array.isArray(res.rows) ? res.rows : [];
  1617. // const currentViewers = Array.isArray(this.liveViewers) ? this.liveViewers : [];
  1618. // this.liveViewers = isLoadMore ? [...currentViewers, ...newRows] : newRows;
  1619. // this.viewPageNum++;
  1620. // } else {
  1621. // this.liveViewers = []; // 接口失败时强制置空数组
  1622. // }
  1623. // })
  1624. // .catch(error => {
  1625. // console.error('获取观众列表失败:', error);
  1626. // this.liveViewers = []; // 捕获异常时强制置空数组
  1627. // })
  1628. // .finally(() => {
  1629. // this.viewLoading = false; // 无论成功失败都关闭加载状态
  1630. // });
  1631. // },
  1632. async getliveUser(isLoadMore = false) {
  1633. this.viewLoading = true;
  1634. try {
  1635. const res = await watchUserList(this.liveId, this.viewPageSize, this.viewPageNum, false);
  1636. if (res.code === 200) {
  1637. const userRows = Array.isArray(res.rows) ? res.rows : [];
  1638. this.liveViewersData = userRows.map(item => ({
  1639. avatar: item.avatar || '',
  1640. userId: item.userId || '',
  1641. nickName: item.nickName || '未命名'
  1642. }));
  1643. this.liveUserTotal = res.total || 0;
  1644. const newRows = Array.isArray(res.rows) ? res.rows : [];
  1645. const currentViewers = Array.isArray(this.liveViewers) ? this.liveViewers : [];
  1646. this.liveViewers = isLoadMore ? [...currentViewers, ...newRows] : newRows;
  1647. this.viewPageNum++;
  1648. }
  1649. } catch (error) {
  1650. console.error('获取观众列表失败:', error);
  1651. } finally {
  1652. this.viewLoading = false;
  1653. }
  1654. },
  1655. //小黄车搜索商品
  1656. handleSearchInput() {
  1657. // 使用防抖优化性能,避免频繁请求
  1658. clearTimeout(this.searchTimer);
  1659. this.searchTimer = setTimeout(() => {
  1660. this.queryCollect();
  1661. }, 500); // 500毫秒延迟
  1662. },
  1663. // 显示购买提示信息
  1664. showPurchaseMessage() {
  1665. // 清除之前的定时器
  1666. if (this.purchasePromptTimer) {
  1667. clearTimeout(this.purchasePromptTimer);
  1668. }
  1669. // 显示提示
  1670. this.showPurchasePrompt = true;
  1671. // 2秒后自动隐藏
  1672. this.purchasePromptTimer = setTimeout(() => {
  1673. this.showPurchasePrompt = false;
  1674. }, 2000);
  1675. },
  1676. //名字超过省略
  1677. truncateString(str, maxLength) {
  1678. if (typeof str !== 'string' || str.length <= maxLength) {
  1679. return str;
  1680. }
  1681. return str.slice(0, maxLength) + '...'; // 截断后加省略号
  1682. },
  1683. // 去订单列表
  1684. goOrderList() {
  1685. uni.navigateTo({
  1686. url: "/pages_shopping/live/order"
  1687. })
  1688. },
  1689. // 修改获取直播信息方法
  1690. async getliving(liveId) {
  1691. if (!liveId) return;
  1692. const param = {
  1693. id: liveId
  1694. };
  1695. try {
  1696. const res = await getlive(param);
  1697. if (res.code !== 200) {
  1698. uni.showToast({
  1699. title: res.msg,
  1700. icon: 'none'
  1701. });
  1702. return;
  1703. }
  1704. // 关键:用 Object.assign 合并旧数据与新数据,确保原有响应式属性不丢失
  1705. // 同时通过 $set 触发整体更新(若 liveItem 初始为空,需先初始化)
  1706. this.liveItem = Object.assign({}, this.liveItem, res.data);
  1707. // this.liveItem = res.data;
  1708. this.talklist = Array.isArray((res.data || {}).talklist) ? res.data.talklist : [];
  1709. this.startTimeTimer(this.liveItem);
  1710. // 清除旧定时器(如预告倒计时)
  1711. if (this.liveStartTimer) {
  1712. clearInterval(this.liveStartTimer);
  1713. this.liveStartTimer = null;
  1714. }
  1715. if (res.data.status == 1) {
  1716. // 直播预告
  1717. this.liveStartTimer = setInterval(async () => {
  1718. this.liveCountdown = this.handleTime(res.data.startTime, 0);
  1719. if (!this.liveCountdown) {
  1720. await this.getliving(this.liveId);
  1721. clearInterval(this.liveStartTimer);
  1722. }
  1723. }, 1000);
  1724. this.$set(this.liveItem, 'previewUrl', res.data.previewUrl);
  1725. this.$set(this.liveItem, 'livingUrl', ''); // 清空直播流
  1726. this.$set(this.liveItem, 'videoUrl', ''); // 清空回放视频
  1727. } else if (res.data.status == 2) {
  1728. if (res.data.liveType == 1) {
  1729. // 直播流
  1730. let cTime = Math.floor(Math.random() * 10000) + 1;
  1731. let livingUrl = res.data.flvHlsUrl + "&t=" + cTime;
  1732. console.log("地址在", this.liveItem.livingUrl)
  1733. this.$set(this.liveItem, 'livingUrl', livingUrl);
  1734. this.$set(this.liveItem, 'videoUrl', ''); // 清空回放视频
  1735. } else if (res.data.liveType === 2 || res.data.liveType === 3) {
  1736. // 回放视频 2录播 3直播回放
  1737. this.$set(this.liveItem, 'videoUrl', res.data.videoUrl);
  1738. this.$set(this.liveItem, 'livingUrl', '');
  1739. } else {
  1740. // 未开播
  1741. this.$set(this.liveItem, 'livingUrl', '');
  1742. this.$set(this.liveItem, 'videoUrl', '');
  1743. }
  1744. }
  1745. await this.getLiveMsg(this.liveItem);
  1746. await this.getliveViewData(this.liveItem);
  1747. //流量
  1748. let that = this
  1749. if (this.trafficInterval != null) {
  1750. clearInterval(that.trafficInterval)
  1751. }
  1752. this.trafficInterval = setInterval(function() {
  1753. that.getInternetTraffic()
  1754. },60000);
  1755. this.$set(this.liveItem, 'autoplay', res.data.liveType !== 0);
  1756. this.$set(this.liveItem, 'showType', res.data.showType);
  1757. this.storeId = res.storeId;
  1758. // 2. 启动“10秒刷新直播间数据”的定时器
  1759. this.startLiveViewDataTimer();
  1760. this.playVideo();
  1761. // live_start 时主动初始化播放组件
  1762. // this.initPlayerComponent();
  1763. } catch (err) {
  1764. console.error("获取直播信息失败:", err);
  1765. uni.showToast({
  1766. title: "获取直播信息失败",
  1767. icon: 'none'
  1768. });
  1769. }
  1770. },
  1771. // initPlayerComponent() {
  1772. // const {
  1773. // liveType,
  1774. // status,
  1775. // liveId,
  1776. // livingUrl,
  1777. // videoUrl
  1778. // } = this.liveItem;
  1779. // // 仅在“直播中”(status:2)时初始化
  1780. // if (status !== 2) return;
  1781. // this.$nextTick(() => { // 等待视图更新后再操作组件
  1782. // // 1. 直播流(liveType:1):初始化 live-player
  1783. // if (liveType === 1 && livingUrl) {
  1784. // const livePlayerId = `myLivePlayer_${liveId}`;
  1785. // const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
  1786. // if (livePlayerContext) {
  1787. // livePlayerContext.stop(); // 先停止旧流
  1788. // livePlayerContext.play(); // 播放新流
  1789. // }
  1790. // }
  1791. // // 2. 录播/回放(liveType:2/3):初始化 video
  1792. // if ((liveType === 2 || liveType === 3) && videoUrl) {
  1793. // const videoId = `myVideo_${liveId}`;
  1794. // const videoContext = uni.createVideoContext(videoId, this);
  1795. // if (videoContext) {
  1796. // videoContext.stop(); // 停止旧视频
  1797. // videoContext.seek(0); // 重置到开头
  1798. // videoContext.play(); // 播放新视频
  1799. // }
  1800. // }
  1801. // });
  1802. // },
  1803. // 设置视频播放
  1804. maskString(str, maskChar = '*') {
  1805. // 如果str是undefined或null,直接返回空字符串
  1806. if (!str) return '';
  1807. // 确保str是字符串(如果是数字等类型,先转为字符串)
  1808. const strVal = String(str);
  1809. return strVal.split('').map((char, index) => (index === 0 ? char : maskChar)).join(
  1810. '');
  1811. },
  1812. getPureDecimal(num, precision = 6) {
  1813. const decimalPart = Math.abs(num).toFixed(precision).split('.')[1];
  1814. return decimalPart?.replace(/0+$/, '') || ''; // 移除末尾多余的0
  1815. },
  1816. // 返回上一个页面并关闭WebSocket
  1817. goBack() {
  1818. // 暂停当前视频
  1819. if (this.liveItem) {
  1820. this.pauseVideo();
  1821. }
  1822. // 关闭WebSocket连接
  1823. this.closeWebSocket(true);
  1824. // 导航返回
  1825. const pages = getCurrentPages();
  1826. if (pages.length > 1) {
  1827. uni.navigateBack();
  1828. } else {
  1829. uni.reLaunch({
  1830. url: '/pages_course/livingList'
  1831. });
  1832. }
  1833. },
  1834. // 点赞
  1835. async onLike() {
  1836. if (!this.liveId) return;
  1837. try {
  1838. const res = await liveDataLike(this.liveId);
  1839. if (res?.like) {
  1840. this.liveViewData.like++; // 只更新当前直播间的点赞数
  1841. } else {
  1842. uni.showToast({
  1843. title: res.msg,
  1844. icon: 'none'
  1845. });
  1846. }
  1847. } catch (error) {
  1848. console.error('点赞失败:', error);
  1849. }
  1850. },
  1851. //直播间点赞、关注、在线人数数据
  1852. getliveViewData(liveItem) {
  1853. if (!liveItem || !this.liveId) return;
  1854. getLiveViewData(this.liveId).then(res => {
  1855. if (res.code == 200) {
  1856. // 强制响应式更新,确保数据实时显示
  1857. this.liveViewData = res;
  1858. }
  1859. }).catch(error => {
  1860. console.error("获取直播间数据失败:", error);
  1861. // 失败时兜底,避免显示异常
  1862. this.liveViewData = {
  1863. like: 0,
  1864. watchCount: 0
  1865. };
  1866. });
  1867. },
  1868. startLiveViewDataTimer() {
  1869. // 先清除旧定时器(防止重复创建)
  1870. if (this.liveViewDataTimer) {
  1871. clearInterval(this.liveViewDataTimer);
  1872. this.liveViewDataTimer = null;
  1873. }
  1874. // 启动新定时器,每3秒执行一次
  1875. this.liveViewDataTimer = setInterval(() => {
  1876. // 安全校验:确保liveItem和liveId存在(避免无效请求)
  1877. if (this.liveItem && this.liveId) {
  1878. this.getliveViewData(this.liveItem);
  1879. }
  1880. }, 10000);
  1881. },
  1882. // 去购买,跳商品详情
  1883. goShop(productId, goodsId) {
  1884. if (!this.liveId) return;
  1885. uni.navigateTo({
  1886. url: '/pages_shopping/live/goods?productId=' + productId + '&liveId=' + this.liveId +
  1887. '&goodsId=' +
  1888. goodsId + '&storeId=' + this.storeId
  1889. })
  1890. },
  1891. // 查询店铺
  1892. async queryCollect() {
  1893. if (!this.liveId) return;
  1894. if (this.inputInfo == null) this.inputInfo = ''
  1895. try {
  1896. const res = await liveStore(this.liveId, this.inputInfo);
  1897. if (res.code === 200) {
  1898. // 数据绑定到当前 liveItem,避免全局污染
  1899. this.products = Array.isArray(res.data) ? res.data : [];
  1900. }
  1901. } catch (error) {
  1902. console.error('获取小黄车商品失败:', error);
  1903. }
  1904. },
  1905. // 时间戳
  1906. initTime() {
  1907. const now = new Date();
  1908. this.timestamp = now.getTime(); // 例如:'2023-04-01 12:00:00'
  1909. },
  1910. openCart() {
  1911. this.queryCollect()
  1912. this.shopping = true
  1913. },
  1914. close() {
  1915. this.showadd = false
  1916. },
  1917. // 关闭小黄车
  1918. closeShop() {
  1919. this.shopping = false;
  1920. },
  1921. // 修改关闭WebSocket方法
  1922. // closeWebSocket() {
  1923. // this.socket?.close();
  1924. // },
  1925. // 关闭WebSocket连接(isManual:是否手动关闭)
  1926. closeWebSocket(isManual = true) {
  1927. // 修复判断条件:当 socket 为 null 或未打开时,直接返回
  1928. if (!this.socket || !this.isSocketOpen) {
  1929. console.warn("WebSocket 任务不存在或未打开,无需关闭");
  1930. return;
  1931. }
  1932. console.log("websocket 连接关闭");
  1933. this.isManualClose = isManual;
  1934. this.stopHeartBeat();
  1935. this.resetReconnectState();
  1936. try {
  1937. // 先保存引用,避免在关闭过程中被置为null
  1938. const socketToClose = this.socket;
  1939. this.socket = null;
  1940. this.isSocketOpen = false;
  1941. socketToClose.close({
  1942. code: 1000,
  1943. reason: isManual ? "主动关闭" : "异常关闭"
  1944. });
  1945. console.log("WebSocket连接已发起关闭");
  1946. } catch (err) {
  1947. console.error("关闭WebSocket失败:", err);
  1948. // 即使关闭失败,也要重置状态
  1949. this.socket = null;
  1950. this.isSocketOpen = false;
  1951. }
  1952. },
  1953. startHeartBeat() {
  1954. this.stopHeartBeat(); // 先停止现有心跳,防止重复
  1955. this.sendHeartBeat(); // 立即发送一次心跳
  1956. // 按间隔循环发送心跳
  1957. this.heartBeatTimer = setInterval(() => {
  1958. this.sendHeartBeat();
  1959. }, this.heartBeatInterval);
  1960. },
  1961. initSocket() {
  1962. if (!this.userData) {
  1963. this.getUserInfo()
  1964. }
  1965. if (this.isConnecting) {
  1966. return;
  1967. }
  1968. // 如果已经存在连接且状态为open,则退出
  1969. if (this.socket && this.socket.readyState === 1) {
  1970. return;
  1971. }
  1972. if (this.socket && (this.socket.readyState === 0 || this.socket.readyState === 1)) {
  1973. console.log('关闭现有WebSocket连接,创建新连接');
  1974. this.closeWebSocket(true);
  1975. }
  1976. // 校验必要参数
  1977. if (!this.liveId) {
  1978. console.error("缺失直播间ID,无法初始化WebSocket");
  1979. return;
  1980. }
  1981. console.log("用户信息", this.userData)
  1982. if (!this.userData || !this.userData.userId) {
  1983. console.error("用户信息缺失,无法初始化WebSocket");
  1984. return;
  1985. }
  1986. // 清除之前的重连定时器
  1987. this.resetReconnectState();
  1988. const now = new Date();
  1989. this.timestamp = now.getTime(); // 生成签名
  1990. const signature = CryptoJS.HmacSHA256(
  1991. `${this.liveId}${this.userData.userId}${this.userType}${this.timestamp}`,
  1992. this.timestamp.toString()
  1993. ).toString(CryptoJS.enc.Hex);
  1994. try {
  1995. const baseWsUrl = 'wss://api.fhhx.runtzh.com/ws/app/webSocket';
  1996. // const baseWsUrl = 'ws://192.168.10.166:7114/ws/app/webSocket';
  1997. let wsUrl =
  1998. `${baseWsUrl}?userId=${this.userData.userId}&liveId=${this.liveId}&userType=${this.userType}&timestamp=${this.timestamp}&signature=${signature}`;
  1999. if (this.qrFrom) {
  2000. wsUrl += this.qrFrom;
  2001. }
  2002. // console.log("创建新的WebSocket连接:", wsUrl);
  2003. const socketTask = uni.connectSocket({
  2004. url: wsUrl,
  2005. success: () => console.log("Socket连接请求发送成功"),
  2006. fail: (err) => {
  2007. console.error("Socket连接请求失败:", err);
  2008. this.handleReconnect();
  2009. }
  2010. });
  2011. // 连接打开事件
  2012. socketTask.onOpen((res) => {
  2013. console.log("WebSocket连接已打开");
  2014. this.socket = socketTask;
  2015. this.isConnecting = false;
  2016. this.isSocketOpen = true;
  2017. this.reconnectCount = 0;
  2018. this.resetReconnectState();
  2019. this.heartBeatRetryCount = 0; // 重置心跳重试次数
  2020. this.shownEntryUsers.clear(); // 重连后重置进入提示记录
  2021. this.startHeartBeat();
  2022. });
  2023. // 消息接收事件
  2024. socketTask.onMessage((res) => {
  2025. try {
  2026. const data = JSON.parse(res.data);
  2027. // 处理服务端心跳响应(根据服务端协议调整cmd字段)
  2028. if (data.cmd === "heartBeatAck") {
  2029. this.stopHeartBeat(); // 清除当前超时检测
  2030. this.startHeartBeat(); // 重新启动心跳周期
  2031. return;
  2032. }
  2033. this.handleSocketMessage(res);
  2034. } catch (err) {
  2035. console.error("消息解析异常:", err);
  2036. }
  2037. });
  2038. // 连接错误事件
  2039. socketTask.onError((err) => {
  2040. console.error("WebSocket连接错误:", err);
  2041. this.isSocketOpen = false;
  2042. this.stopHeartBeat();
  2043. this.isConnecting = false;
  2044. this.handleReconnect(); // 错误直接触发重连
  2045. });
  2046. // 连接关闭事件
  2047. socketTask.onClose((res) => {
  2048. console.log("WebSocket连接关闭:", res);
  2049. this.isSocketOpen = false;
  2050. this.isConnecting = false;
  2051. this.stopHeartBeat(); // 清除心跳定时器(复用之前的停止方法)
  2052. if (!this.isManualClose && this.reconnectCount < this.maxReconnectAttempts) {
  2053. this.handleReconnect();
  2054. } else {}
  2055. });
  2056. } catch (e) {
  2057. console.error("创建WebSocket异常:", e);
  2058. this.handleReconnect();
  2059. }
  2060. },
  2061. handleTime(time, duration) {
  2062. // 前置处理:将time转换为毫秒级时间戳
  2063. let timeStamp;
  2064. // 1. 如果time是数字且合理(毫秒级时间戳通常为13位左右的正数),视为有效时间戳
  2065. if (typeof time === 'number' && time > 0 && time < 9999999999999) { // 上限约为3000年
  2066. timeStamp = time;
  2067. }
  2068. // 2. 如果是字符串,尝试解析为日期后转为时间戳
  2069. else if (typeof time === 'string' && time.trim() !== '') {
  2070. // 处理兼容性:将"2025-09-25 17:30:00"转为ISO格式"2025-09-25T17:30:00"
  2071. const isoTime = time.replace(' ', 'T');
  2072. const date = new Date(isoTime);
  2073. // 校验日期是否有效
  2074. if (!isNaN(date.getTime())) {
  2075. timeStamp = date.getTime();
  2076. } else {
  2077. console.error('无效的日期格式:', time);
  2078. return false; // 格式错误时返回false
  2079. }
  2080. } else {
  2081. console.error('time参数必须是有效的时间戳(数字)或日期字符串');
  2082. return false;
  2083. }
  2084. // 后续逻辑保持不变(基于转换后的timeStamp计算)
  2085. const targetTimestamp = timeStamp + duration * 60 * 1000;
  2086. const currentTimestamp = new Date().getTime();
  2087. const timeDiffMs = targetTimestamp - currentTimestamp;
  2088. if (timeDiffMs <= 0) {
  2089. return false;
  2090. }
  2091. const hours = Math.floor(timeDiffMs / (1000 * 60 * 60));
  2092. const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60));
  2093. const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000);
  2094. const formatNum = (num) => num.toString().padStart(2, "0");
  2095. return {
  2096. hours: formatNum(hours),
  2097. minutes: formatNum(minutes),
  2098. seconds: formatNum(seconds)
  2099. };
  2100. },
  2101. // 处理Socket消息
  2102. async handleSocketMessage(message) {
  2103. let data = JSON.parse(message.data)
  2104. const socketMessage = data.data // 服务端返回的消息体
  2105. if (data.code == 200) {
  2106. const messageData = {
  2107. ...socketMessage,
  2108. cmd: socketMessage.cmd || '', // 确保cmd字段存在
  2109. ts: Date.now() // 时间戳
  2110. };
  2111. // 处理服务端返回的sendMsg消息,加入本地列表
  2112. if (socketMessage.cmd == 'sendMsg') {
  2113. if (!this.isSocketAvailable()) {
  2114. uni.showToast({
  2115. title: '连接已断开,正在重试...',
  2116. icon: 'none'
  2117. });
  2118. this.handleReconnect(); // 主动触发重连
  2119. return;
  2120. }
  2121. const oldList = Array.isArray(this.talklist) ? this.talklist : [];
  2122. const newList = [...oldList, messageData];
  2123. this.talklist = newList;
  2124. // 1. 将消息追加到当前直播间的talklist中(响应式更新)
  2125. this.talklist = newList;
  2126. this.scrollToBottom();
  2127. // 2. 延迟下一帧滚动到最新消息(确保DOM已更新)
  2128. // this.$nextTick(() => {
  2129. // const lastIndex = this.talklist.length - 1;
  2130. // this.scrollIntoView = `list_${lastIndex}`;
  2131. // });
  2132. } else if (socketMessage.cmd == 'red') {
  2133. this.redInfo = JSON.parse(socketMessage.data);
  2134. this.isShowRed = socketMessage.status === 1;
  2135. if (this.isShowRed) {
  2136. this.redTimer = setInterval(() => {
  2137. const redCountdown = this.handleTime(this.redInfo.updateTime, this.redInfo
  2138. .duration)
  2139. if (!redCountdown) {
  2140. this.isShowRed = false
  2141. clearInterval(this.redTimer)
  2142. }
  2143. }, 1000);
  2144. }
  2145. } else if (socketMessage.cmd == 'goods') {
  2146. this.goodsCard = JSON.parse(socketMessage.data);
  2147. this.isShowGoods = socketMessage.status == 1;
  2148. } else if (socketMessage.cmd == 'coupon') {
  2149. this.couponInfo = JSON.parse(socketMessage.data);
  2150. this.isShowCoupon = socketMessage.status === 1;
  2151. if (this.isShowCoupon) {
  2152. // this.couponTimer = setInterval(() => {
  2153. // const couponCountdown = this.handleTime(this.couponInfo.updateTime, this.couponInfo.duration)
  2154. // if (!couponCountdown) {
  2155. // this.isShowCoupon = false
  2156. // clearInterval(this.couponTimer)
  2157. // }
  2158. // }, 1000);
  2159. }
  2160. } else if (socketMessage.cmd == 'lottery') {
  2161. const parsedData = JSON.parse(socketMessage.data || '{}'); // 默认为空对象
  2162. this.lotteryInfo = parsedData || {}; // 确保是对象,避免 null
  2163. this.isShowLottery = socketMessage.status === 1;
  2164. if (socketMessage.status != 1) {
  2165. this.isShowLotteryPop = false
  2166. }
  2167. // 清除已有定时器(无论状态是否为1,先清掉旧的)
  2168. clearTimeout(this.lotteryTimer);
  2169. if (this.isShowLottery) {
  2170. this.lotteryTimer = setInterval(() => {
  2171. this.countdown = this.handleTime(this.lotteryInfo.updateTime, this.lotteryInfo
  2172. .duration)
  2173. if (!this.countdown) {
  2174. console.log("倒计时", this.countdown)
  2175. this.isShowLottery = false;
  2176. this.isShowLotteryPop = false;
  2177. clearInterval(this.lotteryTimer)
  2178. }
  2179. }, 1000);
  2180. } else {
  2181. this.isShowLottery = false
  2182. }
  2183. } else if (socketMessage.cmd == 'entry') {
  2184. try {
  2185. if (!this.liveUserCalled) {
  2186. await this.getliveUser(false);
  2187. this.liveUserCalled = true;
  2188. }
  2189. const userIdToEntry = socketMessage.userId;
  2190. const existingIndex = this.liveViewersData.findIndex(item => item.userId ===
  2191. userIdToEntry);
  2192. if (existingIndex === -1) {
  2193. const liveViewers = {
  2194. userId: socketMessage.userId,
  2195. nickName: socketMessage.nickName,
  2196. avatar: socketMessage.avatar
  2197. }
  2198. this.liveViewersData.push(liveViewers);
  2199. this.liveUserTotal++;
  2200. }
  2201. // 解析用户ID(根据实际接口字段调整,此处假设data含userId)
  2202. const userData = JSON.parse(socketMessage.data || '{}');
  2203. const userId = userData.userId || socketMessage.userId; // 兼容不同字段
  2204. if (!userId) return; // 无用户ID不处理
  2205. // 仅新用户(未显示过)才触发提示
  2206. if (!this.shownEntryUsers.has(userId)) {
  2207. this.inAndOut = socketMessage;
  2208. this.showWelcomeMessage = true;
  2209. this.shownEntryUsers.add(userId); // 加入已显示集合
  2210. // 3秒后隐藏提示(可调整时长)
  2211. if (this.welcomeTimer) clearTimeout(this.welcomeTimer);
  2212. this.welcomeTimer = setTimeout(() => {
  2213. this.showWelcomeMessage = false;
  2214. }, 3000);
  2215. }
  2216. } catch (err) {
  2217. console.error("解析entry用户数据失败:", err);
  2218. }
  2219. } else if (socketMessage.cmd == 'out') {
  2220. // console.log("用户离开");
  2221. if (this.liveUserTotal > 0) {
  2222. const userIdToRemove = socketMessage.userId;
  2223. const index = this.liveViewersData.findIndex(item => item.userId === userIdToRemove);
  2224. if (index !== -1) {
  2225. this.liveViewersData.splice(index, 1);
  2226. this.liveUserTotal--; // 根据userId删除对应的用户数据
  2227. }
  2228. }
  2229. this.inAndOut = socketMessage;
  2230. this.showWelcomeMessage = true;
  2231. // 3秒后隐藏提示
  2232. if (this.welcomeTimer) clearTimeout(this.welcomeTimer);
  2233. this.welcomeTimer = setTimeout(() => {
  2234. this.showWelcomeMessage = false;
  2235. }, 3000);
  2236. } else if (socketMessage.cmd == 'live_start' || socketMessage.cmd ==
  2237. 'live_end') {
  2238. // this.getliving(this.liveId);
  2239. // 开始直播,关闭直播
  2240. if (this.liveStartTimer) {
  2241. clearInterval(this.liveStartTimer);
  2242. this.liveStartTimer = null;
  2243. }
  2244. if (this.redTimer) {
  2245. clearInterval(this.redTimer);
  2246. this.redTimer = null;
  2247. }
  2248. // 2. 请求最新直播间数据
  2249. this.getliving(this.liveId); // 注意:需用 await 确保数据更新完成
  2250. // 3. 强制触发视图更新(兜底方案,若上述步骤仍不生效)
  2251. // this.$forceUpdate();
  2252. } else if (socketMessage.cmd == 'Integral') {
  2253. this.integral = {
  2254. msg: socketMessage.msg,
  2255. status: true
  2256. }
  2257. } else if (socketMessage.cmd == 'LotteryDetail') {
  2258. try {
  2259. // 1. 兜底空数据为 "[]",避免 JSON.parse(undefined) 报错
  2260. const parseData = socketMessage.data || '[]';
  2261. // 2. 解析 JSON 并捕获异常
  2262. const prizeData = JSON.parse(parseData);
  2263. // 3. 强制转为数组
  2264. this.prizeInfo = Array.isArray(prizeData) ? prizeData : [];
  2265. } catch (err) {
  2266. console.error('解析抽奖结果失败:', err);
  2267. // 4. 异常时兜底为数组
  2268. this.prizeInfo = [];
  2269. }
  2270. this.isShowPrize = true;
  2271. this.isShowLottery = false;
  2272. this.isShowLotteryPop = false;
  2273. } else if (socketMessage.cmd == 'blockUser') {
  2274. uni.removeStorage({
  2275. key: 'AppToken',
  2276. success: () => {
  2277. uni.reLaunch({
  2278. url: '/pages/auth/login'
  2279. });
  2280. }
  2281. });
  2282. }
  2283. } else {
  2284. uni.showToast({
  2285. title: data.msg,
  2286. icon: 'none'
  2287. });
  2288. }
  2289. },
  2290. sendMsg(retries = 1) {
  2291. // 防止连续点击发送两次(短时锁定)
  2292. if (this.isSending) return;
  2293. this.isSending = true;
  2294. setTimeout(() => {
  2295. this.isSending = false;
  2296. }, 800); // 800ms 内禁止再次发送
  2297. const text = (this.value || '').trim();
  2298. if (!text) {
  2299. uni.showToast({
  2300. title: "不能发送空消息",
  2301. icon: 'none'
  2302. });
  2303. return;
  2304. }
  2305. // 1. 连接状态校验:使用定义后的 retries
  2306. if (!this.isSocketAvailable()) {
  2307. if (retries > 0) {
  2308. uni.showToast({
  2309. title: `连接不稳定,正在重试(${retries}次)...`,
  2310. icon: 'none'
  2311. });
  2312. // 延迟500ms重试,重试次数减1
  2313. setTimeout(() => this.sendMsg(retries - 1), 500);
  2314. } else {
  2315. uni.showToast({
  2316. title: '连接已断开,发送失败',
  2317. icon: 'none'
  2318. });
  2319. this.value = text; // 恢复输入框内容
  2320. }
  2321. return;
  2322. }
  2323. const liveId = this.liveId;
  2324. this.value = ''; // 立即清空输入框,提升体验
  2325. // 构造发送给服务端的消息数据
  2326. const data = {
  2327. liveId,
  2328. userId: this.userData.userId,
  2329. userType: 0,
  2330. cmd: "sendMsg",
  2331. msg: text,
  2332. nickName: this.userData.nickname || '未命名',
  2333. avatar: this.userData.avatar || '/static/images/avatar.png'
  2334. };
  2335. // 发送socket消息
  2336. try {
  2337. this.socket.send({
  2338. data: JSON.stringify(data),
  2339. success: () => {
  2340. // console.log("发送成功");
  2341. this.value = '';
  2342. },
  2343. fail: (err) => {
  2344. console.error("消息发送失败:", err);
  2345. // 2. 发送失败重试:使用定义后的 retries
  2346. if (retries > 0) {
  2347. uni.showToast({
  2348. title: `发送失败,正在重试(${retries}次)`,
  2349. icon: 'none'
  2350. });
  2351. setTimeout(() => this.sendMsg(retries - 1), 500);
  2352. } else {
  2353. uni.showToast({
  2354. title: '发送失败,请稍后再试',
  2355. icon: 'none'
  2356. });
  2357. this.value = text; // 恢复输入框内容
  2358. }
  2359. }
  2360. });
  2361. } catch (err) {
  2362. console.error("发送消息异常:", err);
  2363. if (retries > 0) {
  2364. setTimeout(() => this.sendMsg(retries - 1), 500);
  2365. } else {
  2366. uni.showToast({
  2367. title: '发送失败,请稍后再试',
  2368. icon: 'none'
  2369. });
  2370. this.value = text;
  2371. }
  2372. }
  2373. }
  2374. }
  2375. };
  2376. </script>
  2377. <style scoped lang="scss">
  2378. ::v-deep .u-icon--right {
  2379. justify-content: flex-end !important;
  2380. }
  2381. // 无头像用户文字样式
  2382. .text-white {
  2383. color: #ffffff;
  2384. }
  2385. .text-xs {
  2386. font-size: 16rpx;
  2387. }
  2388. .text-sm {
  2389. font-size: 24rpx;
  2390. }
  2391. .w52,
  2392. .w72 {
  2393. display: flex;
  2394. align-items: center;
  2395. justify-content: center;
  2396. }
  2397. .swiper-wrapper {
  2398. position: relative;
  2399. width: 100%;
  2400. height: 100vh;
  2401. overflow: hidden;
  2402. background-color: #000000;
  2403. .container {
  2404. width: 100%;
  2405. height: 100%;
  2406. position: relative;
  2407. transition: opacity 0.3s ease;
  2408. transform: translateZ(0);
  2409. will-change: opacity;
  2410. }
  2411. }
  2412. .loading-tip {
  2413. position: absolute;
  2414. top: 50%;
  2415. left: 50%;
  2416. transform: translate(-50%, -50%);
  2417. display: flex;
  2418. flex-direction: column;
  2419. align-items: center;
  2420. justify-content: center;
  2421. z-index: 10;
  2422. .loading-text {
  2423. color: #ffffff;
  2424. font-size: 28rpx;
  2425. margin-top: 20rpx;
  2426. }
  2427. }
  2428. /* button自带样式清除 */
  2429. button::after {
  2430. border: none !important;
  2431. padding: 0 !important;
  2432. margin: 0 !important;
  2433. }
  2434. button {
  2435. background-color: transparent !important;
  2436. padding: 0 !important;
  2437. line-height: inherit !important;
  2438. margin: 0 !important;
  2439. width: auto !important;
  2440. font-weight: 500 !important;
  2441. border-radius: none !important;
  2442. }
  2443. .welcome-message {
  2444. position: fixed;
  2445. width: 100%;
  2446. bottom: 38vh;
  2447. left: 50%;
  2448. transform: translateX(-50%);
  2449. color: white;
  2450. padding: 10px 20px;
  2451. border-radius: 20px;
  2452. z-index: 10;
  2453. transition: opacity 0.3s ease;
  2454. }
  2455. .send {
  2456. background-color: #fafafa;
  2457. border-radius: 28rpx;
  2458. padding: 14rpx 16rpx;
  2459. color: #181818;
  2460. font-weight: 500;
  2461. }
  2462. .talk-list {
  2463. max-width: 100%;
  2464. border-radius: 30rpx;
  2465. background-color: rgba(33, 33, 33, 0.5);
  2466. padding: 10rpx 30rpx;
  2467. }
  2468. .content {
  2469. position: relative;
  2470. z-index: 2;
  2471. height: 100%;
  2472. width: 100%;
  2473. top: 0;
  2474. left: 0;
  2475. display: flex;
  2476. flex-direction: column;
  2477. justify-content: space-between;
  2478. .activity-box {
  2479. position: fixed;
  2480. top: 188rpx;
  2481. left: 30rpx;
  2482. z-index: 5;
  2483. display: flex;
  2484. align-items: center;
  2485. .item-box {
  2486. border-radius: 16rpx;
  2487. background-color: rgba(77, 77, 77, 0.5);
  2488. width: 90rpx;
  2489. height: 100rpx;
  2490. margin-right: 20rpx;
  2491. position: relative;
  2492. z-index: 999;
  2493. .tip {
  2494. position: absolute;
  2495. width: 100%;
  2496. bottom: 0;
  2497. color: #fafcff;
  2498. font-size: 26rpx;
  2499. background-color: rgba(15, 15, 15, 0.8);
  2500. border-radius: 16rpx;
  2501. text-align: center;
  2502. }
  2503. .item {
  2504. margin: 0 auto;
  2505. padding: 10rpx 0;
  2506. .img {
  2507. height: 100%;
  2508. }
  2509. }
  2510. }
  2511. }
  2512. .side-group {
  2513. position: absolute;
  2514. top: 65%;
  2515. right: 30rpx;
  2516. z-index: 1000;
  2517. display: flex;
  2518. flex-direction: column;
  2519. align-items: center;
  2520. .side-item {
  2521. font-weight: 500;
  2522. font-size: 24rpx;
  2523. color: #FFFFFF;
  2524. margin-bottom: 32rpx;
  2525. text-align: center;
  2526. .image {
  2527. width: 72rpx;
  2528. height: 72rpx;
  2529. }
  2530. }
  2531. }
  2532. .content-top {
  2533. width: 100%;
  2534. margin-top: 48rpx;
  2535. display: flex;
  2536. justify-content: space-between;
  2537. padding: 0 24rpx;
  2538. box-sizing: border-box;
  2539. .sum {
  2540. width: 80rpx;
  2541. height: 52rpx;
  2542. background: rgba(0, 0, 0, 0.5);
  2543. border-radius: 26rpx 26rpx 26rpx 26rpx;
  2544. font-size: 24rpx;
  2545. color: #FFFFFF;
  2546. text-align: center;
  2547. line-height: 52rpx;
  2548. }
  2549. }
  2550. .follow-btn {
  2551. padding: 8rpx 16rpx;
  2552. background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
  2553. border-radius: 26rpx;
  2554. font-weight: 500;
  2555. font-size: 26rpx;
  2556. color: #FFFFFF;
  2557. }
  2558. }
  2559. .trailer-box {
  2560. position: relative;
  2561. top: 15%;
  2562. display: flex;
  2563. flex-direction: column;
  2564. align-items: center;
  2565. color: #ffffff;
  2566. padding: 20rpx;
  2567. .button {
  2568. margin-top: 20rpx;
  2569. background: #6d7bd4;
  2570. color: #fff;
  2571. border-radius: 20rpx;
  2572. padding: 20rpx 30rpx;
  2573. position: relative;
  2574. z-index: 99999;
  2575. }
  2576. .ash {
  2577. background: #636363;
  2578. }
  2579. .countdown-item {
  2580. display: flex;
  2581. flex-direction: column;
  2582. align-items: center;
  2583. .white {
  2584. width: 60rpx;
  2585. height: 60rpx;
  2586. text-align: center;
  2587. overflow: hidden;
  2588. background: #FFFFFF;
  2589. border-radius: 8rpx;
  2590. margin: 30rpx 10rpx 0;
  2591. font-weight: 600;
  2592. font-size: 24rpx;
  2593. color: #000000;
  2594. line-height: 60rpx;
  2595. }
  2596. }
  2597. .item {
  2598. width: 100%;
  2599. height: 400rpx;
  2600. }
  2601. .name {
  2602. font-size: 34rpx;
  2603. }
  2604. .img {
  2605. margin-bottom: 40rpx;
  2606. width: 240rpx;
  2607. height: 240rpx;
  2608. }
  2609. .title {
  2610. margin-top: 30rpx;
  2611. font-size: 42rpx;
  2612. font-weight: 500;
  2613. }
  2614. }
  2615. .videolist {
  2616. position: relative;
  2617. height: 100vh;
  2618. width: 100%;
  2619. .video {
  2620. height: 100vh;
  2621. width: 100%;
  2622. background-color: rgba(57, 57, 57, 0.4);
  2623. .item {
  2624. width: 100%;
  2625. height: 100%;
  2626. }
  2627. .time {
  2628. color: #ffffff;
  2629. font-size: 20rpx;
  2630. margin-left: 10rpx;
  2631. }
  2632. .lable {
  2633. position: absolute;
  2634. top: 50rpx;
  2635. right: 16rpx;
  2636. background-color: rgba(57, 57, 57, 0.6);
  2637. padding: 4rpx 10rpx;
  2638. color: #fff;
  2639. border-radius: 15rpx;
  2640. }
  2641. }
  2642. .video_row {
  2643. position: absolute;
  2644. top: 20%;
  2645. max-height: 450rpx;
  2646. z-index: 99;
  2647. }
  2648. }
  2649. .prize-card {
  2650. width: 504rpx;
  2651. padding: 40rpx 40rpx 30rpx;
  2652. box-sizing: border-box;
  2653. display: flex;
  2654. flex-direction: column;
  2655. border-radius: 20rpx;
  2656. align-items: center;
  2657. background: linear-gradient(180deg, #f7823f 0%, #ffd4be 27%, #ffffff 100%);
  2658. position: relative;
  2659. .nav-img {
  2660. width: 311rpx;
  2661. position: absolute;
  2662. top: -122rpx;
  2663. left: 50%;
  2664. transform: translateX(-50%);
  2665. }
  2666. .title {
  2667. color: #C32008;
  2668. font-size: 34rpx;
  2669. font-weight: 600;
  2670. margin: 20rpx 0 40rpx;
  2671. }
  2672. .prize-content {
  2673. width: 100%;
  2674. display: flex;
  2675. justify-content: space-between;
  2676. align-items: center;
  2677. font-size: 28rpx;
  2678. margin: 10rpx 0;
  2679. .txt {
  2680. font-weight: 600;
  2681. }
  2682. }
  2683. .tip {
  2684. font-size: 28rpx;
  2685. color: #414141;
  2686. margin: 40rpx 0;
  2687. }
  2688. .button {
  2689. width: 200rpx;
  2690. height: 70rpx;
  2691. line-height: 70rpx;
  2692. background: linear-gradient(180deg, #ff7c30 0%, #FF3A1E 100%);
  2693. border-radius: 28rpx;
  2694. font-weight: 500;
  2695. font-size: 32rpx;
  2696. color: #ffffff;
  2697. text-align: center;
  2698. }
  2699. }
  2700. .no-prize-card {
  2701. width: 504rpx;
  2702. padding: 40rpx 40rpx 30rpx;
  2703. box-sizing: border-box;
  2704. display: flex;
  2705. flex-direction: column;
  2706. border-radius: 20rpx;
  2707. align-items: center;
  2708. position: relative;
  2709. .img {
  2710. margin-top: 40rpx;
  2711. width: 300rpx;
  2712. height: 300rpx;
  2713. }
  2714. .tip {
  2715. font-size: 36rpx;
  2716. color: #414141;
  2717. margin: 40rpx 0;
  2718. }
  2719. .button {
  2720. width: 220rpx;
  2721. height: 80rpx;
  2722. line-height: 80rpx;
  2723. background: linear-gradient(180deg, #fdfbb8 0%, #b79243 100%);
  2724. border-radius: 28rpx;
  2725. font-weight: 500;
  2726. font-size: 32rpx;
  2727. color: #ffffff;
  2728. text-align: center;
  2729. }
  2730. }
  2731. .red-card {
  2732. width: 550rpx;
  2733. height: 636rpx;
  2734. position: relative;
  2735. .img {
  2736. position: absolute;
  2737. width: 100%;
  2738. height: 100%;
  2739. }
  2740. .red-content {
  2741. position: relative;
  2742. z-index: 5;
  2743. display: flex;
  2744. flex-direction: column;
  2745. align-items: center;
  2746. .title {
  2747. font-size: 36rpx;
  2748. color: #FF3A1E;
  2749. margin: 180rpx 0 90rpx;
  2750. }
  2751. .txt {
  2752. font-size: 28rpx;
  2753. color: #FFECC3;
  2754. margin: 80rpx 0 40rpx;
  2755. }
  2756. .button {
  2757. width: 392rpx;
  2758. height: 96rpx;
  2759. line-height: 96rpx;
  2760. background: linear-gradient(180deg, #FFF4D5 0%, #FFE5B1 100%);
  2761. border-radius: 48rpx 48rpx 48rpx 48rpx;
  2762. font-weight: 600;
  2763. font-size: 36rpx;
  2764. color: #C32008;
  2765. text-align: center;
  2766. }
  2767. }
  2768. }
  2769. .integral-box {
  2770. min-width: 400rpx;
  2771. max-width: 600rpx;
  2772. display: flex;
  2773. flex-direction: column;
  2774. align-items: center;
  2775. border-radius: 20rpx;
  2776. overflow: hidden;
  2777. .top {
  2778. width: 100%;
  2779. position: relative;
  2780. .title {
  2781. width: 100%;
  2782. font-weight: 600;
  2783. font-size: 40rpx;
  2784. color: #FFFFFF;
  2785. text-shadow: 0px 4px 8px rgba(255, 89, 2, 0.8);
  2786. position: absolute;
  2787. top: 50rpx;
  2788. text-align: center;
  2789. }
  2790. .photo {
  2791. width: 100%;
  2792. }
  2793. }
  2794. .item {
  2795. padding: 20rpx;
  2796. .title {
  2797. font-weight: 500;
  2798. font-size: 32rpx;
  2799. text-align: center;
  2800. }
  2801. .button {
  2802. font-size: 32rpx;
  2803. margin-top: 20rpx;
  2804. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  2805. color: #fff;
  2806. text-align: center;
  2807. padding: 18rpx 60rpx;
  2808. border-radius: 10rpx;
  2809. font-weight: 500;
  2810. }
  2811. }
  2812. }
  2813. .goods {
  2814. position: fixed;
  2815. bottom: 140rpx;
  2816. right: 104rpx;
  2817. z-index: 5;
  2818. background-color: #fff;
  2819. border-radius: 20rpx;
  2820. overflow: hidden;
  2821. width: 280rpx;
  2822. padding: 4rpx;
  2823. .top {
  2824. position: absolute;
  2825. top: 4rpx;
  2826. display: flex;
  2827. justify-content: space-between;
  2828. align-items: center;
  2829. color: #fff;
  2830. width: 100%;
  2831. padding-right: 10rpx;
  2832. box-sizing: border-box;
  2833. .left {
  2834. background-color: rgba(0, 0, 0, 0.8);
  2835. padding: 12rpx;
  2836. font-size: 22rpx;
  2837. display: flex;
  2838. justify-content: space-between;
  2839. align-items: center;
  2840. border-radius: 10rpx;
  2841. }
  2842. }
  2843. .photo {
  2844. width: 100%;
  2845. height: 180rpx;
  2846. border-radius: 16rpx 16rpx 0 0;
  2847. overflow: hidden;
  2848. }
  2849. .item {
  2850. padding: 4rpx;
  2851. .price {
  2852. font-size: 30rpx;
  2853. .red {
  2854. color: #FF5701;
  2855. font-weight: 600;
  2856. margin-right: 10rpx;
  2857. }
  2858. .del {
  2859. color: #828282;
  2860. font-weight: 500;
  2861. font-size: 28rpx;
  2862. text-decoration: line-through
  2863. }
  2864. }
  2865. .title {
  2866. font-weight: 500;
  2867. font-size: 30rpx;
  2868. margin: 10rpx 0 12rpx;
  2869. }
  2870. .button {
  2871. background: linear-gradient(270deg, #ff4702 0%, #fe6304 100%);
  2872. color: #fff;
  2873. text-align: center;
  2874. padding: 16rpx 0;
  2875. border-radius: 10rpx;
  2876. font-weight: 500;
  2877. font-size: 30rpx;
  2878. }
  2879. }
  2880. }
  2881. .coupon-pop {
  2882. position: fixed;
  2883. bottom: 140rpx;
  2884. right: 100rpx;
  2885. z-index: 5;
  2886. border-radius: 20rpx;
  2887. width: 320rpx;
  2888. .coupon-block {
  2889. width: 100%;
  2890. position: relative;
  2891. .item {
  2892. width: 100%;
  2893. position: absolute;
  2894. top: 20rpx;
  2895. display: flex;
  2896. flex-direction: column;
  2897. align-items: center;
  2898. color: #fff;
  2899. .title {
  2900. font-weight: 500;
  2901. font-size: 30rpx;
  2902. margin: 16rpx 0 12rpx;
  2903. }
  2904. .price {
  2905. font-size: 40rpx;
  2906. .bold {
  2907. font-size: 56rpx;
  2908. font-weight: 600;
  2909. }
  2910. }
  2911. .txt {
  2912. font-weight: 500;
  2913. font-size: 30rpx;
  2914. margin: 5rpx 0;
  2915. }
  2916. .button {
  2917. background: linear-gradient(270deg, #fffce1 0%, #ffeaaf 100%);
  2918. color: #ff0004;
  2919. text-align: center;
  2920. padding: 16rpx 0;
  2921. border-radius: 40rpx;
  2922. font-weight: 500;
  2923. font-size: 30rpx;
  2924. width: 70%;
  2925. margin-top: 26rpx;
  2926. }
  2927. }
  2928. .bg {
  2929. height: 432rpx;
  2930. width: 100%;
  2931. }
  2932. .nav {
  2933. position: absolute;
  2934. height: 120rpx;
  2935. top: -120rpx;
  2936. left: 0;
  2937. width: 100%;
  2938. z-index: 6;
  2939. }
  2940. .close {
  2941. position: absolute;
  2942. right: 10rpx;
  2943. top: 10rpx;
  2944. }
  2945. }
  2946. }
  2947. .icon-bg {
  2948. background-color: rgba(57, 57, 57, 0.8);
  2949. border-radius: 50%;
  2950. width: 88rpx;
  2951. height: 88rpx;
  2952. display: flex;
  2953. justify-content: center;
  2954. align-items: center;
  2955. transition: transform 0.2s ease;
  2956. }
  2957. .list {
  2958. width: 80%;
  2959. margin-bottom: 20rpx;
  2960. animation: xxxawdawd .2s;
  2961. }
  2962. @keyframes xxxawdawd {
  2963. from {
  2964. margin-top: 0rpx;
  2965. opacity: 0;
  2966. }
  2967. to {
  2968. // margin-top: 20rpx;
  2969. opacity: 1;
  2970. }
  2971. }
  2972. .shop-prompt {
  2973. position: absolute;
  2974. bottom: 750rpx;
  2975. left: 24rpx;
  2976. padding: 6rpx 20rpx;
  2977. background: rgba(230, 154, 34, 0.7);
  2978. border-radius: 24rpx;
  2979. z-index: 9;
  2980. font-weight: 500;
  2981. color: #FFFFFF;
  2982. transition: opacity 0.3s ease;
  2983. }
  2984. .red-box {
  2985. .button {
  2986. margin: 0 auto;
  2987. width: 80%;
  2988. line-height: 88rpx;
  2989. height: 88rpx;
  2990. background: linear-gradient(90deg, #FF5701 0%, #FFB501 100%);
  2991. box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(238, 124, 80, 0.2);
  2992. border-radius: 44rpx 44rpx 44rpx 44rpx;
  2993. font-weight: 600;
  2994. font-size: 32rpx;
  2995. color: #FFFFFF;
  2996. text-align: center;
  2997. }
  2998. }
  2999. .view-box {
  3000. position: relative;
  3001. height: 40vh;
  3002. /* 设置弹出层高度为视窗高度的70% */
  3003. padding: 40rpx 0rpx 120rpx;
  3004. box-sizing: border-box;
  3005. display: flex;
  3006. flex-direction: column;
  3007. .scroll-content {
  3008. flex: 1;
  3009. overflow-y: auto;
  3010. padding: 0 40rpx;
  3011. }
  3012. .bottom {
  3013. padding: 20rpx 40rpx;
  3014. position: absolute;
  3015. bottom: 0;
  3016. width: 100%;
  3017. box-shadow: 0rpx -4rpx 10rpx 0rpx rgba(195, 195, 195, 0.3);
  3018. background: #fff;
  3019. }
  3020. }
  3021. // 抽奖
  3022. .prize-box {
  3023. position: relative;
  3024. .nav-img {
  3025. width: 311rpx;
  3026. position: absolute;
  3027. top: -122rpx;
  3028. left: 50%;
  3029. transform: translateX(-50%);
  3030. }
  3031. .bg-img {
  3032. position: absolute;
  3033. top: 0;
  3034. left: 0;
  3035. width: 100%;
  3036. height: 100%;
  3037. z-index: 1;
  3038. }
  3039. .prize-content {
  3040. position: relative;
  3041. z-index: 2;
  3042. padding: 24rpx 0 68rpx;
  3043. .white-item {
  3044. width: 40rpx;
  3045. height: 40rpx;
  3046. text-align: center;
  3047. overflow: hidden;
  3048. background: #FFFFFF;
  3049. box-shadow: inset 0rpx 2rpx 8rpx 0rpx #FFEBB2;
  3050. border-radius: 8rpx;
  3051. margin: 4rpx;
  3052. font-weight: 600;
  3053. font-size: 24rpx;
  3054. color: #F85D22;
  3055. line-height: 40rpx;
  3056. }
  3057. .item-group {
  3058. width: 100%;
  3059. }
  3060. .point-group {
  3061. margin: 20rpx 0 50rpx;
  3062. display: flex;
  3063. gap: 6rpx;
  3064. .item {
  3065. width: 20rpx;
  3066. height: 8rpx;
  3067. background: rgba(255, 255, 255, 0.5);
  3068. border-radius: 4rpx 4rpx 4rpx 4rpx;
  3069. }
  3070. .selected {
  3071. background: #FFEB66;
  3072. }
  3073. }
  3074. .button {
  3075. margin-top: 30rpx;
  3076. width: 520rpx;
  3077. height: 88rpx;
  3078. line-height: 88rpx;
  3079. background: linear-gradient(180deg, #FFF4D6 0%, #FFEB66 100%);
  3080. box-shadow: 0rpx 10rpx 8rpx 4rpx rgba(246, 82, 25, 0.5);
  3081. border-radius: 44rpx;
  3082. font-weight: 500;
  3083. font-size: 36rpx;
  3084. color: #F4410B;
  3085. text-align: center;
  3086. }
  3087. }
  3088. }
  3089. .shoppop {
  3090. padding: 22rpx 16rpx;
  3091. .shoppop-top {
  3092. display: flex;
  3093. justify-content: space-between;
  3094. align-items: center;
  3095. padding: 0 16rpx 22rpx;
  3096. .search-input {
  3097. width: 414rpx;
  3098. height: 76rpx;
  3099. background: #FFFFFF;
  3100. border-radius: 36rpx;
  3101. margin-left: 20rpx;
  3102. padding: 0 32rpx;
  3103. box-sizing: border-box;
  3104. font-size: 24rpx;
  3105. margin-right: 24rpx;
  3106. }
  3107. .search-top {
  3108. font-size: 20rpx;
  3109. color: #222222;
  3110. }
  3111. }
  3112. .shop-list {
  3113. overflow: hidden;
  3114. .list-item {
  3115. display: flex;
  3116. align-items: center;
  3117. padding: 20rpx 16rpx;
  3118. background: #FFFFFF;
  3119. border-radius: 16rpx;
  3120. margin-bottom: 16rpx;
  3121. .goods-img {
  3122. width: 200rpx;
  3123. height: 200rpx;
  3124. border-radius: 16rpx;
  3125. overflow: hidden;
  3126. position: relative;
  3127. margin-right: 24rpx;
  3128. .img {
  3129. width: 100%;
  3130. height: 100%;
  3131. }
  3132. .goods-label {
  3133. position: absolute;
  3134. top: 0;
  3135. width: 64rpx;
  3136. height: 40rpx;
  3137. background: rgba(0, 0, 0, 0.5);
  3138. border-radius: 16rpx 0rpx 16rpx 0rpx;
  3139. text-align: center;
  3140. font-weight: 500;
  3141. font-size: 28rpx;
  3142. color: #FFFFFF;
  3143. }
  3144. }
  3145. .goods-right {
  3146. flex: 1;
  3147. .goods-title {
  3148. font-weight: 500;
  3149. font-size: 30rpx;
  3150. color: #000000;
  3151. margin-bottom: 10rpx;
  3152. }
  3153. .goods-details {
  3154. font-size: 24rpx;
  3155. color: #999999;
  3156. margin: 10rpx 0 20rpx;
  3157. }
  3158. .goods-people {
  3159. font-size: 22rpx;
  3160. color: #E69A22;
  3161. height: 56rpx;
  3162. }
  3163. .goods-shop {
  3164. display: flex;
  3165. justify-content: space-between;
  3166. .nummber {
  3167. color: #FF5C03;
  3168. font-size: 22rpx;
  3169. font-weight: 500;
  3170. }
  3171. .btn-group {
  3172. text-align: center;
  3173. line-height: 56rpx;
  3174. .collect-btn {
  3175. width: 72rpx;
  3176. height: 100%;
  3177. background: #F5F7FA;
  3178. border-radius: 8rpx 0rpx 0rpx 8rpx;
  3179. }
  3180. .shop-btn {
  3181. width: 152rpx;
  3182. background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
  3183. border-radius: 0rpx 8rpx 8rpx 0rpx;
  3184. font-weight: 500;
  3185. font-size: 30rpx;
  3186. color: #FFFFFF;
  3187. }
  3188. }
  3189. }
  3190. }
  3191. }
  3192. }
  3193. }
  3194. </style>