living.vue 95 KB

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