123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295 |
- <template>
- <view class="swiper-wrapper">
- <swiper class="swiper-container" :current="currentSwiperIndex" :circular="false" vertical
- @change="onSwiperChange" :style="{height: '100vh'}" :duration="300">
- <swiper-item v-for="(liveItem, index) in list" :key="liveItem.liveId">
- <view class="container" :class="{active: currentSwiperIndex === index}">
- <!-- 原有直播间内容结构保持不变 -->
- <view class="blackbg"></view>
- <view class="content">
- <!-- 页面内容 -->
- <view style=" position: fixed;top: 0;z-index: 5;" class="content-top">
- <view class="u-flex-y-center">
- <image @click="goBack" style="width: 60rpx;height: 64rpx;margin-right: 26rpx;"
- src="@/static/images/live/return.png"></image>
- <view class=" align-center"
- style="padding: 6rpx 4rpx;height: 64rpx;background: rgba(0,0,0,0.5);border-radius: 32rpx;">
- <u-avatar :src="liveItem.liveImgUrl||$img.logo" size="32"></u-avatar>
- <view class="colorf" style="margin-left: 8rpx;">
- <view>{{liveItem.liveName?truncateString(liveItem.liveName,5):"未命名"}}</view>
- <view style="font-size: 16rpx;">
- {{ liveItem.liveViewData?.follow || liveItem.liveViewData?.follow === 0 ? liveItem.liveViewData.follow : 0 }}位粉丝
- </view>
- </view>
- <view v-if="liveItem.isFollow" @click="onFollow(liveItem)" class="follow-btn ml20">
- 关注</view>
- <view v-else @click="onFollow(liveItem)" class="follow-btn ml20">已关注</view>
- </view>
- </view>
- <view class="u-flex-end align-center" @click="showadd=!showadd">
- <image class="w52 h52 mr4" v-for="(item,viewerIndex) in liveItem.filteredViewers"
- :key="viewerIndex" style="border-radius: 26rpx;" :src="item.avatar||$img.logo">
- </image>
- <view class="sum">{{liveItem.liveUserTotal||0}}</view>
- </view>
- </view>
- <!-- 页面内容 -->
- <view style=" position: fixed;top:100rpx;left: 0rpx; z-index: 5;" class="content-top">
- <view class="u-flex-y-center">
- <image @click="onRed(liveItem)" v-if="liveItem.redInfo?.redStatus==1"
- style="width: 70rpx;height: 70rpx;" src="@/static/images/hongbao.png"></image>
- </view>
- </view>
- <!-- 右边的 -->
- <view :class=" liveItem.showType==1 ? 'siderow-group' : 'side-group'">
- <view class="side-item">
- <image @click="onLike(liveItem)" src="/static/images/live/like.png"></image>
- <view>{{liveItem.liveViewData?.like||0}}</view>
- </view>
- <view class="side-item">
- <image @click="goStore(liveItem)" src="/static/images/live/shop.png"></image>
- <view>店铺</view>
- </view>
- <view class="side-item">
- <button open-type="share">
- <image src="/static/images/live/share.png" mode="widthFix"></image>
- </button>
- <view>分享</view>
- </view>
- </view>
- <view class="shop-prompt u-flex-y-center"
- v-if="liveItem.showPurchasePrompt&&liveItem.orderUser?.count">
- <image class="w32 h32 mr8" src="/static/images/live/shopping.png"></image>
- <text> {{liveItem.orderUser.userName ? maskString(liveItem.orderUser.userName) : ''}} 等
- {{liveItem.orderUser.count || 0}}
- 人正在去购买</text>
- </view>
- <!-- object-fit:fill; -->
- <view class="videolist " style="margin: auto 0">
- <view class="video" style="height:100vh">
- <!-- 修改video组件以支持HLS -->
- <!-- showType 1 横屏 2 竖屏 -->
- <video v-if="liveItem.livingUrl" :id="'myVideo_' + liveItem.liveId"
- :class="liveItem.showType == 1 ? 'video_row' : 'videotop'" :src="liveItem.livingUrl"
- :autoplay="currentSwiperIndex === index" :controls='false' object-fit='contain'
- :custom-cache="false" :enable-progress-gesture="false"
- vslide-gesture-in-fullscreen='true' :show-center-play-btn="false"
- :http-cache="false" @error="videoError">
- </video>
- <video v-if="liveItem.videoUrl"
- :class="liveItem.showType == 1 ? 'video_row' : 'videotop'" :src="liveItem.videoUrl"
- :autoplay="currentSwiperIndex === index" :controls='false' object-fit='contain'
- :custom-cache="false" :enable-progress-gesture="false"
- vslide-gesture-in-fullscreen='true' :show-center-play-btn="false"
- :http-cache="false" loop @error="videoError">
- </video>
- <!-- 加载提示 -->
- <view v-if="liveItem.loading" class="loading-tip">
- <u-loading mode="circle" color="#ffffff" size="36"></u-loading>
- <text class="loading-text">加载中...</text>
- </view>
- </view>
- </view>
- <view class="pb40 mt90" style="position: fixed;bottom: 0;">
- <view class="w100 h300 mt20">
- <scroll-view enable-flex scroll-y="true" class="talk p20 scrolly flex-1 column"
- style="width: calc(100% - 40rpx);height: calc(100% - 40rpx);"
- :scroll-into-view="liveItem.scrollIntoView">
- <view>
- <view class="list justify-start" v-for="(item,talkIndex) in liveItem.talklist"
- :key="talkIndex" v-show="item.cmd=='announcement'">
- <view class="talk-list ml16 justify-start">
- <view class="fs24">
- <text class='fs24 colorf'>
- {{item.msg}}直播间{{liveItem.messageContent}}</text>
- </view>
- </view>
- </view>
- </view>
- <view class="list justify-start" v-for="(item,talkIndex) in liveItem.talklist"
- :key="talkIndex" :id="`list_${talkIndex}`"
- v-show="item.cmd!='red'&&item.cmd!='out'&&item.cmd!='entry'">
- <view class="talk-list ml16 justify-start">
- <view class="fs24">
- <text style="color: #FFDA73;">{{item.nickName}}:</text>
- <text class='fs24 colorf'>{{item.msg}}</text>
- </view>
- </view>
- </view>
- <view v-if="liveItem.showWelcomeMessage" class="welcome-message">
- <view class="list justify-start" v-for="(item,talkIndex) in liveItem.talklist"
- :key="talkIndex" v-show="item.cmd=='entry'||item.cmd=='out'">
- <view class="talk-list ml16 justify-start">
- <view class="fs24">
- <text style="color: #ff89d6;">{{item.nickName}} </text>
- <text class='fs24 colorf'>
- {{item.msg}}直播间{{liveItem.messageContent}}</text>
- </view>
- </view>
- </view>
- </view>
- </scroll-view>
- </view>
- <view class="justify-between p24">
- <view class="u-flex-y-center"
- style="background:rgba(157, 157, 157, 0.8);padding:18rpx 14rpx 18rpx 32rpx;width: 526rpx;box-sizing:border-box;border-radius:36rpx;">
- <u-input :placeholder="liveItem.placeholderText" border="none"
- customStyle='font-size:24rpx;' v-model="liveItem.value" shape='circle'
- color='#fff' placeholderStyle='color:#e7e7e7' class="ml20"
- @keydown.enter="sendMsg(liveItem)" @confirm="sendMsg(liveItem)">
- </u-input>
- </view>
- <view class="justify-between mr30 align-center">
- <view class="icon-bg ml20" @click="liveItem.shopping=!liveItem.shopping">
- <image src="/static/images/shopping.png" class="w48 h48"></image>
- </view>
- <view class="icon-bg ml20" @click="liveItem.showziliao=!liveItem.showziliao">
- <image src="/static/images/more-icon.png" class="w48 h48"></image>
- </view>
- </view>
- </view>
- </view>
- </view>
- <!-- 弹窗组件保持不变 -->
- <u-popup :show="showadd" @close="close" @open="openViews" round='20rpx' bgColor='#ffffff'>
- <view class="view-box">
- <view class="t-c fs30">在线观众</view>
- <scroll-view scroll-y class="scroll-content" :style="{height: scrollHeight + 'px'}"
- @scrolltolower="handleScrollToLower">
- <view class="fs24 u-flex-y-center mb20" v-for="(item,index) in liveViewers"
- :key="index">
- <view
- :style="{color: index === 0 ? '#FF3B30' : index === 1 ? '#FF9500' : index === 2 ? '#FFCC00' : '#8E8E93',fontWeight: index < 3 ? 'bold' : 'normal',width: '50rpx'}"
- class="mr10">{{index+1}}</view>
- <u-avatar :src="item.avatar||$img.logo" size="32"></u-avatar>
- <text class="ml16">{{item.nickName||"未命名"}}</text>
- </view>
- <view class="no-more" v-if="viewNoMoreData && liveViewers.length > 0">
- <text>没有更多了</text>
- </view>
- </scroll-view>
- <view class="fs24 u-flex-y-center bottom">
- <view class="mr10" style="width:50rpx">我</view>
- <u-avatar :src="livedata.liveImgUrl||$img.logo" size="32"></u-avatar>
- <text class="ml16">{{livedata.liveName||"未命名"}}</text>
- </view>
- </view>
- </u-popup>
- <u-popup :show="shopping" @close="closeShop" @open="openShop" round='20rpx' bgColor='f3f5f9'>
- <view class="shoppop">
- <view class="shoppop-top">
- <u-avatar :src="store.logoUrl" size="36" class="ml16"></u-avatar>
- <view class="search-input u-flex-y-center">
- <image style="width: 24rpx;height: 24rpx;margin-right: 16rpx;"
- src="@/static/images/search.png">
- </image>
- <input placeholder="请搜索商品" v-model="inputInfo" @input="handleSearchInput" />
- </view>
- <view class="t-c search-top" style="margin-right: 48rpx;">
- <image @click="onStoreCollect" v-if="store.isFavorite"
- style="width: 32rpx;height: 32rpx;" src="@/static/images/collect_select.png">
- </image>
- <image v-else @click="onStoreCollect" style="width: 32rpx;height: 32rpx;"
- src="@/static/images/collect.png"></image>
- <view>收藏</view>
- </view>
- <view class="t-c search-top" @click="goOrderList">
- <image style="width: 32rpx;height: 32rpx;" src="@/static/images/order.png"></image>
- <view>订单</view>
- </view>
- </view>
- <scroll-view enable-flex scroll-y class="shop-list" :style="{ height: boxHeight + 'px' }">
- <view class="list-item " v-for="(item,index) in products" :key="index">
- <view class="goods-img">
- <image :src="item.imgUrl" mode="widthFix"></image>
- <view class="goods-label">{{index+1}}</view>
- </view>
- <view class="goods-right">
- <view class="goods-title">{{item.productName}}</view>
- <view class="goods-people">{{item.sales}} 人已购</view>
- <view class="goods-shop">
- <text class="nummber"><text
- style="font-size: 20rpx;font-weight: 600;">¥</text><text
- style="font-size: 36rpx;font-weight: bold;">{{Math.trunc(item.price)}}</text>.{{getPureDecimal(item.price)?getPureDecimal(item.price):'00'}}/日</text>
- <view class="btn-group u-flex-y-center">
- <view class="collect-btn">
- <image v-if="item.isFavorite" @click="onGoodsCollect(item)"
- style="width: 32rpx;height: 32rpx;"
- src="/static/images/collect_select.png">
- </image>
- <image v-else @click="onGoodsCollect(item)"
- style="width: 32rpx;height: 32rpx;"
- src="/static/images/collect.png">
- </image>
- </view>
- <view v-if="item.status==1" class="shop-btn"
- @click="goShop(item.productId,item.goodsId)">去购买
- </view>
- <view v-else-if="item.status==0" @click="goShop(item.productId)"
- class="shop-btn">
- 已下架</view>
- </view>
- </view>
- </view>
- </view>
- </scroll-view>
- </view>
- </u-popup>
- </view>
- <<<<<<< HEAD
- </swiper-item>
- </swiper>
- <!-- 预加载指示器 -->
- <view v-if="preloading" class="preload-indicator">
- <u-loading mode="circle" color="#ffffff" size="28"></u-loading>
- =======
- <view class="justify-between p24">
- <view class="u-flex-y-center"
- style="background:rgba(157, 157, 157, 0.8);padding:18rpx 14rpx 18rpx 32rpx;width: 526rpx;box-sizing:border-box;border-radius:36rpx;">
- <u-input :placeholder="placeholderText" border="none" customStyle='font-size:24rpx;'
- v-model="value" shape='circle' color='#fff' placeholderStyle='color:#e7e7e7' class="ml20"
- @keydown.enter="sendMsg">
- </u-input>
- <!-- <image @click="sendMsg" class="w44 h44" src="@/static/images/live/like.png"></image> -->
- </view>
- <!-- :disabled='talkdisabled' ></u-input> -->
- <!-- <view @click="sendMsg" class="colorf center ml10 fs24">发送</view> -->
- <view class="justify-between mr30 align-center">
- <!-- <view class="icon-bg ml20" @click="answerbtn=!answerbtn">
- <image src="/static/images/redbag.png" class="w40 h40"></image>
- </view> -->
- <view class="icon-bg ml20" @click="shopping=!shopping">
- <image src="/static/images/shopping.png" class="w48 h48"></image>
- </view>
- <view class="icon-bg ml20" @click="showziliao=!showziliao">
- <image src="/static/images/more-icon.png" class="w48 h48"></image>
- </view>
- <!-- <view class="icon-bg ml20" :class="{ 'zoom-button-active': isZoom }"
- @touchstart="handleTouchStart" @touchend="handleTouchEnd">
- <image src="/static/images/dianzan.png" class="w40 h40"></image>
- </view> -->
- </view>
- </view>
- </view>
- >>>>>>> 57028795d3bcee2e15cce5538d4362a47313f66a
- </view>
- </view>
- </template>
- <script>
- import Hls from 'hls.js';
- import CryptoJS from 'crypto-js'
- import {
- liveList
- } from '@/api/list'
- import {
- liveRed, // 点击领红包
- liveDataLike, // 点赞
- collectStore, // 店铺收藏/取消收藏
- collectGoods, // 商品收藏/取消收藏
- store, // 查询店铺
- follow, // 关注/取消关注
- watchUserList, //获取直播间用户(展示在线用户)
- liveMsg, //获取最近聊天记录
- // 小黄车
- liveStore, //店铺展示,
- // liveGoodsDetail, //商品详情,
- liveOrderUser, //正在购买
- getLiveInfo, //获取直播间信息接口
- getLiveViewData //直播间点赞、关注、在线人数数据
- } from '@/api/live'
- import {
- liveOrderList, // 订单列表
- } from '@/api/order'
- import parse from '../../uni_modules/uview-plus/libs/config/props/parse';
- import {
- LiveWS
- } from '@/utils/liveWS.js'
- import {
- getlive,
- // gettextlist,
- getAnswerlist,
- submitAnswer
- } from '@/api/home'
- // var wsUrl = "ws://192.168.10.166:7114/app/webSocket";
- <<<<<<< HEAD
- // var wsUrl = "ws://192.168.10.166:7114/app/webSocket"; //余红奇
- // var wsUrl = "ws://192.168.10.125:7114/app/webSocket"; //涂小龙
- var wsUrl = "wss://live.test.ylrztop.com/ws/live-api/app/webSocket"; //余红奇
- =======
- var wsUrl = "ws://192.168.10.166:7114/app/webSocket"; //余红奇
- // var wsUrl = "ws://192.168.10.125:7114/app/webSocket"; //涂小龙
- // var wsUrl = "ws://live.test.ylrztop.com/prod-api/app/webSocket"; //余红奇
- >>>>>>> 57028795d3bcee2e15cce5538d4362a47313f66a
- // var wsUrl = "ws://nd383294.natappfree.cc/app/webSocket"; //余红奇
- // var wsUrl = "ws://v56c9b8e.natappfree.cc/app/webSocket"; //余红奇
- // var wsUrl = "ws://192.168.10.170:7114/app/webSocket"; //陈果
- // var wsUrl = "ws://live.ylrzcloud.com/socket/app/webSocket";
- var pingpangTimes = null;
- var initTimes = null;
- var isSocketOpen = false;
- var socket = null;
- export default {
- data() {
- return {
- socketInstances: {}, // 改为对象存储多个socket实例
- currentSwiperIndex: 0, // 当前swiper索引
- preloadCount: 5, // 预加载直播间数量
- list: [], // 直播间列表
- preloading: false, // 预加载状态
- socketInstances: {},
- liveUserTotal: null,
- viewPageSize: 10, // 每页数量
- viewPageNum: 1, // 当前页码
- viewLoading: false, // 是否正在加载
- viewNoMoreData: false, // 是否没有更多数据
- scrollHeight: 0,
- scrollTimer: null, // 滚动防抖定时器
- socketInstance: null, // 统一管理 socket 实例
- reconnectCount: 0,
- maxReconnectAttempts: 3,
- isManualClose: false, // 标记是否手动关闭
- showRed: true,
- redInfo: {},
- inputInfo: '',
- searchTimer: null,
- storeId: null,
- reconnectTimer: null,
- isCollect: false,
- showPurchasePrompt: false,
- purchasePromptTimer: null,
- prevOrderCount: 0, // 用于记录上一次的购买人数
- videoUrl: null,
- showType: 1, //横屏1 竖屏2
- boxHeight: 300, //小黄车高度
- isFollow: true,
- liveViewData: {},
- liveViewers: [], //观众
- likeName: 0,
- hlsPlayer: null, // HLS播放器实例,
- livingUrl: "",
- products: {},
- store: {},
- orderUser: {}, //正在购买
- userType: 0,
- timestamp: '',
- liveId: null,
- // userId: uni.getStorageSync("userInfo.userId"),
- placeholderText: '说点什么...',
- isZoom: false, //点赞按钮控制是否放大
- userinfo: '', //用户信息
- // path: 'http://192.168.10.166/dev-api', //余红奇
- // path: 'http://v56c9b8e.natappfree.cc', //余红奇
- // path: 'live.test.ylrztop.com/prod-api', //余红奇
- // path: 'http://192.168.10.170/dev-api', //陈果
- value: '',
- talkdisabled: false, //输入框是否禁用
- autoplay: false, //视频自动播放
- showadd: false,
- talklist: [],
- scrollIntoView: '',
- videoContext: '',
- thistime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
- showWelcomeMessage: false,
- isSubmit: false,
- messageContent: "",
- showziliao: false,
- isScreen: true,
- shopping: false, //小黄车弹窗
- scrollTop: 0, //弹幕
- old: {
- scrollTop: 0
- },
- livedata: {}, //直播间点赞、关注、在线人数数据
- };
- },
- onLoad(options) {
- this.userinfo = JSON.parse(uni.getStorageSync("userInfo"))
- <<<<<<< HEAD
- // 初始化直播间列表
- this.initLiveList(options);
- =======
- if (options.liveId) {
- this.liveId = options.liveId; // 仅当 liveId 变化时更新
- }
- const platform = uni.getSystemInfoSync().platform;
- if (['mp-weixin', 'mp-alipay', 'mp-baidu', 'mp-toutiao'].includes(platform)) {
- // 确保 API 存在再调用
- if (uni.showShareMenu) {
- uni.showShareMenu({
- withShareTicket: true, // 可选参数,根据需求配置
- success: () => {
- console.log('分享菜单显示成功');
- },
- fail: (err) => {
- console.error('分享菜单显示失败:', err);
- }
- });
- } else {
- console.warn('当前平台不支持 uni.showShareMenu');
- }
- } else {
- console.log('当前平台无需显示分享菜单');
- }
- >>>>>>> 57028795d3bcee2e15cce5538d4362a47313f66a
- },
- onShareAppMessage() {
- return {
- // title: this.product.title,
- title: this.livedata.liveName,
- path: '/pages/home/index',
- imageUrl: this.products.image,
- success(res) {
- console.log("分享成功", res);
- },
- fail(err) {
- console.error("分享失败", err);
- }
- };
- },
- computed: {
- filteredViewers() {
- if (!this.liveViewers) {
- return
- } else {
- return this.liveViewers.slice(0, 3);
- }
- }
- },
- mounted() {
- // this.getLiveMsg() // 获取最近聊天记录
- // this.onLike()
- this.getliveViewData() ////直播间点赞、关注、在线人数数据
- // this.intervalId = setInterval(() => {
- // this.getliveViewData();
- // }, 60 * 1000);
- // this.getLiveinformation() // 获取直播间信息接口
- this.getliveOrder() //正在购买
- // this.getliveStore() // 获取小黄车 店铺展示
- // this.getliveGoods() // 获取小黄车 商品详情
- this.getliveUser() // 获取直播间用户
- this.initTime()
- // this.initWebSocket()
- this.initSocket()
- var that = this;
- uni.$on('initSocket', () => {
- that.initSocket()
- })
- uni.$on('sendMsg', (item) => {
- that.sendMsg(item)
- })
- uni.$on('closeWebSocket', () => {
- that.closeWebSocket()
- })
- this.getEWechatSdk();
- this.getliving() //hls
- // this.gettalklist()
- // this.getAnswerlists()
- },
- onHide() {
- clearInterval(this.intervalId); // 页面隐藏时清理
- },
- onUnload() {
- // 关闭所有WebSocket连接
- this.closeAllWebSockets();
-
- // 移除所有全局事件监听
- this.removeAllEventListeners();
-
- // 清理定时器
- this.clearAllTimers();
-
- // 销毁HLS播放器
- if (this.hlsPlayer) {
- this.hlsPlayer.destroy();
- this.hlsPlayer = null;
- }
- },
- watch: {
- // 监听orderUser.count的变化
- 'orderUser.count': {
- handler(newVal, oldVal) {
- if (newVal !== this.prevOrderCount) {
- this.prevOrderCount = newVal;
- this.showPurchaseMessage();
- }
- },
- immediate: true
- }
- },
- methods: {closeAllWebSockets() {
- this.isManualClose = true;
-
- // 关闭所有连接
- Object.keys(this.socketInstances).forEach(liveId => {
- try {
- if (this.socketInstances[liveId] && this.socketInstances[liveId].instance) {
- this.socketInstances[liveId].instance.close({
- code: 1000,
- reason: '页面关闭'
- });
- console.log(`直播间 ${liveId} WebSocket 已关闭`);
- }
- } catch (e) {
- console.error(`关闭直播间 ${liveId} WebSocket 时出错:`, e);
- }
- });
-
- this.socketInstances = {};
- isSocketOpen = false;
- },// 新增:移除所有全局事件监听器
- removeAllEventListeners() {
- uni.$off('initSocket');
- uni.$off('sendMsg');
- uni.$off('closeWebSocket');
- uni.$off('refreshOrder');
- // 可以根据实际情况添加其他需要移除的事件
- },// 新增:清理所有定时器
- clearAllTimers() {
- if (this.intervalId) {
- clearInterval(this.intervalId);
- this.intervalId = null;
- }
-
- if (this.pingpangTimes) {
- clearInterval(this.pingpangTimes);
- this.pingpangTimes = null;
- }
-
- if (this.reconnectTimer) {
- clearTimeout(this.reconnectTimer);
- this.reconnectTimer = null;
- }
-
- if (this.scrollTimer) {
- clearTimeout(this.scrollTimer);
- this.scrollTimer = null;
- }
-
- if (this.searchTimer) {
- clearTimeout(this.searchTimer);
- this.searchTimer = null;
- }
-
- if (this.purchasePromptTimer) {
- clearTimeout(this.purchasePromptTimer);
- this.purchasePromptTimer = null;
- }
- },
- // 初始化当前直播间数据
- async initCurrentLiveData() {
- const currentLive = this.list[this.currentSwiperIndex];
- if (!currentLive) return;
- // 确保WebSocket连接已初始化
- if (!this.socketInstances[currentLive.liveId] || !this.socketInstances[currentLive.liveId].isOpen) {
- this.initSocket(currentLive);
- }
- try {
- // 并行加载,但允许单个失败不阻塞整体
- await Promise.allSettled([
- this.getLiveMsg(currentLive),
- this.getliveViewData(currentLive),
- this.getliving(currentLive),
- this.initSocket(currentLive)
- ]);
- currentLive.loaded = true;
- } catch (error) {
- console.error("初始化直播间数据失败:", error);
- } finally {
- currentLive.loading = false;
- }
- },
- // 初始化直播间列表
- async initLiveList(options) {
- try {
- await this.getList(); // 先加载直播间列表
- if (this.list.length === 0) {
- console.error("直播间列表为空,无法初始化");
- return;
- }
-
- // 设置初始直播间索引
- if (options.liveId) {
- const index = this.list.findIndex(item => item.liveId == options.liveId);
- this.currentSwiperIndex = index !== -1 ? index : 0;
- } else {
- this.currentSwiperIndex = 0;
- }
-
- // 获取当前直播间的liveItem
- const currentLive = this.list[this.currentSwiperIndex];
- if (currentLive) {
- this.liveId = currentLive.liveId;
- // 只初始化当前直播间的WebSocket
- await this.getLiveMsg(currentLive);
- await this.initCurrentLiveData();
- this.preloadNearbyLives();
- }
-
- } catch (error) {
- console.error("初始化失败:", error);
- }
- },
- // 预加载相邻直播间
- async preloadNearbyLives() {
- if (this.list.length === 0) {
- console.warn("list 为空,跳过预加载");
- return;
- }
- this.preloading = true;
- const preloadIndexes = [];
- const currentIndex = this.currentSwiperIndex;
- // 预加载前后各一个直播间
- if (currentIndex > 0) preloadIndexes.push(currentIndex - 1);
- if (currentIndex < this.list.length - 1) preloadIndexes.push(currentIndex + 1);
- // 异步预加载
- for (const index of preloadIndexes) {
- const liveItem = this.list[index];
- if (!liveItem) continue;
- if (!liveItem.loaded && !liveItem.loading) {
- try {
- await this.getLiveMsg(liveItem);
- await this.getliveViewData(liveItem);
- // 新增:预加载视频地址(关键)
- await this.getliving(liveItem);
- liveItem.loaded = true;
- } catch (error) {
- console.error(`预加载直播间 ${index} 失败:`, error);
- }
- }
- }
- this.preloading = false;
- },
- // Swiper切换事件
- async onSwiperChange(e) {
- const newIndex = e.detail.current;
- const oldIndex = this.currentSwiperIndex;
-
- // 1. 关闭旧直播间连接,暂停视频
- const oldLive = this.list[oldIndex];
- if (oldLive) {
- this.closeWebSocket(oldLive.liveId);
- this.pauseVideo(oldLive);
- }
-
- // 2. 更新当前直播间索引和 liveId
- this.currentSwiperIndex = newIndex;
- const newLive = this.list[newIndex];
- if (!newLive) return;
- this.liveId = newLive.liveId;
-
- // 3. 重置全局数据(避免旧数据影响新直播间)
- this.liveViewers = []; // 重置观众列表
- this.products = []; // 重置商品列表
- this.store = {}; // 重置店铺信息
- this.orderUser = {}; // 重置正在购买用户
- this.viewPageNum = 1; // 重置观众分页
- this.viewNoMoreData = false;
-
- // 4. 加载新直播间数据
- try {
- // 并行加载关键数据(视频、观众、商品等)
- await Promise.all([
- this.getliving(newLive), // 视频源
- this.getLiveMsg(newLive), // 聊天记录
- this.getliveViewData(newLive), // 点赞/关注数据
- this.getliveUser(), // 观众列表(当前直播间)
- this.getliveOrder() // 正在购买用户(当前直播间)
- ]);
- // 播放新视频
- this.$nextTick(() => this.playVideo(newLive));
- } catch (error) {
- console.error('切换直播间加载数据失败:', error);
- }
- }
- ,
- // 获取直播间列表
- async getList() {
- const data = {
- page: 1,
- page_size: 20
- };
- try {
- const res = await liveList(data);
- if (res.code === 200) {
- this.list = res.rows.map(item => ({
- ...item,
- talklist: [],
- loading: false,
- loaded: false,
- // 其他初始化字段...
- }));
- console.log("直播间列表加载成功,数量:", this.list.length); // 确认数量是否 > 0
- } else {
- uni.showToast({
- title: res.msg,
- icon: "none"
- });
- this.list = []; // 接口失败时清空列表,避免后续错误
- }
- } catch (error) {
- console.error("获取直播间列表失败:", error);
- this.list = []; // 异常时清空列表
- }
- },
- // 播放视频
- playVideo(liveItem) {
- if (!liveItem) {
- console.error('播放失败:直播间数据不存在');
- return;
- }
- // 检查视频源是否存在
- if (!liveItem.livingUrl && !liveItem.videoUrl) {
- console.error('播放失败:无视频源', liveItem);
- // 尝试重新加载视频源
- liveItem.loading = true;
- this.getliving(liveItem).then(() => {
- liveItem.loading = false;
- this.$nextTick(() => this.playVideo(liveItem)); // 重新尝试播放
- });
- return;
- }
- this.$nextTick(() => {
- try {
- const videoId = `myVideo_${liveItem.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- if (videoContext) {
- videoContext.play();
- } else {
- console.error('未找到视频组件', videoId);
- }
- } catch (error) {
- console.error("播放视频失败:", error);
- }
- });
- },
- // 预加载相邻直播间
- async preloadNearbyLives() {
- this.preloading = true;
- const currentIndex = this.currentSwiperIndex;
- const preloadIndexes = [];
- if (currentIndex > 0) preloadIndexes.push(currentIndex - 1);
- if (currentIndex < this.list.length - 1) preloadIndexes.push(currentIndex + 1);
- for (const index of preloadIndexes) {
- const liveItem = this.list[index];
- if (!liveItem || liveItem.loaded || liveItem.loading) continue;
- liveItem.loading = true; // 标记为加载中
- try {
- // 等待视频源加载完成
- await this.getliving(liveItem);
- // 确保其他必要数据加载
- await Promise.all([
- this.getLiveMsg(liveItem),
- this.getliveViewData(liveItem)
- ]);
- liveItem.loaded = true; // 所有数据加载完成才标记为“已加载”
- } catch (error) {
- console.error(`预加载直播间 ${index} 失败:`, error);
- liveItem.loaded = false; // 加载失败则不标记为已加载
- } finally {
- liveItem.loading = false;
- }
- }
- this.preloading = false;
- },
- // 初始化直播间数据
- initLiveData() {
- // 重置数据
- this.resetLiveData();
- // 初始化直播间特定数据
- this.getLiveMsg();
- this.getliveViewData();
- this.getliveOrder();
- this.getliving();
- this.initSocket();
- // 设置定时器
- this.intervalId = setInterval(() => {
- this.getliveViewData();
- }, 60 * 1000);
- },
- openViews() {
- // 计算scroll-view高度
- this.$nextTick(() => {
- const query = uni.createSelectorQuery().in(this);
- query.select('.view-box').boundingClientRect(data => {
- if (data) {
- // 减去标题和底部固定区域的高度
- this.scrollHeight = data.height - 80 - 120; // 80是标题高度,120是底部高度
- }
- }).exec();
- });
- },
- // 重置直播间数据
- resetLiveData() {
- // 保留不需要重置的数据(如用户信息等)
- const keepData = {
- userinfo: this.userinfo,
- list: this.list,
- currentSwiperIndex: this.currentSwiperIndex
- };
- // 重置其他直播间特定数据
- this.liveUserTotal = null;
- this.liveViewData = {};
- this.liveViewers = [];
- this.livingUrl = "";
- this.videoUrl = null;
- this.products = {};
- this.store = {};
- this.orderUser = {};
- this.talklist = [];
- this.livedata = {};
- this.isFollow = true;
- // 恢复需要保留的数据
- Object.assign(this, keepData);
- },
- // 获取直播间用户
- async getliveUser(isLoadMore = false) {
- // 强制使用当前 liveId,避免使用旧值
- const currentLiveId = this.liveId;
- if (!currentLiveId) return;
-
- if (this.viewLoading || this.viewNoMoreData) return;
- this.viewLoading = true;
-
- try {
- const res = await watchUserList(currentLiveId, this.viewPageSize, this.viewPageNum, false);
- if (res.code === 200) {
- // 若请求期间已切换直播间,忽略旧数据
- if (this.liveId !== currentLiveId) return;
-
- this.liveUserTotal = res.total;
- if (res.rows.length === 0) {
- this.viewNoMoreData = true;
- return;
- }
-
- this.liveViewers = isLoadMore
- ? [...this.liveViewers, ...res.rows]
- : res.rows; // 首次加载/切换直播间时重置数据
- this.viewPageNum++;
- }
- } catch (error) {
- console.error('获取观众列表失败:', error);
- } finally {
- this.viewLoading = false;
- }
- },
- // 滚动到底部触发
- handleScrollToLower() {
- // 清除上一次未执行的定时器,避免重复请求
- if (this.scrollTimer) {
- clearTimeout(this.scrollTimer);
- }
- // 延迟0.5秒(500毫秒)执行接口请求
- this.scrollTimer = setTimeout(() => {
- this.getliveUser(true); // 加载更多数据
- }, 1000); // 延迟时间:500毫秒
- },
- // gettalklist() {
- // if (!this.liveId) return;
- // const param = {
- // id: this.liveId
- // }
- // gettextlist(param).then(res => {
- // if (res.code == 200) {
- // this.talklist = res.data
- // // console.log(res.data);
- // this.$nextTick(() => {
- // this.scrollIntoView = `list_${this.talklist.length-1}`
- // })
- // }
- // })
- // },
- // 修改其他方法,增加liveItem参数
- async getLiveMsg(liveItem) {
- // 强化校验:确保 liveItem 存在且包含 liveId
- if (!liveItem || !liveItem.liveId) {
- console.error('getLiveMsg 错误:无效的 liveItem', {
- liveItem: liveItem,
- currentIndex: this.currentSwiperIndex,
- listLength: this.list.length
- });
- return; // 直接返回,不执行后续逻辑
- }
- try {
- const res = await liveMsg(liveItem.liveId, 30, 1);
- if (res.code == 200) {
- // 确保使用响应式更新
- this.$set(liveItem, 'talklist', [...res.rows]);
- this.$nextTick(() => {
- this.$set(liveItem, 'scrollIntoView', `list_${liveItem.talklist.length-1}`);
- });
- }
- } catch (error) {
- console.error("获取聊天记录失败:", error);
- }
- },
- // 暂停视频
- pauseVideo(liveItem) {
- if (!liveItem.livingUrl && !liveItem.videoUrl) return;
- try {
- const videoId = `myVideo_${liveItem.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- if (videoContext) {
- videoContext.pause();
- }
- } catch (error) {
- console.error("暂停视频失败:", error);
- }
- },
- // 点击红包
- onRed() {
- console.log("点了")
- if (!this.liveId) return;
- console.log("点了this.liveId", this.liveId)
- if (!this.redInfo?.redId) return;
- console.log("点了this.redInfo?.redId", this.redInfo.redId)
- console.log("点了this.userinfo.userId", this.userinfo.userId)
- let data = {
- liveId: this.liveId,
- userId: this.userinfo.userId,
- redId: this.redInfo.redId,
- }
- liveRed(data).then(res => {
- if (res.code == 200) {} else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- }
- },
- rej => {}
- );
- },
- handleSearchInput() {
- // 使用防抖优化性能,避免频繁请求
- clearTimeout(this.searchTimer);
- this.searchTimer = setTimeout(() => {
- this.queryCollect();
- }, 500); // 500毫秒延迟
- },
- // 显示购买提示信息
- showPurchaseMessage() {
- // 清除之前的定时器
- if (this.purchasePromptTimer) {
- clearTimeout(this.purchasePromptTimer);
- }
- // 显示提示
- this.showPurchasePrompt = true;
- // 2秒后自动隐藏
- this.purchasePromptTimer = setTimeout(() => {
- this.showPurchasePrompt = false;
- }, 2000);
- },
- truncateString(str, maxLength) {
- return str.length > maxLength ? str.slice(0, maxLength) + '...' : str;
- },
- goStore() {
- console.log("带过去storeId", this.storeId)
- uni.navigateTo({
- url: '/pages_shop/store?liveId=' + this.liveId + "&storeId=" + this.storeId
- })
- },
- // 去订单列表
- goOrderList() {
- uni.navigateTo({
- url: "/pages_shop/order"
- })
- },
- // 初始化HLS播放器
- initHlsPlayer() {
- if (Hls.isSupported() && this.livingUrl) {
- const video = document.getElementById('myVideo');
- if (video) {
- this.hlsPlayer = new Hls();
- this.hlsPlayer.loadSource(this.livingUrl);
- this.hlsPlayer.attachMedia(video);
- this.hlsPlayer.on(Hls.Events.MANIFEST_PARSED, () => {
- video.play();
- });
- }
- }
- },
- // 视频错误处理
- videoError(e) {
- console.error('视频播放错误:', e.detail.errMsg);
- // 尝试重新加载或切换到备用流
- if (this.livingUrl) {
- setTimeout(() => {
- this.videoContext.play();
- }, 2000);
- }
- },
- // 修改获取直播信息方法
- async getliving(liveItem) {
- if (!liveItem || !liveItem.liveId) return;
- console.log("获取直播信息:", liveItem.liveId);
- const param = {
- id: liveItem.liveId
- };
- try {
- const res = await getlive(param);
- if (res.code !== 200) {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- return;
- }
- // 强制更新视频源(覆盖旧值)
- if (res.data.liveType === 2) {
- // 回放视频
- this.$set(liveItem, 'videoUrl', res.data.videoUrl);
- this.$set(liveItem, 'livingUrl', ''); // 清空直播流
- } else if (res.data.liveType === 1) {
- // 直播流
- this.$set(liveItem, 'livingUrl', res.data.flvHlsUrl);
- this.$set(liveItem, 'videoUrl', ''); // 清空回放视频
- } else {
- // 未开播
- this.$set(liveItem, 'livingUrl', '');
- this.$set(liveItem, 'videoUrl', '');
- }
- // 更新其他直播信息
- this.$set(liveItem, 'showType', res.data.showType);
- this.$set(liveItem, 'storeId', res.storeId);
- this.$set(liveItem, 'autoplay', res.data.liveType !== 0); // 未开播不自动播放
- } catch (err) {
- console.error("获取直播信息失败:", err);
- uni.showToast({
- title: "获取直播信息失败",
- icon: 'none'
- });
- }
- }, // 设置视频播放
- setupVideoPlayback(liveItem, liveData) {
- if (!liveItem.livingUrl) return;
- // H5 平台:使用 HLS.js 处理 .m3u8 流
- // #ifdef H5
- if (liveItem.livingUrl.includes('.m3u8')) {
- this.initHlsPlayer(liveItem);
- return;
- }
- // #endif
- // 小程序/App 平台:直接使用 video 组件
- const videoId = `myVideo_${liveItem.liveId}`;
- const videoContext = uni.createVideoContext(videoId, this);
- if (liveData.liveType === 1) {
- // 回放:跳转到指定位置
- videoContext.seek(liveData.nowDuration || 0);
- } else {
- // 直播:直接播放
- videoContext.play();
- }
- },
- maskString(str, maskChar = '*') {
- // 新增:如果str是undefined或null,直接返回空字符串
- if (!str) return '';
- // 确保str是字符串(如果是数字等类型,先转为字符串)
- const strVal = String(str);
- return strVal.split('').map((char, index) => (index === 0 ? char : maskChar)).join('');
- },
- getPureDecimal(num, precision = 6) {
- const decimalPart = Math.abs(num).toFixed(precision).split('.')[1];
- return decimalPart?.replace(/0+$/, '') || ''; // 移除末尾多余的0
- },
- // 返回上一个页面并关闭WebSocket
- goBack() {
- // 暂停当前视频
- const currentLive = this.list[this.currentSwiperIndex];
- if (currentLive) {
- this.pauseVideo(currentLive);
- }
- // 关闭所有WebSocket连接
- this.closeWebSocket();
- // 导航返回
- const pages = getCurrentPages();
- if (pages.length > 1) {
- uni.navigateBack();
- } else {
- uni.switchTab({
- url: '/pages/list/index'
- });
- }
- },
- // 修改其他需要liveItem参数的方法
- async getliveViewData(liveItem) {
- if (!liveItem || !liveItem.liveId) return;
- try {
- const res = await getLiveViewData(liveItem.liveId);
- if (res.code == 200) {
- liveItem.liveViewData = res;
- }
- } catch (error) {
- console.error("获取直播间数据失败:", error);
- }
- },
- //正在购买
- async getliveOrder() {
- const currentLiveId = this.liveId;
- if (!currentLiveId) return;
-
- try {
- const res = await liveOrderUser(currentLiveId);
- if (res.code === 200) {
- // 绑定到当前 liveItem
- const currentLive = this.list[this.currentSwiperIndex];
- if (currentLive) {
- this.$set(currentLive, 'orderUser', res);
- this.orderUser = res; // 同步全局变量
- }
- }
- } catch (error) {
- console.error('获取正在购买用户失败:', error);
- }
- },
- // 获取直播间信息接口
- getLiveinformation() {
- if (!this.liveId) return;
- getLiveInfo(this.liveId).then(res => {
- if (res.code == 200) {
- console.log("获取直播间信息接口>>>>", res)
- this.livingUrl = res.livingUrl
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- }
- },
- rej => {}
- );
- },
- // 修改点赞方法
- async onLike(liveItem) {
- if (!liveItem || !liveItem.liveId) return;
- try {
- const res = await liveDataLike(liveItem.liveId);
- if (res.code === 200 && liveItem.liveViewData) {
- liveItem.liveViewData.like++; // 只更新当前直播间的点赞数
- }
- } catch (error) {
- console.error('点赞失败:', error);
- }
- },
- // 去购买,跳商品详情
- goShop(productId, goodsId) {
- uni.navigateTo({
- url: '/pages_shop/goods?productId=' + productId + '&liveId=' + this.liveId + '&goodsId=' +
- goodsId + '&storeId=' + this.storeId
- })
- },
- // 查询店铺
- <<<<<<< HEAD
- async queryCollect() {
- const currentLive = this.list[this.currentSwiperIndex];
- if (!currentLive || !currentLive.liveId) return;
-
- const { storeId } = currentLive;
- if (!storeId) return;
-
-
- try {
- const res = await store(currentLive.storeId, currentLive.inputInfo);
- if (res.code === 200) {
- // 数据绑定到当前 liveItem,避免全局污染
- this.$set(currentLive, 'products', res.data.goodsList);
- this.$set(currentLive, 'store', res.data);
- // 同步更新全局变量(供弹窗使用)
- this.products = res.data.goodsList;
- this.store = res.data;
- }
- } catch (error) {
- console.error('获取小黄车商品失败:', error);
- }
- =======
- queryCollect() {
- if (!this.storeId) return;
- if (!this.liveId) return;
- store(this.storeId, this.inputInfo,this.liveId).then(res => {
- if (res.code == 200) {
- console.log("查询店铺>>", res)
- this.products = res.data.goodsList
- this.store = res.data
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- }
- },
- rej => {}
- );
- >>>>>>> 57028795d3bcee2e15cce5538d4362a47313f66a
- },
- // 店铺收藏
- onStoreCollect() {
- if (!this.storeId) return;
- collectStore(this.storeId).then(res => {
- if (res.code == 200) {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- this.store.isFavorite = !this.store.isFavorite
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- }
- },
- rej => {}
- );
- },
- // 商品收藏
- onGoodsCollect(item) {
- if (!item || item.length === 0 || !item.goodsId) {
- return;
- }
- collectGoods(item.goodsId).then(res => {
- if (res.code == 200) {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- item.isFavorite = !item.isFavorite
- } else {
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- }
- },
- rej => {}
- );
- },
- // 关注
- async onFollow(liveItem) {
- if (!liveItem || !liveItem.liveId) return;
- try {
- const res = await follow(liveItem.liveId);
- liveItem.isFollow = !liveItem.isFollow;
- uni.showToast({
- title: res.msg,
- icon: 'none'
- });
- } catch (error) {
- console.error("关注操作失败:", error);
- }
- },
- // 时间戳
- initTime() {
- const now = new Date();
- this.timestamp = now.getTime(); // 例如:'2023-04-01 12:00:00'
- },
- // initWebSocket() {
- // const liveWS = new LiveWS('ws://your-server.com', 123, 456);
- // // 从 URL 中解析 timestamp
- // const urlParams = new URL(liveWS.url).searchParams;
- // this.timestamp = urlParams.get('timestamp');
- // // console.log('Timestamp:', timestamp);
- // },
- // 弹幕滚动
- lowerChat: function(e) {
- console.log(e)
- },
- scroll: function(e) {
- console.log(e)
- this.old.scrollTop = e.detail.scrollTop
- },
- loadmore() {
- // for (let i = 0; i < 30; i++) {
- // this.indexList.push({
- // url: this.shopList[uni.$u.random(0, this.shopList.length - 1)],
- // });
- // }
- },
- openShop() {
- },
- openViews() {
- this.$nextTick(() => {
- const query = uni.createSelectorQuery().in(this);
- query.select('.view-box').boundingClientRect(data => {
- if (data) {
- this.scrollHeight = data.height - 80 - 120;
- }
- }).exec();
- });
- },
- close() {
- this.showadd = !this.showadd
- },
- closes() {
- this.showziliao = !this.showziliao
- },
- closest() {
- this.showAnswer = !this.showAnswer
- },
- closestred() {
- this.showAnswerred = !this.showAnswerred
- },
- closeanswer() {
- this.answerbtn = !this.answerbtn
- },
- // 关闭小黄车
- closeShop() {
- this.shopping = !this.shopping
- },
- // 关闭红包
- closeRed() {
- this.showRed = !this.showRed
- },
- // longPress() {
- // this.timeout = setTimeout(() => {
- // this.isLongPress = true;
- // // 执行保存图片的操作
- // uni.saveImageToPhotosAlbum({
- // filePath: this.livedata.qwQrCode, // 图片的本地路径或网络路径
- // success: () => {
- // uni.showToast({
- // title: '保存成功'
- // });
- // },
- // fail: () => {
- // uni.showToast({
- // title: '',
- // icon: 'none'
- // });
- // }
- // });
- // }, 500); // 设置长按的阈值时间,这里是500毫秒
- // },
- // cancelLongPress() {
- // clearTimeout(this.timeout);
- // this.isLongPress = false;
- // },
- // 触摸结束
- handleTouchEnd() {
- this.isZoom = false; // 恢复原状
- },
- getEWechatSdk() {
- // 只在H5平台执行
- // #ifdef H5
- let eWechatSdk = '';
- if (/(Android)/i.test(navigator.userAgent)) {
- eWechatSdk = 'jWeixin';
- } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
- eWechatSdk = 'wx';
- } else {
- eWechatSdk = 'jWeixin';
- }
- uni.setStorageSync("wxSdk", eWechatSdk);
- // #endif
- },
- // 修改关闭WebSocket方法
- closeWebSocket(liveId = null) {
- this.isManualClose = true;
- // 清除所有定时器
- clearInterval(this.pingpangTimes);
- clearTimeout(this.reconnectTimer);
- // 关闭指定或所有WebSocket连接
- if (liveId) {
- // 关闭指定直播间的连接
- if (this.socketInstances[liveId]) {
- try {
- uni.closeSocket({
- instance: this.socketInstances[liveId]
- });
- console.log(`直播间 ${liveId} WebSocket 已安全关闭`);
- } catch (e) {
- console.error('关闭 WebSocket 时出错:', e);
- }
- delete this.socketInstances[liveId];
- }
- } else {
- // 关闭所有连接
- Object.keys(this.socketInstances).forEach(liveId => {
- try {
- uni.closeSocket({
- instance: this.socketInstances[liveId]
- });
- console.log(`直播间 ${liveId} WebSocket 已安全关闭`);
- } catch (e) {
- console.error('关闭 WebSocket 时出错:', e);
- }
- });
- this.socketInstances = {};
- }
- isSocketOpen = false;
- },
- reConnect() {
- var that = this;
- try {
- uni.closeSocket();
- } catch (e) {
- }
- setTimeout(function() {
- that.initSocket();
- }, 10000);
- },
- startHeartbeat() {
- clearInterval(this.pingpangTimes);
- this.pingpangTimes = setInterval(() => {
- if (!isSocketOpen) return;
- const pingData = {
- cmd: 'ping',
- timestamp: Date.now()
- };
- uni.sendSocketMessage({
- data: JSON.stringify(pingData),
- success: () => console.debug('心跳发送成功'),
- fail: (err) => {
- console.error('心跳发送失败:', err);
- this.scheduleReconnect();
- }
- });
- }, 30000); // 30秒心跳间隔
- },
- initSocket(liveItem) {
- // 如果没有指定直播间,不初始化
- if (!liveItem || !liveItem.liveId) return;
-
- const liveId = liveItem.liveId;
-
- // 检查是否是当前活跃的直播间
- if (this.currentSwiperIndex !== this.list.findIndex(item => item.liveId === liveId)) {
- console.log(`不初始化非当前直播间 ${liveId} 的WebSocket`);
- return;
- }
-
- // 关闭之前的连接(如果存在)
- if (this.socketInstances[liveId]) {
- this.closeWebSocket(liveId);
- }
-
- // 防止重复创建
- if (this.socketInstances[liveId]?.isOpen || this.reconnectCount >= this.maxReconnectAttempts) {
- return;
- }
-
- this.isManualClose = false;
-
- // 生成签名
- const signature = CryptoJS.HmacSHA256(
- `${liveId}${this.userinfo.userId}${this.userType}${this.timestamp}`,
- this.timestamp.toString()
- ).toString(CryptoJS.enc.Hex);
-
- // 初始化实例状态
- this.socketInstances[liveId] = {
- instance: null,
- isOpen: false
- };
-
- try {
- const socketTask = uni.connectSocket({
- url: `${wsUrl}?userId=${this.userinfo.userId}&liveId=${liveId}&userType=${this.userType}×tamp=${this.timestamp}&signature=${signature}`,
- success: () => {
- this.socketInstances[liveId].instance = socketTask;
- this.setupSocketListeners(liveId);
- },
- fail: (err) => {
- console.error('WebSocket 连接失败:', err);
- this.scheduleReconnect(liveId);
- }
- });
- } catch (e) {
- console.error('创建 WebSocket 异常:', e);
- this.scheduleReconnect(liveId);
- }
- },
- // 设置 WebSocket 监听器
- setupSocketListeners(liveId) {
- const socketItem = this.socketInstances[liveId];
- if (!socketItem || !socketItem.instance) return;
- const socketInstance = socketItem.instance;
- socketInstance.onOpen(() => {
- socketItem.isOpen = true; // 更新为当前实例的打开状态
- this.reconnectCount = 0;
- console.log(`直播间 ${liveId} WebSocket 连接成功`);
- this.startHeartbeat(liveId);
- });
- socketInstance.onClose(() => {
- socketItem.isOpen = false; // 更新为当前实例的关闭状态
- console.log(`直播间 ${liveId} WebSocket 连接关闭`);
- if (!this.isManualClose) {
- this.scheduleReconnect(liveId);
- }
- });
- socketInstance.onMessage((res) => {
- try {
- const redata = JSON.parse(res.data);
- <<<<<<< HEAD
- // 找到对应的直播间并更新数据
- const targetLive = this.list.find(item => item.liveId === liveId);
- if (targetLive) {
- targetLive.talklist.push(redata.data);
- this.$nextTick(() => {
- targetLive.scrollIntoView = `list_${targetLive.talklist.length - 1}`;
- });
- =======
-
- if(redata.data.cmd == 'sendMsg'){
- this.talklist.push(redata.data);
- this.$nextTick(() => {
- this.scrollIntoView = `list_${this.talklist.length - 1}`; // 最后一项的id
- });
- }
- else if (redata.data.cmd == 'deleteId') {
- uni.$emit('deleteId');
- }
- >>>>>>> 57028795d3bcee2e15cce5538d4362a47313f66a
- // 处理各种消息类型
- this.handleSocketMessage(redata.data, targetLive);
- }
- } catch (e) {
- console.error('解析消息失败:', e);
- }
- });
- },
- // 处理Socket消息
- handleSocketMessage(message, liveItem) {
- if (message.cmd == 'red') {
- // 领红包
- liveItem.redInfo = JSON.parse(message.data);
- } else if (message.cmd == 'sendRedPacketQuestion') {
- const list = JSON.parse(message.data);
- // 处理红包答题逻辑
- } else if (message.cmd == 'entry') {
- liveItem.showWelcomeMessage = true;
- setTimeout(() => {
- liveItem.showWelcomeMessage = false;
- }, 1000);
- } else if (redata.data.cmd == 'live_start') {
- // 直播开始
- } else if (redata.data.cmd == 'live_end') {
- // 直播结束
- } else if (redata.data.cmd == 'deleteId') {
- uni.$emit('deleteId');
- } else if (redata.data.cmd == 'sendRedPacketQuestion') {
- const list = JSON.parse(redata.data.data)
- liveItem.redanswerAll = [...liveItem.redanswerAll, ...list]
- if (liveItem.redanswerAll[1].randomAmount !== null) {
- liveItem.redanswertips = JSON.parse(liveItem.redanswerAll[0]
- .randomAmount)
- }
- }
- },
- scheduleReconnect() {
- if (this.isManualClose || this.reconnectCount >= this.maxReconnectAttempts) return;
- this.reconnectCount++;
- const delay = Math.min(3000 * this.reconnectCount, 30000);
- console.log(`将在 ${delay}ms 后重连 (尝试 ${this.reconnectCount}/${this.maxReconnectAttempts})`);
- this.reconnectTimer = setTimeout(() => {
- this.initSocket();
- }, delay);
- },
- sendMsg(liveItem) {
- if (!liveItem || !liveItem.liveId) return;
- const liveId = liveItem.liveId;
- const socketItem = this.socketInstances[liveId];
- // 检查连接是否存在且已打开
- if (!socketItem || !socketItem.instance || !socketItem.isOpen) {
- // 尝试重新连接
- this.initSocket(liveItem);
- // 显示提示并延迟重试
- uni.showToast({
- title: "连接未建立,正在重试...",
- icon: 'none'
- });
- // 3秒后重试发送
- setTimeout(() => {
- this.sendMsg(liveItem);
- }, 3000);
- return;
- }
- const data = {
- liveId: liveId,
- userId: this.userinfo.userId,
- userType: 0,
- cmd: "sendMsg",
- msg: liveItem.value,
- nickName: this.userinfo.nickName,
- avatar: this.userinfo.avatar
- };
- <<<<<<< HEAD
- if (!liveItem.value.trim()) {
- =======
- console.log(!this.value.trim())
- if (!this.value.trim()) { // 优化空消息判断
- >>>>>>> 57028795d3bcee2e15cce5538d4362a47313f66a
- uni.showToast({
- title: "不能发送空消息",
- icon: 'none'
- });
- return;
- }
- socketItem.instance.send({
- data: JSON.stringify(data),
- success: () => {
- console.log("发送成功");
- liveItem.value = ''; // 清空当前直播间的输入框
- },
- fail: (err) => {
- console.error("发送失败:", err);
- uni.showToast({
- title: "发送失败,请重试",
- icon: 'none'
- });
- }
- });
- },
- },
- };
- </script>
- <style scoped lang="scss">
- .swiper-wrapper {
- position: relative;
- width: 100%;
- height: 100vh;
- overflow: hidden;
- background-color: #000000;
- }
- .swiper-container {
- width: 100%;
- height: 100vh;
- }
- .container {
- width: 100%;
- height: 100%;
- position: relative;
- // 添加渐变过渡效果
- transition: opacity 0.3s ease;
- &.active {
- opacity: 1;
- }
- // 非活动项半透明显示
- // &:not(.active) {
- // opacity: 0.7;
- // }
- }
- .loading-tip {
- position: absolute;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- z-index: 10;
- .loading-text {
- color: #ffffff;
- font-size: 28rpx;
- margin-top: 20rpx;
- }
- }
- .loading-more,
- .no-more {
- display: flex;
- justify-content: center;
- align-items: center;
- padding: 20rpx 0;
- color: #999;
- font-size: 24rpx;
- }
- .loading-more {
- flex-direction: column;
- }
- .preload-indicator {
- position: absolute;
- top: 50%;
- right: 30rpx;
- transform: translateY(-50%);
- z-index: 100;
- background: rgba(0, 0, 0, 0.5);
- border-radius: 50%;
- padding: 16rpx;
- }
- /* button自带样式清除 */
- .student-orther-icon button::after {
- border: none !important;
- padding: 0 !important;
- margin: 0 !important;
- }
- .student-orther-icon button {
- background-color: transparent !important;
- padding: 0 !important;
- line-height: inherit !important;
- margin: 0 !important;
- width: auto !important;
- font-weight: 500 !important;
- border-radius: none !important;
- }
- .welcome-message {
- position: fixed;
- width: 100%;
- bottom: 460rpx;
- left: 50%;
- transform: translateX(-50%);
- color: white;
- padding: 10px 20px;
- border-radius: 20px;
- animation: fadeOut 1s ease 1s forwards;
- z-index: 1000;
- }
- @keyframes fadeOut {
- from {
- opacity: 1;
- }
- to {
- opacity: 0;
- }
- }
- // .container {
- // position: relative;
- // width: 100%;
- // height: 100vh;
- // overflow: hidden;
- // }
- // .talktext {
- // border-radius: 8rpx;
- // background-color: rgba(255, 255, 255, 0.1);
- // view {
- // width: 100%;
- // }
- // }
- .talk-list {
- border-radius: 30rpx;
- background-color: rgba(33, 33, 33, 0.5);
- padding: 10rpx 30rpx;
- }
- // .zoom-button-active {
- // transform: scale(1.5);
- // }
- // .background-image {
- // position: absolute;
- // top: 0;
- // left: -40rpx;
- // width: 110%;
- // height: 110%;
- // object-fit: cover;
- // filter: blur(20px);
- // z-index: 0;
- // }
- // .background-images {
- // position: absolute;
- // top: 0;
- // left: -40rpx;
- // width: 110%;
- // height: 110%;
- // object-fit: cover;
- // filter: blur(20px);
- // z-index: 6;
- // }
- // .blackbg {
- // position: absolute;
- // top: 0;
- // left: 0;
- // width: 100%;
- // height: 100%;
- // background: rgba(0, 0, 0, 0.7);
- // object-fit: cover;
- // filter: blur(10px);
- // z-index: 1;
- // }
- .content {
- position: relative;
- z-index: 2;
- height: 100%;
- width: 100%;
- top: 0;
- left: 0;
- display: flex;
- flex-direction: column;
- justify-content: space-between;
- .content-top {
- width: 100%;
- margin-top: 150rpx;
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 0 24rpx;
- box-sizing: border-box;
- .sum {
- width: 80rpx;
- height: 52rpx;
- background: rgba(0, 0, 0, 0.5);
- border-radius: 26rpx 26rpx 26rpx 26rpx;
- font-size: 24rpx;
- color: #FFFFFF;
- text-align: center;
- line-height: 52rpx;
- }
- }
- .follow-btn {
- padding: 8rpx 16rpx;
- background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
- border-radius: 26rpx;
- font-weight: 500;
- font-size: 26rpx;
- color: #FFFFFF;
- }
- }
- .videolist {
- position: relative;
- }
- .video {
- height: 100vh;
- /* 占屏幕高度的80% */
- width: 100%;
- background-color: rgba(57, 57, 57, 0.4);
- }
- .videotop {
- width: 100%;
- height: 100%;
- }
- .video_row {
- width: 100%;
- max-height: 500rpx;
- overflow: hidden;
- margin-top: 360rpx;
- }
- .popup-video {
- position: absolute;
- top: 30%;
- height: 500rpx;
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- width: 100%;
- color: #fff;
- z-index: 9;
- .more {
- background-color: #3280fe;
- border-radius: 80rpx;
- width: 280rpx;
- text-align: center;
- height: 60rpx;
- line-height: 60rpx;
- }
- }
- .icon-bg {
- background-color: rgba(157, 157, 157, 0.8);
- border-radius: 50%;
- width: 72rpx;
- height: 72rpx;
- display: flex;
- justify-content: center;
- align-items: center;
- transition: transform 0.2s ease;
- }
- .list {
- width: 80%;
- margin-bottom: 20rpx;
- animation: xxxawdawd .2s;
- }
- @keyframes xxxawdawd {
- from {
- margin-top: 0rpx;
- opacity: 0;
- }
- to {
- margin-top: 20rpx;
- opacity: 1;
- }
- }
- .shop-prompt {
- position: absolute;
- bottom: 600rpx;
- left: 24rpx;
- padding: 6rpx 20rpx;
- background: rgba(230, 154, 34, 0.7);
- border-radius: 24rpx;
- z-index: 9;
- font-weight: 500;
- font-size: 26rpx;
- color: #FFFFFF;
- transition: opacity 0.3s ease;
- }
- .siderow-group {
- position: absolute;
- top: 56%;
- right: 50rpx;
- z-index: 9;
- display: flex;
- flex-direction: column;
- align-items: center;
- .side-item {
- font-weight: 500;
- font-size: 24rpx;
- color: #FFFFFF;
- margin-bottom: 32rpx;
- text-align: center;
- button {
- background-color: transparent;
- margin: 0;
- line-height: 1;
- padding: 0;
- }
- image {
- width: 72rpx;
- height: 72rpx;
- }
- }
- }
- .side-group {
- position: absolute;
- // top: 30%;
- top: 56%;
- right: 50rpx;
- z-index: 9;
- display: flex;
- flex-direction: column;
- align-items: center;
- .side-item {
- font-weight: 500;
- font-size: 24rpx;
- color: #FFFFFF;
- margin-bottom: 32rpx;
- text-align: center;
- button {
- background-color: transparent;
- margin: 0;
- line-height: 1;
- padding: 0;
- }
- image {
- width: 72rpx;
- height: 72rpx;
- }
- }
- }
- .red-box {
- .button {
- margin: 0 auto;
- width: 80%;
- line-height: 88rpx;
- height: 88rpx;
- background: linear-gradient(90deg, #FF5701 0%, #FFB501 100%);
- box-shadow: 0rpx 8rpx 8rpx 0rpx rgba(238, 124, 80, 0.2);
- border-radius: 44rpx 44rpx 44rpx 44rpx;
- font-weight: 600;
- font-size: 32rpx;
- color: #FFFFFF;
- text-align: center;
- }
- }
- .view-box {
- position: relative;
- height: 40vh;
- /* 设置弹出层高度为视窗高度的70% */
- padding: 40rpx 0rpx 120rpx;
- box-sizing: border-box;
- display: flex;
- flex-direction: column;
- .scroll-content {
- flex: 1;
- overflow-y: auto;
- padding: 0 40rpx;
- }
- .bottom {
- padding: 20rpx 40rpx;
- position: absolute;
- bottom: 0;
- width: 100%;
- box-shadow: 0rpx -4rpx 10rpx 0rpx rgba(195, 195, 195, 0.3);
- background: #fff;
- }
- }
- .shoppop {
- padding: 22rpx 16rpx;
- .shoppop-top {
- display: flex;
- justify-content: space-between;
- align-items: center;
- padding: 0 16rpx 22rpx;
- .search-input {
- width: 414rpx;
- height: 76rpx;
- background: #FFFFFF;
- border-radius: 36rpx;
- margin-left: 20rpx;
- padding: 0 32rpx;
- box-sizing: border-box;
- font-size: 24rpx;
- margin-right: 24rpx;
- }
- .search-top {
- font-size: 18rpx;
- color: #222222;
- }
- }
- .shop-list {
- overflow: hidden;
- .list-item {
- display: flex;
- align-items: center;
- padding: 20rpx 16rpx;
- background: #FFFFFF;
- border-radius: 16rpx;
- margin-bottom: 16rpx;
- .goods-img {
- width: 200rpx;
- height: 200rpx;
- border-radius: 16rpx;
- overflow: hidden;
- position: relative;
- margin-right: 24rpx;
- image {
- width: 100%;
- height: 100%;
- }
- .goods-label {
- position: absolute;
- top: 0;
- width: 64rpx;
- height: 40rpx;
- background: rgba(0, 0, 0, 0.5);
- border-radius: 16rpx 0rpx 16rpx 0rpx;
- text-align: center;
- font-weight: 500;
- font-size: 28rpx;
- color: #FFFFFF;
- }
- }
- .goods-right {
- flex: 1;
- .goods-title {
- font-weight: 500;
- font-size: 28rpx;
- color: #000000;
- }
- .goods-details {
- font-size: 24rpx;
- color: #999999;
- margin: 10rpx 0 20rpx;
- }
- .goods-people {
- font-size: 22rpx;
- color: #E69A22;
- height: 56rpx;
- }
- .goods-shop {
- display: flex;
- justify-content: space-between;
- .nummber {
- color: #FF5C03;
- font-size: 22rpx;
- font-weight: 500;
- }
- .btn-group {
- text-align: center;
- line-height: 56rpx;
- .collect-btn {
- width: 72rpx;
- background: #F5F7FA;
- border-radius: 8rpx 0rpx 0rpx 8rpx;
- }
- .shop-btn {
- width: 152rpx;
- background: linear-gradient(270deg, #FF5C03 0%, #FFAC64 100%);
- border-radius: 0rpx 8rpx 8rpx 0rpx;
- font-weight: 500;
- font-size: 26rpx;
- color: #FFFFFF;
- }
- }
- }
- }
- }
- }
- }
- :deep(.u-list-item) {
- width: 100%;
- display: flex;
- align-items: center;
- }
- :deep(.u-safe-area-inset-bottom) {
- padding-bottom: 0
- }
- </style>
|