<template>
	<view class="swiper-wrapper" :class="liveItem.showType == 1 ? 'horizontal' : ''">
		<view class="container">
			<!-- 预告课程状态 -->
			<view :class="liveItem.previewUrl?'trailer-box':'trailer-box2'" v-if="liveItem.status == 1">
				<view class="video-container2"
					:style="{ paddingBottom:liveItem.previewUrl?videoRatio + '%':'' ,height:auto,width:'100%'}">
					<video v-if="liveItem.previewUrl" :id="`myVideo_${liveId}`" class="trailer-video"
						:src="liveItem.previewUrl" :autoplay="true" :loop="false"
						:object-fit="isHeight?'contain':'fill'" :custom-cache="false" :enable-progress-gesture="false"
						vslide-gesture-in-fullscreen="false" :show-center-play-btn="false" :http-cache="false"
						@error="videoError" @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause"
						@play="onVideoPlay" :disable-progress="true" :enable-play-gesture="true"
						@waiting="onVideoWaiting" preload="auto" type="application/x-mpegURL" :controls="false"></video>
				</view>
				<image v-if="liveItem.status == 1 && !liveItem.previewUrl" class="trailer-placeholder"
					src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/readyStart.png">
				</image>
				<view class="countdown-container" v-if="liveItem.status == 1 && liveCountdown">
					<view class="live-name" v-if="liveItem.previewUrl">{{ liveItem.liveName }}</view>
					<view class="countdown-display">
						<text class="countdown-label">距离开课还有</text>
						<view class="countdown-unit">
							{{ liveCountdown.hours || '00' }}
						</view>
						<view class="countdown-separator">:</view>
						<view class="countdown-unit">
							{{ liveCountdown.minutes || '00' }}
						</view>
						<view class="countdown-separator">:</view>
						<view class="countdown-unit">
							{{ liveCountdown.seconds || '00' }}
						</view>
					</view>
				</view>
			</view>
			<!-- 主要内容区域 -->
			<view class="content"
				:class="{ 'horizontal-content': isFocus==1, 'trailer-content': liveItem.status==1,  'fullscreen-mode': isFullscreen   }">
				<!-- 顶部观看人数栏 P1 -->
				<LiveViewerBar
					v-if="modules.p1 && !isFullscreen"
					:live-item="liveItem"
					:is-fullscreen="isFullscreen"
					:filtered-viewers="filteredViewers"
					:formatted-watch-count="formattedWatchCount"
				/>

				<!-- 视频区域 P0 -->
				<LiveVideoPlayer
					ref="videoPlayer"
					:live-id="liveId"
					:live-item="liveItem"
					:is-fullscreen="isFullscreen"
					:is-height="isHeight"
					:video-ratio="videoRatio"
					:scale="scale"
					:generating="false"
					:is-playback="isPlayback"
					:playback-time="playbackTime"
					@play="onVideoPlay"
					@pause="onVideoPause"
					@timeupdate="onVideoTimeUpdate"
					@error="videoError"
					@fullscreen-change="onVideoFullscreenChange"
					@live-state-change="onVideoLiveStateChange"
					@loadedmetadata="onVideoMetaLoaded"
				/>
				<!-- v-if="!hasReachedTarget" -->
				<!-- &&liveItem.completionPointsEnabled -->

				<LiveSideActions
					:live-item="liveItem"
					:is-focus="isFocus"
					:is-fullscreen="isFullscreen"
					:formatted-like-count="formattedLikeCount"
					@like="onLike"
				/>

				<!-- 课程答题入口（socket liveQuizStart 显示，liveQuizClose 隐藏） -->
				<view class="slide-group live-quiz-entry-wrap" v-if="!isFocus && !isFullscreen && liveQuizShowEntry">
					<view class="action-button-group end">
						<view :class="[liveItem.showType === 1 ? 'horizontal' : 'vertical','ml20']" @tap.stop="openLiveQuizSheet">
							<view class="live-quiz-entry-btn">参与答题</view>
						</view>
					</view>
				</view>

				<!-- 底部聊天区域 P0 -->
				<LiveChatPanel
					ref="chat"
					v-show="p0Ready"
					:live-id="liveId"
					:live-item="liveItem"
					:user-info="userInfo"
					:myself-flag="myselfFlag"
					:is-fullscreen="isFullscreen"
					:is-end="isEnd"
					:is-playback="isPlayback"
					:is-i-o-s="isIOS"
					:notice="notice"
					:is-show-notice="isShowNotice"
					:socket-connected="socketConnected"
					@chat-send="handleChatSend"
					@focus-change="onChatFocusChange"
					@keyboard-show="onChatKeyboardShow"
					@keyboard-hide="onChatKeyboardHide"
					@open-cart="openCart"
					@open-more="onMoreClick"
				/>
			</view>

			<LiveShopPanel
				v-if="p0Ready"
				ref="shop"
				:live-id="liveId"
				:store-id="storeId"
				:live-item="liveItem"
				:goods-card="goodsCard"
				:is-show-goods="isShowGoods && !isFullscreen"
				:order-user="orderUser"
				:show-purchase-prompt="showPurchasePrompt"
				@update:isShowGoods="isShowGoods = $event"
				@buy="onShopBuy"
				@collect="onGoodsCollect"
				@open-more="onShopOpenMore"
				@open-orders="navgetTo('/pages_user/user/storeOrder?status=')"
			/>

			<LiveActivityHost
				v-if="modules.p2Activity"
				:userlogo="userlogo"
				:is-show-lottery-pop="isShowLotteryPop"
				:live-quiz-sheet-visible="liveQuizSheetVisible"
				:should-show-integral-popup="shouldShowIntegralPopup"
				:is-show-red="isShowRed"
				:is-show-lottery="isShowLottery"
				:is-show-red-card="isShowRedCard"
				:is-show-pop-msg="isShowPopMsg"
				:is-show-prize="isShowPrize"
				:have-prize="havePrize"
				:winning="winning"
				:is-more="isMore"
				:is-show-coupon="isShowCoupon"
				:countdown="countdown"
				:lottery-products="lotteryProducts"
				:live-quiz="liveQuiz"
				:live-quiz-option-list="liveQuizOptionList"
				:live-quiz-can-submit="liveQuizCanSubmit"
				:has-quiz-selection="hasQuizSelection"
				:is-quiz-option-selected="isQuizOptionSelected"
				:integral-status="integral.status"
				:integral-msg="integral.msg"
				:red-card="redCard"
				:pop-msg="popMsg"
				:is-current-user-won="isCurrentUserWon"
				:prize-info="prizeInfo"
				:prize-all="prizeAll"
				:coupon-info="couponInfo"
				@confirm-nickname="confimrname"
				@nickname-input="onNickNameInput"
				@update:userlogo="userlogo = $event"
				@update:isShowLotteryPop="isShowLotteryPop = $event"
				@lottery-claim="onClaim"
				@quiz-close="closeLiveQuizSheet"
				@quiz-select="selectQuizOption"
				@quiz-submit="submitLiveQuizAnswer"
				@integral-close="closeIntegralPopup"
				@update:isShowRed="isShowRed = $event"
				@red-claim="onRed"
				@update:isShowLottery="isShowLottery = $event"
				@lottery-confirm="onLottery"
				@update:isShowRedCard="isShowRedCard = $event"
				@update:isShowPopMsg="isShowPopMsg = $event"
				@prize-confirm="confirm"
				@prize-fill-address="onPrizeFillAddress"
				@winning-close="closeWin"
				@winning-fill-address="onWinningFillAddress"
				@more-close="closeMore"
				@more-integral="onMoreIntegral"
				@more-exchange="onMoreExchange"
				@more-winning-record="onMoreWinningRecord"
				@update:isShowCoupon="isShowCoupon = $event"
				@coupon-claim="onCoupon"
			/>

			<view v-if="liveItem.status == 1" class="ash_bg"></view>
			<view class="custom-toast" v-if="showToast">
				<view class="toast-content">
					完课积分已到账
				</view>
			</view>
		</view>
		<CustomToast ref="customToast">
		</CustomToast>
	</view>
</template>

<script>
	import {
		CustomToast
	} from '@/components/custom-toast.vue';
	import LiveVideoPlayer from '@/pages_course/living/components/LiveVideoPlayer.vue';
	import LiveShopPanel from '@/pages_course/living/components/LiveShopPanel.vue';
	import LiveActivityHost from '@/pages_course/living/components/LiveActivityHost.vue';
	import LiveChatPanel from '@/pages_course/living/components/LiveChatPanel.vue';
	import LiveViewerBar from '@/pages_course/living/components/LiveViewerBar.vue';
	import LiveSideActions from '@/pages_course/living/components/LiveSideActions.vue';
	import { fetchLiveOrderUser } from '@/pages_course/living/services/liveShopService.js';
	import { fetchLiveUserInfo } from '@/pages_course/living/services/liveUserService.js';
	import {
		fetchLiveRoom,
		fetchLiveViewData,
		fetchCurrentActivities,
		fetchRemainingTime,
		fetchCompletionRecords,
		clearLiveRoomRequestCache
	} from '@/pages_course/living/services/liveRoomService.js';
	import { createLiveSocket } from '@/pages_course/living/services/liveSocket.js';
	import { parseWsEnvelope, parseJsonField, parseNumericField, isSuccessEnvelope } from '@/pages_course/living/services/liveSocketProtocol.js';
	import {
		myLottery,
		coupon,
		liveLottery,
		claim,
		liveRed,
		liveDataLike,
		collectGoods,
		subNotifyLive,
		internetTraffic,
		liveInternetTraffic,
		loginByMp,
		getIsAddKf,
		liveWatchUser,
		submitLiveQuiz,
		completionReceive,
		completionUnreceived,
		updateWatchDuration,
		receivePoints,
		integrallogs
	} from '@/api/cacheLiving.js';
	import {
		editUser
	} from '@/api/user'
	import {
		mapGetters
	} from 'vuex';
	import {
		TOKEN_KEYAuto,
		generateRandomString
	} from '@/utils/courseTool.js'
	import dayjs from 'dayjs';
	export default {
		name: 'LivingNewPage',
		components: {
			CustomToast,
			LiveVideoPlayer,
			LiveShopPanel,
			LiveActivityHost,
			LiveChatPanel,
			LiveViewerBar,
			LiveSideActions
		},
		data() {
			return {
				showToast: false, //完课弹窗
				videoDuration: 0, //要看的时长
				pointsRemainingTime: 0,
				hasReceived: false,
				receiveStatus: false,
				completionRate: 0,
				playbackTime: '00:00:00', //用户观看回放时间
				// 观看时长统计变量
				watchStartTime: 0, // 开始观看时间戳
				accumulatedWatchDuration: 0, // 累计观看时长（秒）
				isPageVisible: true, // 页面是否可见
				lastPauseTime: 0,
				qwCode: false,
				hasReachedTarget: false,
				receiveList: [],
				recordId: null, //完课积分记录ID
				showPoints: false,
				remainingTime: 0, // 剩余时间（秒）
				watchProgressKey: '', // 存储键
				isCountdownActive: false, // 倒计时是否激活
				countdownTimer: null, // 倒计时定时器
				lastUpdateTime: 0, // 上次更新时间

				totalWatchTime: 0, // 累计观看时间（秒）
				watchTimeStorageKey: '', // 存储键
				lastSaveTime: 0, // 上次保存时间
				watchTimeTimer: null, // 观看时间定时器
				hasSubscribed: false, // 已成功订阅（永久禁用）
				urlOption: {},

				menuButtonInfo: {}, // 胶囊按钮布局信息
				isHeight: false,
				isFullscreen: false,
				isVideoRotated: false,
				showNonVideoElementsFlag: true,
				videoRatio: 56.25, // 默认16:9比例
				scale: 1,
				isMuted: false,
				showCustomControls: true,
				videoContext: null,
				isNow: false,
				fakeAvatar: Array.from({
						length: 11
					}, (_, i) =>
					`https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/avatar${i + 1}.jpg`),
				virtualHuman: null,
				userlogo: false,
				hasPlayback: false,
				isPlayback: false, //是否是回放
				isIOS: false,
				myselfFlag: false, // yhq
				isEnd: false,
				popMsg: null,
				// barrageList: ['支持你!', '谢谢你!', '平台真好!', '666', '欢迎回家!'], //一键弹幕列表
				uuId: '',
				totalTraffic: 0, // 总流量（字节）
				bitrate: 800, // 录播默认码率 0.16Mbps
				bitrateLive: 1600, // 课程默认码率 0.16Mbps
				videoLoaded: false, // 视频是否加载成功
				isManualPause: false, // 是否手动暂停
				waitingTimer: null, // 视频等待定时器
				waitingStartTime: 0, // 视频等待开始时间
				lastVideoUpdateTime: 0, // 视频最后更新时间
				trafficStartTime: 0, // 流量计算开始时间
				liveBeginWatchTime: 0, //开始观看的时间点 不包含预告
				//定时器
				trafficTimer: null,
				liveViewDataTimer: null,
				scrollTimer: null,
				lastScrollTime: 0,
				scrollDebounceDelay: 200,
				searchTimer: null,
				purchasePromptTimer: null,
				welcomeTimer: null,
				redTimer: null,
				liveStartTimer: null,
				lotteryTimer: null,
				memoryMonitorTimer: null,
				networkStatusTimer: null,
				lastPerformanceCheck: 0,
				stayTime: 0,
				startTime: 0,
				isOnload: false,
				// 请求状态标记，防止重复请求
				isLoadingLiveInfo: false, // 是否正在加载课程间信息
				isLoadingVideo: false, // 是否正在加载视频资源
				hasCheckedLogin: false, // 是否已检查登录状态
				initPromise: null, // 登录后初始化 Promise，防止重复
				p1DataLoaded: false,
				secondaryDataLoaded: false,
				chatHistoryLoaded: false,
				isFirstShow: true,
				isFetchingUserInfo: false,
				lastTrafficSubmitAt: 0,

				liveViewersData: [],
				liveUserCalled: false,
				shownEntryUsers: new Set(),
				networkType: 'unknown',
				isNetworkAvailable: true,

				templateId: '4OFTqa6oQUrI3oPGvoespPTM6uz5SjmQE1L-JEPxF-g', //岚财良品
				//templateId: 'ELHbRqBdzSV7ttXTWw7RgnddnIqkj2-ld8dMU-gJmyU', //乐享优品
				isAgreement: false,

				qrFrom: null,
				scene: '',

				liveCountdown: {},
				countdown: {},
				liveViewData: {},

				isKeyboardShow: false,
				videoCurrentTime: 0,
				videoProgressKey: '',
				inAndOut: {},
				winning: false,
				isShowPrize: false,
				isShowCoupon: false,
				prizeInfo: [],
				havePrize: uni.getStorageSync('havePrize') || false,
				countDownKey: 0,
				lotteryProducts: [],
				lotteryList: [],
				isShowLotteryPop: false,
				liveItem: {},
				isMore: false,

				prizeAll: [],
				isShowLottery: false,
				isShowRedCard: false,
				isShowPopMsg: false,
				isShowNotice: false,
				notice: [],
				redCard: null, //点击红包出现弹窗
				integral: {},
				lotteryInfo: {},
				goodsCard: {},
				couponInfo: {},
				redInfo: {},
				storeId: null,
				isFocus: false,
				systemInfo: null,
				getlivingTimer: null,
				showWelcomeMessage: false,
				isShowGoods: false,
				goodsCardHiddenByKeyboard: false,
				isShowRed: false,
				lastClickTime: 0,
				videoRetryCounts: Object.create(null),
				clickDelay: 300,
				liveUserTotal: 0,
				showPurchasePrompt: false,
				prevOrderCount: 0,
				videoUrl: null,
				showType: 1, //横屏1 竖屏2
					liveViewers: [], //观众
				livingUrl: '',
						orderUser: {}, //正在购买
				userType: 0,
						liveId: null,
				userInfo: {}, //用户信息
				userData: {},
				diffTotalTime: '',
				address: '',
					user: {},
				watchDuration: 0,
				liveFlag: -1, //0 回放   1 课程
				isPreview: true, //是否预告
				diffLiveStartTime: 0, //距离课程开始时间差值
				diffLiveEndTime: 0, //距离课程结束时间差值
				completionTime: 0, //领取积分所需时间
				hasLiveEnd: false, //是否经历过首播结束

				// 课程答题（WebSocket: liveQuizStart / liveQuizClose）
				liveQuizShowEntry: false,
				liveQuizSheetVisible: false,
				liveQuizCanSubmit: true,
				liveQuiz: {
					title: '',
					type: 1,
					options: [],
					relId: null,
					questionBankId: null
				},
				liveQuizSelectedKey: null,
				liveQuizSelectedKeys: [],
				isPageLoadFirst: true, //是否首次加载课程间
				pointsRetryTimer: null, // 积分领取重试定时器
				completionPointsEnabled: false, //是否开启积分
				p0Ready: false,
				liveSocket: null,
				socketConnected: false,
				wsBaseUrl: '',
				modules: {
					p1: false,
					p2Activity: false
				}
			};
		},
		async onLoad(options) {

			this.getMenuButtonInfo(); // 初始化获取胶囊信息
			// 解析参数
			if (options.liveId) {
				this.liveId = options.liveId;
			}
			if (options.qwUserId) {
				this.urlOption.companyId = options.companyId
				this.urlOption.companyUserId = options.companyUserId
				this.urlOption.corpId = options.corpId
				this.urlOption.liveId = options.liveId
				this.urlOption.qwUserId = options.qwUserId
				this.urlOption.qwExternalId = options.externalId
				this.urlOption.chatId = options.chatId
			}
			// 扫码传来的参数
			if (options.scene) {
				this.scene = options.scene;
				const decodedScene = decodeURIComponent(this.scene);
				const params = {};
				decodedScene.split('&').forEach((item) => {
					const [key, value] = item.split('=');
					params[key] = value;
					this.liveId = params.a;
				});
				if (params.b && params.c) {
					console.log("扫码参数", params)
					this.qrFrom = `&companyId=${params.b}&companyUserId=${params.c}`;
				}
			}
			if (options.companyId && options.companyUserId) {
				this.qrFrom = `&companyId=${options.companyId}&companyUserId=${options.companyUserId}`;
			}
			this.userinfo = uni.getStorageSync('userinfo');
			this.hasSubscribed = uni.getStorageSync('subscribe_status_' + this.liveId) || false;
			console.log('全部参数', options);
			// 优先判断登录状态，然后加载数据
			// this.userData = uni.getStorageSync('userData');
			try {
				const isLogin = await this.utils.checkLiveToken();
				this.hasCheckedLogin = true;
				if (isLogin) {
					// 登录后：优先加载课程间信息，然后加载视频资源
					await this.haveLogin();
				} else {
					// 未登录：先登录，登录成功后再加载数据
					this.goLogin();
				}

			} catch (error) {
				console.error('初始化失败:', error);
				this.hasCheckedLogin = true;
			}

			// 初始化网络状态监听
			this.initNetworkStatusListener();
		},
		async onPullDownRefresh() {
			if (this.liveId) {
				clearLiveRoomRequestCache(this.liveId);
				this.isLoadingLiveInfo = false;
				this.chatHistoryLoaded = false;
				this.secondaryDataLoaded = false;
				this.p1DataLoaded = false;
				await this.getliving(this.liveId, { refresh: true });
				await this.loadChatHistory(true);
				this.modules.p1 = true;
				this.loadP1Data(true);
			}
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		mounted() {
			// 获取 video 上下文
			// 监听视频全屏事件
			setTimeout(() => {
				this.videoContext = uni.createVideoContext(`myVideo_${this.liveId}`, this);
				// 添加全屏状态变化监听（更可靠的方式）
				if (this.videoContext) {
					// 使用 uni.onUserCaptureScreen 作为备选方案
					uni.onUserCaptureScreen(() => {
						console.log('用户截屏，可能是全屏状态');
					});
				}
			}, 1000);
		},
		async onShow() {
			setTimeout(() => {
				this.startCountdown();
			}, 500);
			const systemInfo = uni.getSystemInfoSync();
			this.isIOS = systemInfo.platform === 'ios';
			console.log(systemInfo, '当前系统型号')
			if (!this.hasCheckedLogin) {
				try {
					const isLogin = await this.utils.checkLiveToken();
					this.hasCheckedLogin = true;
					if (isLogin) {
						await this.haveLogin();
						if (this.urlOption.qwUserId) {
							this.getIsAddKf()
						}
					} else {
						this.goLogin();
					}
				} catch (error) {
					console.error('初始化失败:', error);
					this.hasCheckedLogin = true;
				}
			}
			this.uuId = generateRandomString(16);
			const isLiveLogin = uni.getStorageSync('isLiveLogin');
			this.share = uni.getStorageSync('share');
			this.scene = uni.getStorageSync('scene');
			if (this.share && this.share.length > 0) {
				this.liveId = this.share.liveId;
				this.qrFrom = `&companyId=${this.share.companyId}&companyUserId=${this.share.companyUserId}`;
				uni.removeStorageSync('share');
			}
			if (this.scene) {
				const decodedScene = decodeURIComponent(this.scene);
				const params = {};
				decodedScene.split('&').forEach((item) => {
					const [key, value] = item.split('=');
					params[key] = value;
					this.liveId = params.a;
				});
				if (params.b && params.c) {
					this.qrFrom = `&companyId=${params.b}&companyUserId=${params.c}`;
				}
				uni.removeStorageSync('scene');
			}

			// 恢复播放和连接（首次 onShow 跳过，避免与 onLoad 重复拉取）
			if (!this.isFirstShow) {
				await this.resumePageActivity();
			}
			this.isFirstShow = false;

			// 恢复观看时长统计（如果之前已经开始统计）
			if (this.watchStartTime > 0 || this.accumulatedWatchDuration > 0) {
				this.resumeWatchDurationTracking();
			}

			// this.userinfo = JSON.parse(uni.getStorageSync('userInfo'));
			this.userinfo = uni.getStorageSync('userinfo');
			this.isAgreement = uni.getStorageSync('isAgreement');

			this.$nextTick(() => {
				this.setVideoProgress();
			});
			if (this.lookTimer) {
				clearInterval(this.lookTimer);
				this.lookTimer = null;
				this.stayTime = 0;
				this.startTime = 0;
			}

			// 启动内存监控，定期清理
			this.startMemoryMonitor();
			// 不在 onShow 重置流量统计，避免重复上报 getLiveInternetTraffic
			if (!this.lookTimer) {
				this.startTimer();
			}
			this.$nextTick(() => {
				console.log(444, this.userInfo);
				if (!this.userInfo || !this.userInfo.nickname) {
					console.log('用户信息不完整，显示授权弹窗');
					this.userlogo = true;
					return;
				}

				// // 重新计算 isNow
				// const isNowCalculated = dayjs(this.userInfo.updateTime).isSame(dayjs(), 'day');
				// console.log('重新计算 isNow:', isNowCalculated);
				// if (!isNowCalculated) {
				//    console.log('不是今天更新过，显示授权弹窗');
				// 	  this.userlogo = true;
				// }

				setTimeout(() => {
					this.videoContext = uni.createVideoContext(`myVideo_${this.liveId}`,
						this);
					console.log('videoContext 初始化完成:', this.videoContext);
				}, 1000);
			});

		},
		//分享给好友
		onShareAppMessage() {
			return {
				title: '邀请你来观看课程：' + this.liveItem.liveName,
				path: '/pages_course/living?companyId=-2&companyUserId=' + this.userInfo.userId +
					'&liveId=' + this.liveId,
				imageUrl: 'https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/app/vip/share.png',
				success(res) {
					console.log('分享成功', res);
				},
				fail(err) {
					console.error('分享失败', err);
				}
			};
		},

		// 分享到朋友圈
		onShareTimeline() {
			return {
				title: '邀请你来观看课程：' + this.liveItem.liveName,
				query: 'companyId=-2&companyUserId=' + this.userInfo.userId + '&liveId=' + this.liveId
			};
		},
		computed: {
			shouldShowIntegralPopup() {
				//只有当 showPoints 为 true 且 receiveList 有数据时才显示
				return this.showPoints;
			},
			// 格式化后的倒计时
			formattedCountdown() {
				return this.formatCountdown(this.pointsRemainingTime);
			},

			// 倒计时百分比
			countdownPercentage() {
				return this.getCountdownPercentage();
			},

			// 环形进度条样式
			// circularStyle() {
			// 	const percentage = this.getCountdownPercentage();
			// 	const strokeDashoffset = 314 - (314 * percentage) / 100; // 2 * π * 50 = 314
			// 	return {
			// 		'--percentage': percentage + '%',
			// 		'--stroke-dashoffset': strokeDashoffset
			// 	};
			// },

			// 是否显示倒计时
			// showCountdown() {
			// 	return !this.hasReachedTarget &&
			// 		this.liveItem?.liveType === 2 && // 只对录播显示
			// 		this.pointsRemainingTime > 0 && // 还有剩余时间
			// 		this.pointsRemainingTime < this.liveItem.duration * this.completionRate; // 已经开始计时
			// },

			// 控制是否显示非视频元素
			shouldShowNonVideoElements() {
				return !this.isFullscreen && this.showNonVideoElementsFlag;
			},

			// 控制是否显示全屏按钮
			shouldShowFullscreenButton() {
				return this.liveItem.showType == 1 && !this.isFullscreen;
			},
			...mapGetters(['coureLogin']),
			appid() {
				return this.$store.state.appid
			},
			// 观看人数
			formattedWatchCount() {
				return this.formatNumber(this.virtualHuman || 0);
			},
			//点赞人数
			formattedLikeCount() {
				return this.formatNumber(this.liveViewData.like || 0);
			},
			hasQuizSelection() {
				if (this.liveQuiz && Number(this.liveQuiz.type) === 2) {
					return Array.isArray(this.liveQuizSelectedKeys) && this.liveQuizSelectedKeys.length > 0;
				}
				return !!this.liveQuizSelectedKey;
			},
			// 答题选项列表（模板 v-for 只用稳定数组，避免部分端解析异常）
			liveQuizOptionList() {
				const q = this.liveQuiz;
				if (!q || !Array.isArray(q.options)) return [];
				return q.options;
			},
			filteredViewers() {
				// 获取3个随机假头像，而不是显示真实观众
				const avatarCount = 3; // 需要显示的假头像数量

				// 如果fakeAvatar数组为空或不存在，返回空数组
				if (!this.fakeAvatar || !Array.isArray(this.fakeAvatar) || this.fakeAvatar.length === 0) {
					return [];
				}

				// 从fakeAvatar中随机选择3个不同的头像
				const randomAvatars = [];
				const availableAvatars = [...this.fakeAvatar]; // 创建副本避免修改原数组

				// 确保有足够的头像可选
				if (availableAvatars.length < avatarCount) {
					// 如果头像数量不足，可以重复使用
					for (let i = 0; i < avatarCount; i++) {
						const randomIndex = Math.floor(Math.random() * availableAvatars.length);
						randomAvatars.push(availableAvatars[randomIndex]);
					}
				} else {
					// 随机选择不重复的头像
					for (let i = 0; i < avatarCount; i++) {
						const randomIndex = Math.floor(Math.random() * availableAvatars.length);
						randomAvatars.push(availableAvatars[randomIndex]);
						availableAvatars.splice(randomIndex, 1); // 移除已选的头像，避免重复
					}
				}

				console.log("随机选择的头像:", randomAvatars);
				return randomAvatars;
			},
			isCurrentUserWon() {
				if (!Array.isArray(this.prizeInfo) || !this.userInfo?.userId) {
					return false;
				}
				return this.prizeInfo.some((item) => {
					return String(item.userId) === String(this.userInfo.userId);
				});
			},
			getCurrentUserPrizeProductId() {
				if (!Array.isArray(this.prizeInfo) || !this.userInfo?.userId) {
					return null;
				}
				// 在 prizeInfo 中查找当前用户的中奖记录
				const userPrize = this.prizeInfo.find(item => {
					return String(item.userId) == String(this.userInfo.userId);
				});

				// 返回商品ID，如果没有找到则返回null
				return userPrize ? userPrize.productId : null;
			},
			getCurrentUserPrizeRecordId() {
				if (!Array.isArray(this.prizeInfo) || !this.userInfo?.userId) {
					console.log('条件不满足，返回null');
					return null;
				}
				const userPrize = this.prizeInfo.find(item => {
					const match = String(item.userId) == String(this.userInfo.userId);
					return match;
				});
				return userPrize ? userPrize.recordId : null;
			},
			nameuser() {
				return this.userInfo.nickname
			},
		},
		onHide() {
			if (this.$refs.chat && this.$refs.chat.closeChatInput) {
				this.$refs.chat.closeChatInput();
			}
			this.updateWatchDuration(); //更新用户的看课时长
			this.stopCountdown();
			if (this.watchTimeTimer) {
				clearInterval(this.watchTimeTimer);
				this.watchTimeTimer = null;
			}
			this.saveWatchTime();
			//  清除所有定时器
			// this.clearAllTimersEnhanced();
			// this.stopHeartBeat();
			// 页面隐藏时，提交当前流量数据
			if (this.videoLoaded && this.trafficStartTime && this.trafficTimer) {
				const watchDuration = Math.floor((this.getServerTimeNow() - this.trafficStartTime) / 1000);
				this.submitTraffic(watchDuration);
			}
			if (this.trafficTimer) {
				clearInterval(this.trafficTimer);
				this.trafficTimer = null;
			}
			// 清除课程间数据定时器（防止页面隐藏后继续请求）
			if (this.liveViewDataTimer) {
				clearInterval(this.liveViewDataTimer);
				this.liveViewDataTimer = null;
			}
			// 暂停观看时长统计
			this.pauseWatchDurationTracking();
			// 页面隐藏时清理部分数据，减少内存占用
			if (this.$refs.chat && this.$refs.chat.trimTalklist) {
				this.$refs.chat.trimTalklist(20);
			}
			// 触发垃圾回收
			// this.triggerGarbageCollection();
		},
		onVideoStateChange(e) { //废弃
			// 这里可以根据视频状态控制倒计时
			if (e.detail.code === 2004) { // 视频开始播放
				//this.startCountdown();
			} else if (e.detail.code === 2006) { // 视频播放结束
				this.stopCountdown();
			}
		},
		onUnload() {

			this.stopCountdown();
			if (this.watchTimeTimer) {
				clearInterval(this.watchTimeTimer);
				this.watchTimeTimer = null;
			}
			this.saveWatchTime();
			// 保存视频进度
			this.saveVideoProgress();
			// 停止观看时长统计
			this.stopWatchDurationTracking();
			// 用户退出时，再次请求一次10s流量接口
			if (this.videoLoaded && this.trafficStartTime) {
				const watchDuration = Math.floor((this.getServerTimeNow() - this.trafficStartTime) / 1000);
				// 提交最后一次流量数据（至少10秒）
				const finalDuration = Math.max(watchDuration, 10);
				this.submitTraffic(finalDuration);
			}
			// 清理课程相关定时器
			if (this.liveItem) {
				this.pauseVideo();
				// 清除课程间的时间定时器
				if (this.liveItem.timeTimer) {
					clearInterval(this.liveItem.timeTimer);
					this.liveItem.timeTimer = null;
				}
			}

			// 销毁 WebSocket 管理器
			this.liveSocket?.destroy();
			this.liveSocket = null;

			// 清除 getliving 防抖定时器
			if (this.getlivingTimer) {
				clearTimeout(this.getlivingTimer);
				this.getlivingTimer = null;
			}
            // 显式清除课程间数据定时器（防止页面卸载后继续请求）
            			if (this.liveViewDataTimer) {
            				clearInterval(this.liveViewDataTimer);
            				this.liveViewDataTimer = null;
            			}
			// 清除所有定时器（使用增强清理）
			this.clearAllTimersEnhanced();

			// 暂停视频
			const videoId = `myVideo_${this.liveId}`;
			const videoContext = uni.createVideoContext(videoId, this);
			if (videoContext) {
				videoContext.pause();
			}
			// 移除网络状态监听
			try {
				uni.offNetworkStatusChange();
			} catch (err) {
				console.warn('移除网络状态监听失败:', err);
			}
			// 清理大数据和状态
			this.clearBigData();
			this.resetAllStates();
			// 解锁屏幕方向
			this.unlockOrientation();
			// 强制退出全屏
			this.isFullscreen = false;
			this.showCustomControls = true;
		},

		mounted() {
			this.systemInfo = uni.getSystemInfoSync();
			console.log('系统信息:', this.systemInfo.platform, this.systemInfo.model);
		},
		watch: {
			coureLogin: {
				immediate: true, // 页面一进入就检查一次
				handler(val) {
					if (val == 2 && this.isLogin) {
						this.isLogin = false
						this.goLogin();
					}
				}
			},
			// 监听liveItem.status的变化
			'liveItem.status': {
				handler(newStatus, oldStatus) {
					if (newStatus === undefined || oldStatus === undefined) return;
					if (newStatus === oldStatus) return;
					if (!this.liveId) {
						console.warn('liveId不存在，无法触发getliving请求');
						return;
					}
					// 状态变化时，调用getliving更新课程间数据
					// 添加防抖，避免频繁请求
					if (this.getlivingTimer) {
						clearTimeout(this.getlivingTimer);
					}
					this.getlivingTimer = setTimeout(() => {
						this.getliving(this.liveId);
					}, 500); // 500ms 防抖
				},
				deep: true
			},
			// 监听orderUser.count的变化
			'orderUser.count': {
				handler(newVal, oldVal) {
					if (newVal !== this.prevOrderCount) {
						this.prevOrderCount = newVal;
						this.showPurchaseMessage();
					}
				},
				immediate: true
			},
		},
		methods: {
			// 查询当前用户当前课程间领取积分的剩余时长
			getRemainingTime(refresh = false) {
				if (!this.liveId) return;
				fetchRemainingTime(this.liveId, refresh).then((res) => {
					if (res.code == 200) {
						this.hasReceived = res.data.hasReceived;
						this.videoDuration = res.data.videoDuration;
						this.watchDuration = res.data.watchDuration;
						console.log("查询当前用户当前课程间领取积分的剩余时长", res)
					}
				}).catch(() => {});
			},
			loadSecondaryLiveData(refresh = false) {
				if (!refresh && this.secondaryDataLoaded) {
					return;
				}
				if (!this.liveId) {
					return;
				}
				this.secondaryDataLoaded = true;
				this.loadCompletionRecords(refresh);
				if (this.liveItem.completionPointsEnabled) {
					this.getRemainingTime(refresh);
				}
			},
			loadCompletionRecords(refresh = false) {
				if (!this.liveId) return;
				fetchCompletionRecords(this.liveId, refresh).then((res) => {
					if (res.code == 200) {
						const targetData = res.data.find(item => item.liveId == this.liveId);
						if (targetData) {
							this.receiveStatus = true;
						} else {
							this.receiveStatus = false;
						}
						console.log("查询用户积分领取记录", res)
					}
				}).catch(() => {});
			},

			// 更新用户的看课时长 (传入课程间id和看课时长)
			updateWatchDuration() {
				if (!this.liveId) return;
				if (this.isPreview) return;
				//const watchDuration = Math.floor((Date.now() - this.liveBeginWatchTime) / 1000)
				const watchDuration = this.totalWatchTime - this.watchDuration;
				updateWatchDuration(this.liveId, watchDuration).then((res) => {
					if (res.code == 200) {
						console.log("更新用户的看课时长", res);
						this.receivePoints();
					}
				}).catch((error) => {

				});
			},

			// 用户领取看课积分 (传入课程间id)
			receivePoints(retryCount = 0) {
				if (!this.liveId) return;
				const data = {
					liveId: this.liveId
				}
				receivePoints(data).then((res) => {
					if (res.code == 200) {
						console.log("用户领取看课积分", res);
						//清除重试定时器
						if (this.pointsRetryTimer) {
							clearTimeout(this.pointsRetryTimer);
							this.pointsRetryTimer = null;
						}
					}
				}).catch((error) => {
					console.log("用户领取积分失败error", error);
					// 增加重试机制：最多重试3次
					if (retryCount < 3) {
						const delay = (retryCount + 1) * 2000; // 递增延迟: 2s, 4s, 6s
						console.log(`领取积分失败，${delay}ms后进行第${retryCount + 1}次重试`);
						if (this.pointsRetryTimer) {
							clearTimeout(this.pointsRetryTimer);
						}
						this.pointsRetryTimer = setTimeout(() => {
							this.receivePoints(retryCount + 1);
						}, delay);
					}
				});
			},

			// ======================== 观看时长统计相关方法 ========================
			/**
			 * 开始观看时长统计
			 * WebSocket连接成功后调用
			 */
			startWatchDurationTracking() {
				// 防止重复启动
				if (this.watchStartTime > 0) {
					console.log('观看时长统计已启动，跳过');
					return;
				}
				this.watchStartTime = Date.now();
				this.isPageVisible = true;
				console.log('开始观看时长统计', new Date(this.watchStartTime).toLocaleString());

				// 启动页面可见性监听
				this.initPageVisibilityListener();
			},

			/**
			 * 获取当前累计观看时长（秒）
			 * @returns {number} 观看时长（秒）
			 */
			getCurrentWatchDuration() {
				if (this.watchStartTime === 0) {
					return this.accumulatedWatchDuration;
				}
				// 如果页面可见，计算当前时段的时长
				if (this.isPageVisible) {
					const currentDuration = Math.floor((Date.now() - this.watchStartTime) / 1000);
					return this.accumulatedWatchDuration + currentDuration;
				}
				// 页面不可见，返回累计时长
				return this.accumulatedWatchDuration;
			},

			/**
			 * 暂停观看时长统计（页面隐藏/后台时）
			 */
			pauseWatchDurationTracking() {
				if (!this.isPageVisible || this.watchStartTime === 0) {
					return;
				}
				// 累加本次观看的时长
				const currentSessionDuration = Math.floor((Date.now() - this.watchStartTime) / 1000);
				this.accumulatedWatchDuration += currentSessionDuration;
				this.lastPauseTime = Date.now();
				this.isPageVisible = false;
				console.log(`暂停观看统计: 本次=${currentSessionDuration}秒, 累计=${this.accumulatedWatchDuration}秒`);
			},

			/**
			 * 恢复观看时长统计（页面显示/前台时）
			 */
			resumeWatchDurationTracking() {
				if (this.isPageVisible) {
					return;
				}
				// 重新记录开始时间
				this.watchStartTime = Date.now();
				this.isPageVisible = true;
				const pauseDuration = this.lastPauseTime > 0 ? Math.floor((Date.now() - this.lastPauseTime) /
					1000) : 0;
				console.log(`恢夏观看统计: 暂停了${pauseDuration}秒, 当前累计=${this.accumulatedWatchDuration}秒`);
			},

			/**
			 * 停止观看时长统计
			 */
			stopWatchDurationTracking() {
				if (this.isPageVisible && this.watchStartTime > 0) {
					const currentSessionDuration = Math.floor((Date.now() - this.watchStartTime) / 1000);
					this.accumulatedWatchDuration += currentSessionDuration;
				}
				console.log(`停止观看统计: 总时长=${this.accumulatedWatchDuration}秒`);
				// 重置状态
				this.watchStartTime = 0;
				this.isPageVisible = true;
				this.lastPauseTime = 0;
				// 移除监听
				this.removePageVisibilityListener();
			},

			/**
			 * 初始化页面可见性监听
			 */
			initPageVisibilityListener() {
				// uni-app 的页面生命周期已经在 onShow/onHide 中处理
				// 这里主要监听小程序的前后台切换
				uni.onAppShow(() => {
					console.log('小程序回到前台');
					this.resumeWatchDurationTracking();
				});

				uni.onAppHide(() => {
					console.log('小程序切换到后台');
					this.pauseWatchDurationTracking();
				});
			},

			/**
			 * 移除页面可见性监听
			 */
			removePageVisibilityListener() {
				// uni-app 不需要手动移除监听，生命周期自动管理
				console.log('页面可见性监听已移除');
			},
			/**
			 * 获取当前服务器时间戳（毫秒）
			 * 如果存在 serviceTime，则基于服务器时间计算；否则使用本地时间
			 * serviceTime 格式：1768816544512（13位毫秒级时间戳）
			 */
			getServerTimeNow() {
				if (!this.liveItem || !this.liveItem.serviceTime) {
					return Date.now();
				}
				//return this.liveItem.serviceTime;
				const localTimeWhenReceived = this.liveItem._localTimeWhenReceived;
				if (!localTimeWhenReceived) {
					// 如果没有记录接收时间，使用本地时间
					return Date.now();
				}
				let serverTimeWhenReceived;
				const serviceTime = this.liveItem.serviceTime;

				//如果 serviceTime 是数字类型（毫秒级时间戳，如：1768816544512）
				if (typeof serviceTime === 'number') {
					serverTimeWhenReceived = serviceTime;
				}
				//如果 serviceTime 是字符串格式的数字时间戳
				else if (typeof serviceTime === 'string' && /^\d+$/.test(serviceTime)) {
					// 纯数字字符串，转换为数字
					const numTime = Number(serviceTime);
					// 判断是秒级还是毫秒级时间戳（13位及以上为毫秒级）
					serverTimeWhenReceived = numTime < 1000000000000 ? numTime * 1000 : numTime;
				}
				//如果 serviceTime 是时间字符串（如：2025-01-01 12:00:00）
				else {
					const safeTimeStr = String(serviceTime).replace(/-/g, '/');
					serverTimeWhenReceived = Date.parse(safeTimeStr);
					if (isNaN(serverTimeWhenReceived)) {
						return Date.now();
					}
				}

				//计算服务器时间与本地时间的差值（毫秒）
				const timeDiff = serverTimeWhenReceived - localTimeWhenReceived;
				// 当前服务器时间 = 当前本地时间 + 时间差
				return Date.now() + timeDiff;
			},
			/**
			 * 获取课程开始时间，优先使用 serviceStartTime，如果不存在则使用 startTime
			 */
			getLiveStartTime() {
				if (!this.liveItem) {
					return null;
				}
				// 优先使用 serviceStartTime（服务器返回的课程开始时间）
				if (this.liveItem.serviceStartTime) {
					return this.liveItem.serviceStartTime;
				}
				// 如果不存在，回退到 startTime
				return this.liveItem.startTime || null;
			},
			/**
			 * 计算当前时间与目标时间的差值（秒）
			 */
			calculateLiveTimeDiff(timeStr, useServerTime = false) {
				// 0. 安全校验：防止 undefined/null 导致 crash
				if (!timeStr) {
					return 0;
				}
				// 1. 获取当前时间戳（毫秒）- 倒计时场景使用服务器时间
				const now = this.getServerTimeNow();
				// 3. 【关键】解决 iOS 兼容性问题
				// iOS 系统不支持 "2025-12-25" 这种带横杠的格式，需要替换为斜杠 "2025/12/25"
				// const safeTimeStr = new Date(timeStr.replace(/-/g, '/'));
				// // 4. 解析目标时间戳（毫秒）
			 //    const liveStartTime = Date.parse(safeTimeStr);
				// 5. 计算差值（毫秒 -> 秒）
				// 结果为：当前时间 - 课程开始时间
				const diffInSeconds = Math.floor((now - timeStr) / 1000);
				//console.log("结果为：当前时间 - 课程开始时间,",diffInSeconds,now,timeStr)
				return diffInSeconds;
			},
			// 根据开始时间和时长计算结束时间
			calculateLiveEndTime(startDate, duration) {
				if (!startDate) return '';
				// 计算结束时间戳
				const endTimeMs = startDate + (Number(duration) * 1000);
				const endDate = new Date(endTimeMs);
				// 格式化
				const year = endDate.getFullYear();
				const month = this.padZero(endDate.getMonth() + 1);
				const day = this.padZero(endDate.getDate());
				const hours = this.padZero(endDate.getHours());
				const minutes = this.padZero(endDate.getMinutes());
				const seconds = this.padZero(endDate.getSeconds());
				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			// 开始倒计时
			startCountdown() {
				///console.log("this.completionPointsEnabled",this.liveItem)
				if (!this.liveItem.completionPointsEnabled) {
					return;
				}
				// 如果倒计时已经在运行，先清除旧的定时器
				if (this.countdownTimer) {
					clearInterval(this.countdownTimer);
					this.countdownTimer = null;
				}
				// 使用服务器时间重新计算初始状态，确保设备时间不一致时也能正确判断
				const liveStartTime = this.getLiveStartTime();
				if (liveStartTime) {
					this.diffLiveStartTime = this.calculateLiveTimeDiff(liveStartTime, true);
					// 如果课程已开始，确保 isPreview 为 false
					if (this.diffLiveStartTime >= 0 ) {
						this.isPreview = false;
					}
				}
				this.isCountdownActive = true;
				// 立即执行一次更新，确保倒计时显示正确
				this.updateCountdown();
				this.countdownTimer = setInterval(() => {
					this.updateCountdown();
				}, 1000); // 每秒更新一次
				//console.log("this.completionPointsEnabled+++++++",this.liveItem.completionPointsEnabled,this.countdownPercentage,this.receiveStatus,this.hasReceived,this.isPreview)
			},
			// 更新倒计时
			updateCountdown() {
				if (!this.liveItem) {
					return;
				}
				//console.log("this.completionPointsEnabled",this.completionTime)
				this.completionTime = this.liveItem.duration * this.completionRate;
				//console.log("qxj watchDuration:"+this.watchDuration+" completionTime:"+this.completionTime+" pointsRemainingTime:"+this.pointsRemainingTime);
				//console.log(`qxj countdownPercentage=${this.countdownPercentage} completionPointsEnabled=${this.liveItem.completionPointsEnabled} receiveStatus=${this.receiveStatus} liveItemStatus=${this.liveItem.status} hasReceived=${this.hasReceived} isPreview=${this.isPreview}`);
				if (this.watchDuration > this.completionTime) { //已达成观看时间
					if (this.countdownTimer) {
						clearInterval(this.countdownTimer);
						this.countdownTimer = null;
						this.isPreview = true;
						return;
					}
				}
				if (this.pointsRemainingTime < 0) {
					this.stopCountdown();
					return;
				}
				this.showPoints = false;
				// 使用服务器时间计算差值
				const serverTimeNow = this.getServerTimeNow();
				const liveStartTime = this.getLiveStartTime();
				this.diffLiveStartTime = this.calculateLiveTimeDiff(liveStartTime, true);
				this.diffLiveEndTime = this.calculateLiveTimeDiff(liveStartTime, true) - this.liveItem.duration;
				if (!this.liveItem.finishTime) {
					this.liveItem.finishTime = this.calculateLiveEndTime(liveStartTime, this.liveItem.duration); //得出首播结束时间
				}
				if (this.diffLiveStartTime < 0) { //预告状态
					this.isPreview = true;
					//console.log('updateCountdown - 服务器时间显示课程还未开始，设置为预告状态');
					return;
				} else {
					// 课程已开始（基于服务器时间），确保 isPreview 为 false
					this.isPreview = false;
					//console.log('updateCountdown - 课程已开始，设置 isPreview = false');
				}
				if (this.diffLiveStartTime >= 0) {
					this.totalWatchTime = this.watchDuration + Math.floor((serverTimeNow - this.liveBeginWatchTime) /
						1000); //累计观看的总时长
				}
				//console.log("qxj课程中 completionTime:"+this.completionTime+" totalWatchTime:"+this.totalWatchTime+" pointsRemainingTime:"+this.pointsRemainingTime+" watchDuration:"+this.watchDuration+", liveBeginWatchTime:"+this.liveBeginWatchTime);
				if (this.totalWatchTime >= this.completionTime) { //积分领取满足条件
					if (this.countdownTimer) {
						clearInterval(this.countdownTimer);
						this.countdownTimer = null;
						this.onCountdownComplete();
						return;
					}
				}

				if (this.diffLiveStartTime >= 0) {
					this.isPreview = false;
					if (this.diffLiveEndTime < 0) { //课程中状态
						this.pointsRemainingTime = Math.max(0, this.completionTime - this.totalWatchTime);
					}
					if (this.diffLiveEndTime >= 0) { //课程回放中
						this.pointsRemainingTime = Math.max(0, this.completionTime - this.totalWatchTime);
					}
				}
				// 更新显示
				this.updateCountdownDisplay();
			},

			// 停止倒计时
			stopCountdown() {
				if (this.countdownTimer) {
					clearInterval(this.countdownTimer);
					this.countdownTimer = null;
				}
				this.isCountdownActive = false;
				this.updateWatchDuration();
				//this.saveWatchProgress(); // 立即保存
			},

			// 倒计时完成
			onCountdownComplete() {
				console.log('倒计时完成!');
				this.stopCountdown();
				this.pointsRemainingTime = -1;
				//this.updateCountdownDisplay();
				this.triggerWatchComplete();
				setTimeout(() => {
					// 5秒后自动隐藏
					this.showToast = true;
					setTimeout(() => {
						this.showToast = false;
					}, 5000); // 5000ms = 5秒
				}, 1000);

				// setTimeout(()=>{
				// 	uni.showToast({title:"完课积分已到账",duration:150000,icon:"none"});
				// },1000);
				// setTimeout(()=>{
				// 	this.showPoints=true;
				// },5000)
			},

			// 触发观看完成事件
			async triggerWatchComplete() {
				if (!this.userInfo?.userId || !this.liveId) return;
				try {
					// 这里可以调用API通知服务器用户已完成观看
					console.log('用户已完成观看');
					// 清空进度，防止重复计算
					uni.removeStorageSync(this.watchProgressKey);
				} catch (error) {
					console.error('触发观看完成事件失败:', error);
				}
			},

			// 补零函数
			padZero(num) {
				return num < 10 ? `0${num}` : num.toString();
			},

			// 倒计时格式化函数
			formatCountdown(seconds) {
				// 1. 先校验输入：确保是有效正整数，避免负数/非数字导致计算错误
				const totalSeconds = Math.max(0, Math.floor(Number(seconds) || 0));
				// 2. 重新梳理计算逻辑（核心修复）
				const hours = Math.floor(totalSeconds / 3600);
				const remainingAfterHours = totalSeconds % 3600; // 小时取余后剩余的秒数
				const minutes = Math.floor(remainingAfterHours / 60);
				const secs = remainingAfterHours % 60;
				// 3. 返回格式化结果（补零+原始值）
				return {
					hours: this.padZero(hours),
					minutes: this.padZero(minutes),
					seconds: this.padZero(secs),
					total: totalSeconds // 确保total是处理后的有效数值
				};
			},
		getCountdownPercentage() {
			// 1. 使用倒计时的 remainingTime 计算进度
			if (!this.getRemainingTime) {
				console.log('进度条计算：liveItem.duration无效', this.liveItem?.duration);
				return 0;
			}
			// 2. 如果还在预告状态或课程未开始，返回0%
			const liveStartTime = this.getLiveStartTime();
			if (this.isPreview || !this.liveItem || !liveStartTime) {
				return 0;
			}
			// 3. 使用服务器时间判断课程是否已开始（以服务器时间为准）
			const diffLiveStartTime = this.calculateLiveTimeDiff(liveStartTime, true);
			if (diffLiveStartTime < 0) {
				// 服务器时间显示课程还未开始，无论status是什么，都返回0%
				// 这样可以避免设备时间小于服务器时间时，pointsRemainingTime为0导致返回100%的问题
				return 0;
			}
			// 4. 如果 videoDuration 未初始化，返回0%
			if (!this.videoDuration || this.videoDuration <= 0) {
				return 0;
			}
			// 5. 如果已经达到目标（pointsRemainingTime <= 0），直接返回100%
			if (this.pointsRemainingTime <= 0) {
				return 100;
			}
			//console.log('进度条计算：this.pointsRemainingTime', this.pointsRemainingTime, 'videoDuration:', this.videoDuration);
			// 6. remainingTime = 剩余需要观看的时间
			// 已观看时间 = 总目标时间 - 剩余时间
			const watchedTime = this.videoDuration - this.pointsRemainingTime;
			// 7. 确保数值有效
			if (watchedTime <= 0) {
				return 0;
			}
			// 8. 计算百分比（已观看时间 / 目标时间）
			const percentage = (watchedTime / this.videoDuration) * 100;
			// 9. 限制在 0-100 范围内
			return Math.min(100, Math.max(0, percentage));
		},
			// 更新倒计时显示（如果需要强制更新视图）
			updateCountdownDisplay() {
				// 如果需要，可以在这里触发视图更新
				this.$forceUpdate();
			},
			// 初始化观看时间
			initWatchTime() {
				// 创建基于用户ID和课程ID的存储键
				const userId = this.userInfo?.userId || 'anonymous';
				this.watchTimeStorageKey = `watchTime_${userId}_${this.liveId}`;
				// 从本地存储加载累计观看时间
				try {
					const storedTime = uni.getStorageSync(this.watchTimeStorageKey);
					this.totalWatchTime = storedTime ? parseInt(storedTime) : 0;
					console.log(`加载累计观看时间: ${this.totalWatchTime}秒`);
				} catch (error) {
					console.error('加载观看时间失败:', error);
					this.totalWatchTime = 0;
				}
			},

			//保存观看时间到本地存储
			saveWatchTime() {
				if (!this.watchTimeStorageKey) return;
				try {
					uni.setStorageSync(this.watchTimeStorageKey, this.totalWatchTime);
					console.log(`保存观看时间: ${this.totalWatchTime}秒`);
				} catch (error) {
					console.error('保存观看时间失败:', error);
				}
			},

			// 格式化显示时间
			formatWatchTime(seconds) {
				const hours = Math.floor(seconds / 3600);
				const minutes = Math.floor((seconds % 3600) / 60);
				const secs = seconds % 60;
				return {
					hours: this.padZero(hours),
					minutes: this.padZero(minutes),
					seconds: this.padZero(secs),
					total: seconds
				};
			},

			// // 获取用户未领取的积分列表
			// completionUnreceived() {
			// 	if (!this.liveId) return;
			// 	const data = {
			// 		liveId: this.liveId
			// 	}
			// 	completionUnreceived(data).then((res) => {
			// 		if (res.code == 200) {
			// 			console.log("获取用户未领取的积分列表", res)
			// 			if (res.data) {
			// 				this.receiveList = res.data
			// 				this.showPoints = true
			// 			}
			// 		}
			// 	}).catch((error) => {});
			// },

			// 领取完课积分
			// completionReceive(item) {
			// 	if (!item.id) return;
			// 	completionReceive(item.id).then((res) => {
			// 		if (res.code == 200) {
			// 			this.showPoints = false
			// 			console.log("领取完课积分", res)
			// 			uni.showToast({
			// 				title: '领取积分成功',
			// 				icon: 'none'
			// 			});
			// 		}
			// 	}).catch((error) => {});
			// },

			getMenuButtonInfo() {
				// 微信小程序API（Uniapp可直接用uni.getMenuButtonBoundingClientRect）
				const menuBtn = uni.getMenuButtonBoundingClientRect();
				if (menuBtn) {
					this.menuButtonInfo = {
						top: menuBtn.top + 'px', // 胶囊顶部距离
						height: menuBtn.height + 'px', // 胶囊高度
						centerY: (menuBtn.top + menuBtn.height / 2) + 'px', // 胶囊垂直居中Y坐标
						right: menuBtn.right + 'px' // 胶囊右侧距离
					};
				}
			},
			// 退出全屏
			exitFullscreen() {
				console.log('执行退出全屏');
				this.isFullscreen = false;

				// 恢复竖屏样式
				this.restoreVideoList();

				// 显示非videolist元素
				this.showNonVideoElements();

				// 强制页面重排
				this.$forceUpdate();
			},
			// 添加屏幕方向变化监听
			addOrientationChangeListener() {
				if (window.addEventListener) {
					window.addEventListener('orientationchange', this.handleOrientationChange);
				}
			},

			// 移除屏幕方向变化监听
			removeOrientationChangeListener() {
				if (window.removeEventListener) {
					window.removeEventListener('orientationchange', this.handleOrientationChange);
				}
			}, // 处理屏幕方向变化
			handleOrientationChange() {
				uni.onWindowResize((res) => {
					const windowWidth = res.size.windowWidth;
					const windowHeight = res.size.windowHeight;
					const isLandscape = windowWidth > windowHeight;

					if (this.isFullscreen && !isLandscape) {
						console.log('全屏状态下屏幕方向不正确，尝试退出全屏');
						if (this.videoContext) {
							this.videoContext.exitFullScreen();
						}
					}
				});
			}, // 恢复videolist盒子
			restoreVideoList() {
				this.isVideoRotated = false;
				this.isFullscreen = false;
				console.log('恢复视频容器竖屏状态');
			},
			// 强制横屏全屏（备用方案）
			forceLandscapeFullscreen() {
				// 尝试多种全屏方式
				try {
					// 方案1: 使用video的requestFullScreen
					if (this.videoContext) {
						this.videoContext.requestFullScreen({
							direction: 90
						});
						return true;
					}
				} catch (e) {
					console.log('方案1失败:', e);
				}

				try {
					// 方案2: 尝试DOM全屏API
					const videoElement = document.getElementById(`myVideo_${this.liveId}`);
					if (videoElement && videoElement.requestFullscreen) {
						videoElement.requestFullscreen();
						return true;
					}
				} catch (e) {
					console.log('方案2失败:', e);
				}

				try {
					// 方案3: 使用Web API全屏
					if (document.documentElement.requestFullscreen) {
						document.documentElement.requestFullscreen();
						return true;
					}
				} catch (e) {
					console.log('方案3失败:', e);
				}

				console.log('所有全屏方案都失败了');
				uni.showToast({
					title: '无法全屏播放，请尝试手动横屏',
					icon: 'none'
				});
				return false;
			},
			// 切换全屏
			toggleFullscreen() {
				console.log('自定义全屏按钮被点击');
				if (this.isFullscreen) {
					// 退出全屏
					this.exitFullscreen();
				} else {
					// 进入全屏
					this.enterFullscreen();
				}
			}, // 进入全屏
			enterFullscreen() {
				console.log('执行进入全屏');
				this.isFullscreen = true;
				// 设置横屏样式
				this.rotateVideoList();

				// 隐藏非videolist元素
				this.hideNonVideoElements();

				// 强制页面重排
				this.$forceUpdate();
			},
			// 强制全屏的备用方案
			forceFullscreen() {
				console.log('使用备用方案进入全屏');
				const videoId = `myVideo_${this.liveId}`;
				// 在小程序中，只能使用 videoContext
				if (this.videoContext) {
					try {
						this.videoContext.requestFullScreen({
							direction: 90 // 横屏方向
						});
					} catch (error) {
						console.error('请求全屏失败:', error);
						uni.showToast({
							title: '无法全屏播放，请尝试手动横屏',
							icon: 'none'
						});
					}
				}
			}, // 隐藏非videolist元素
			hideNonVideoElements() {
				this.showNonVideoElementsFlag = false;
				console.log('隐藏非视频元素');
			},
			// 显示非videolist元素
			showNonVideoElements() {
				this.showNonVideoElementsFlag = true;
				console.log('显示非视频元素');
			},
			// 旋转videolist盒子
			rotateVideoList() {
				// 在小程序中，通过设置CSS类名来控制样式，而不是直接操作DOM
				this.isVideoRotated = true;
				this.isFullscreen = true;
				console.log('视频容器旋转到横屏状态');
			},
			// 全屏状态变化监听
			onFullscreenChange(e) {
				console.log('全屏状态变化事件详情:', e);
				// 方法1：通过事件参数获取（小程序主要方式）
				let fullScreen = false;
				// 视频组件的全屏事件参数
				if (e.detail && typeof e.detail.fullScreen !== 'undefined') {
					fullScreen = e.detail.fullScreen;
					console.log('通过e.detail.fullScreen获取全屏状态:', fullScreen);
				}
				// 其他可能的参数名
				else if (e.detail && typeof e.detail.fullscreen !== 'undefined') {
					fullScreen = e.detail.fullscreen;
					console.log('通过e.detail.fullscreen获取全屏状态:', fullScreen);
				} else {
					// 在小程序环境中，可以通过屏幕方向判断
					try {
						const systemInfo = uni.getSystemInfoSync();
						fullScreen = systemInfo.windowWidth > systemInfo.windowHeight;
						console.log('通过屏幕方向判断全屏状态:', fullScreen);
					} catch (err) {
						console.error('获取系统信息失败:', err);
						// 默认使用事件参数
						fullScreen = e.detail || false;
					}
				}

				this.isFullscreen = fullScreen;
				console.log('最终设置isFullscreen为:', this.isFullscreen);

				// 根据全屏状态显示/隐藏自定义控件
				this.showCustomControls = !this.isFullscreen;

				// 强制UI更新
				this.$forceUpdate();

				// 全屏时锁定横屏
				if (this.isFullscreen) {
					this.lockOrientation();
				} else {
					this.unlockOrientation();
				}
			},
			// 锁定屏幕方向为横屏
			lockOrientation() {
				// 设置屏幕方向为横屏
				try {
					// 尝试锁定横屏
					plus.screen.lockOrientation('landscape-primary');
				} catch (e) {
					console.log('锁定屏幕方向失败:', e);
					// 备用方案
					try {
						// 使用 Web API（如果支持）
						if (screen.orientation && screen.orientation.lock) {
							screen.orientation.lock('landscape');
						}
					} catch (err) {
						console.log('备用方案也失败了:', err);
					}
				}
			}, // 解锁屏幕方向
			unlockOrientation() {
				try {
					if (screen.orientation && screen.orientation.unlock) {
						screen.orientation.unlock();
					}
				} catch (err) {
					console.log('备用解锁方案也失败了:', err);
				}
			},

			shouquan() {
				if (this.user.nickname == '') {
					uni.showToast({
						icon: 'none',
						title: "请先授权微信昵称",
					});
				}
			},
			confimrname() {
				if (this.user.nickname == '') {
					uni.showToast({
						icon: 'none',
						title: "请授权微信昵称",
					});
					return
				}
				this.editUser();
				uni.setStorageSync('userInfo', this.userInfo);
				if (this.user.nickname) {
					this.userlogo = false;
				}
			},

			editUser() {
				this.user.nickName = this.user.nickname;
				editUser(this.user).then(
					res => {
						if (res.code == 200) {
							uni.showToast({
								icon: 'success',
								title: "修改成功",
							});
							this.getUserInfo()
						} else {
							uni.showToast({
								icon: 'none',
								title: res.msg,
							});
						}
					},
					rej => {}
				);
			},

			onNickNameInput(e) {
				console.log(e)
				this.user.nickname = e.detail.value
			},
			async haveLogin() {
				if (this.initPromise) {
					return this.initPromise;
				}
				this.initPromise = this._doHaveLogin();
				try {
					return await this.initPromise;
				} catch (err) {
					this.initPromise = null;
					throw err;
				}
			},
			async _doHaveLogin() {
				if (this.isOnload) {
					return;
				}
				this.isOnload = true;
				await this.getUserInfo();
				if (!this.liveId) {
					return;
				}
				await this.getliving(this.liveId);
				await this.$nextTick();
				await Promise.all([
					this.loadChatHistory(),
					this.initSocket()
				]).catch(err => {
					console.error('P0 加载失败:', err);
				});
				this.p0Ready = true;
				this.scheduleDeferredModules();
			},
			scheduleDeferredModules() {
				if (this.p1DataLoaded) {
					return;
				}
				setTimeout(() => {
					if (this.p1DataLoaded) {
						return;
					}
					this.modules.p1 = true;
					this.loadP1Data();
				}, 1500);
			},
			loadP1Data(refresh = false) {
				if (!refresh && this.p1DataLoaded) {
					return;
				}
				if (!this.liveId) {
					return;
				}
				this.p1DataLoaded = true;
				this.getliveViewData(refresh);
				this.loadLiveOrderUser(refresh);
				this.modules.p2Activity = true;
				this.applyCurrentActivities(refresh);
			},
			loadLiveOrderUser(refresh = false) {
				if (!this.liveId) return;
				fetchLiveOrderUser(this.liveId, refresh).then(res => {
					if (res.code === 200) {
						this.orderUser = res;
					}
				}).catch(() => {});
			},
			onShopOpenCart() {
				if (this.$refs.shop && this.$refs.shop.openCart) {
					this.$refs.shop.openCart();
				}
			},
			onShopOpenMore() {
				this.isMore = true;
				if (this.$refs.shop && this.$refs.shop.closeShop) {
					this.$refs.shop.closeShop();
				}
			},
			ensureLiveSocket() {
				if (this.liveSocket) return;
				this.liveSocket = createLiveSocket({
					wsBaseUrl: this.wsBaseUrl,
					getWsBaseUrl: () => this.wsBaseUrl,
					getConnectConfig: () => ({
						liveId: this.liveId,
						userId: this.userInfo?.userId,
						userType: this.userType,
						qrFrom: this.qrFrom,
						urlOption: this.urlOption,
						address: this.address
					}),
					getToken: () => uni.getStorageSync('AppToken'),
					getNetworkAvailable: () => this.isNetworkAvailable,
					getNetworkType: () => this.networkType,
					getWatchDuration: () => this.getCurrentWatchDuration(),
					onMessage: (res) => this.handleSocketMessage(res),
					onOpen: () => {
						this.socketConnected = true;
						this.shownEntryUsers.clear();
					},
					onClose: () => {
						this.socketConnected = false;
						this.pauseWatchDurationTracking();
					}
				});
			},
			initSocket() {
				this.ensureLiveSocket();
				if (!this.isSocketAvailable()) {
					this.liveSocket.close(true);
				}
				this.liveSocket.isManualClose = false;
				this.liveSocket.connect();
			},
			closeWebSocket(isManual = true) {
				this.liveSocket?.close(isManual);
				this.socketConnected = false;
			},
			isSocketAvailable() {
				return this.socketConnected && (this.liveSocket?.isAvailable() ?? false);
			},
			handleReconnect() {
				this.ensureLiveSocket();
				this.liveSocket.triggerReconnect();
			},
			handleChatSend(payload) {
				const { data, resolve, reject } = payload || {};
				this._sendChatMessage(data).then(resolve).catch(reject);
			},
			async _sendChatMessage(data) {
				const ready = await this._waitSocketReady(6000);
				if (!ready) {
					uni.showToast({ title: '连接未就绪，请稍后重试', icon: 'none' });
					throw new Error('socket not ready');
				}
				return this.sendSocketMessage(data);
			},
			_waitSocketReady(timeoutMs = 6000) {
				if (this.isSocketAvailable()) {
					return Promise.resolve(true);
				}
				this.initSocket();
				const start = Date.now();
				return new Promise((resolve) => {
					const tick = () => {
						if (this.isSocketAvailable()) {
							resolve(true);
							return;
						}
						if (Date.now() - start >= timeoutMs) {
							resolve(false);
							return;
						}
						setTimeout(tick, 200);
					};
					tick();
				});
			},
			sendSocketMessage(data) {
				if (!this.liveSocket) {
					return Promise.reject(new Error('socket not ready'));
				}
				return this.liveSocket.send(data);
			},
			onChatFocusChange(focused) {
				this.isFocus = focused;
			},
			onChatKeyboardShow() {
				this.isKeyboardShow = true;
				this.hideGoodsCardForKeyboard();
			},
			onChatKeyboardHide() {
				this.isKeyboardShow = false;
				this.restoreGoodsCardAfterKeyboard();
			},
			async loadChatHistory(refresh = false) {
				if (!refresh && this.chatHistoryLoaded) {
					return;
				}
				if (this.$refs.chat && this.$refs.chat.loadHistory) {
					await this.$refs.chat.loadHistory(this.liveItem, refresh);
					this.chatHistoryLoaded = true;
				}
			},
			onShopBuy({ productId, goodsId }) {
				uni.navigateTo({
					url: '/pages_shopping/live/goods?productId=' + productId + '&liveId=' +
						this.liveId + '&goodsId=' + goodsId + '&storeId=' + this.storeId
				});
			},
			onVideoFullscreenChange(fullScreen) {
				this.isFullscreen = !!fullScreen;
				if (!fullScreen) {
					this.showCustomControls = true;
				}
			},
			onVideoLiveStateChange(code) {
				this.onLiveStateChange({ detail: { code } }, this.liveItem);
			},
			playVideoByRef() {
				if (this.$refs.videoPlayer && this.$refs.videoPlayer.playVideo) {
					this.$refs.videoPlayer.playVideo();
				} else {
					this.playVideo();
				}
			},
			// 静默登录
			goLogin(data) {
				let provider = 'weixin'
				uni.login({
					provider: provider,
					success: async loginRes => {
						uni.getUserInfo({
							provider: provider,
							success: (infoRes) => {
								uni.showToast({
									title: '登录中...',
									icon: 'loading'
								});
								loginByMp({
									code: loginRes.code,
									encryptedData: infoRes.encryptedData,
									iv: infoRes.iv,
									appId: this.appid
								}).then(res => {
									uni.hideLoading();
									if (res.code == 200) {
										uni.setStorageSync('AppToken', res
											.token);
										uni.setStorageSync('userInfo', JSON
											.stringify(res
												.user));
										this.userInfo = uni.getStorageSync(
											'userInfo');
										// uni.setStorageSync('auto_userInfo', JSON.stringify(res.user));
										// this.user = res.user
										this.$store.commit('setCoureLogin', 1);
										this.isLogin = true
										this.haveLogin()
										this.userlogo = true
										// console.log("TOKEN_KEYAuto",TOKEN_KEYAuto)
										if (this.urlOption.qwUserId) {
											this.getIsAddKf() //this.getIsAddKf()
										}
									} else {
										uni.showToast({
											title: res.msg,
											icon: 'none'
										});
									}
								}).catch(err => {
									uni.hideLoading();
									uni.showToast({
										icon: 'none',
										title: "登录失败,请重新登录",
									});
								});
							}
						});
					}
				})
			},
			// liveWatchUser(){
			// 	var data={
			// 		qwUserId:this.urlOption.qwUserId,
			// 		liveId:this.urlOption.liveId,
			// 		userId:this.userInfo.userId,
			// 		corpId:this.urlOption.corpId,
			// 		companyUserId:this.urlOption.companyUserId,
			// 		qwExternalId:this.urlOption.qwExternalId,
			// 		companyId:this.urlOption.companyId,
			// 		chatId:this.urlOption.chatId,
			// 	}
			// 	liveWatchUser(data).then(
			// 		res => {
			// 			if (res.code == 200) {

			// 			} else {
			// 				uni.showToast({
			// 					icon: 'none',
			// 					title: res.msg,
			// 				});
			// 			}
			// 		},
			// 		rej => {}
			// 	);
			// },
			// 客服
			getIsAddKf() {
				// {videoId: this.videoId,qwUserId: this.qwUserId,corpId: this.corpId}
				getIsAddKf(this.urlOption).then(res => {
						if (res.code == 200) {
							this.isAddKf = 1
							this.qwCode = true
							//this.getH5CourseVideoDetails()
						} else if (res.code == 401) {
							this.isAddKf = 0
							this.goLogin();
						} else {
							this.qwCode = false
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					},
					err => {}
				);
			},
			clickTabs(item) {},
			formatNumber(num) {
				if (typeof num !== 'number') {
					num = Number(num) || 0;
				}
				if (num < 10000) {
					return num.toString();
				}
				// 处理万以上的数字
				const wan = num / 10000;
				if (wan < 10) {
					// 1万-10万之间，保留2位小数
					const rounded = Math.round(wan * 100) / 100;
					return rounded.toFixed(2).replace(/\.?0+$/, '') + 'w';
				} else if (wan < 10000) {
					// 10万-1亿之间，保留1位小数
					const rounded = Math.round(wan * 10) / 10;
					return rounded.toFixed(1).replace(/\.0$/, '') + 'w';
				} else {
					// 1亿以上，转换为亿单位
					const yi = wan / 10000;
					const rounded = Math.round(yi * 100) / 100;
					return rounded.toFixed(2).replace(/\.?0+$/, '') + '亿';
				}
			},
			// 重置所有状态
			resetAllStates() {
				this.liveUserCalled = false;
				if (this.$refs.chat && this.$refs.chat.clearMessages) {
					this.$refs.chat.clearMessages();
				}
				this.liveViewersData = [];
				this.liveViewers = [];
				this.liveItem = [];

				// 重置 WebSocket（委托 liveSocket）
				this.liveSocket?.resetState();
				this.socketConnected = false;
				this.isNetworkAvailable = true;
				this.networkType = 'unknown';
				this.lastPerformanceCheck = 0;
			},

			// 获取WebSocket性能统计
			getWebSocketPerformanceStats() {
				const stats = this.liveSocket?.getStats() ?? {};
				return {
					...stats,
					networkType: this.networkType
				};
			},

			// 定期检查性能并输出统计信息
			performanceCheck() {
				const now = Date.now();
				// 每5分钟输出一次性能统计
				if (now - this.lastPerformanceCheck > 300000) { // 5分钟
					const stats = this.getWebSocketPerformanceStats();
					console.log('WebSocket性能统计:', stats);
					this.lastPerformanceCheck = now;
					// 如果错误率过高，记录警告
					if (stats.errorRate > 10) {
						console.warn(`WebSocket错误率过高: ${stats.errorRate}%`);
					}
					// 如果连接延迟过高，记录警告
					if (stats.connectionLatency > 5000) {
						console.warn(`WebSocket连接延迟过高: ${stats.connectionLatency}ms`);
					}
				}
			},
			// 定期清理视频缓存
			startVideoCacheCleanup() {
				if (this.videoCleanupTimer) {
					clearInterval(this.videoCleanupTimer);
				}
				// 每30秒清理一次视频缓存
				this.videoCleanupTimer = setInterval(() => {
					this.cleanupVideoCache();
				}, 30000);
			},
			// 清理视频缓存
			cleanupVideoCache() {
				if (!this.liveItem || !this.liveId) return;

				// 只对录播视频进行清理
				if (this.liveItem.liveType === 2 && this.liveItem.videoUrl) {
					this.reloadVideoPlayer();
				}
			},
			// 重新加载视频播放器
			reloadVideoPlayer() {
				const videoId = `myVideo_${this.liveId}`;
				const videoContext = uni.createVideoContext(videoId, this);

				if (videoContext) {
					const currentTime = this.videoCurrentTime;
					// 暂停视频
					videoContext.pause();
					// 延迟重新加载
					setTimeout(() => {
						// 重新设置视频源，强制清理缓存
						this.$set(this.liveItem, 'videoUrl', this.liveItem.videoUrl + '&t=' + Date.now());

						// 恢复播放位置
						setTimeout(() => {
							if (videoContext.seek) {
								videoContext.seek(currentTime);
							}
							videoContext.play();
						}, 500);
					}, 100);
				}
			},
			// 启动内存监控
			startMemoryMonitoring() {
				if (this.memoryMonitorTimer) {
					clearInterval(this.memoryMonitorTimer);
				}
				this.memoryMonitorTimer = setInterval(() => {
					this.checkMemoryUsage();
				}, 15000); // 每15秒检查一次
			},


			// 检查内存使用情况
			checkMemoryUsage() {
				try {
					// 检查定时器数量
					const timerCount = this.getActiveTimerCount();
					if (timerCount > 10) {
						console.warn(`检测到过多定时器: ${timerCount}个，可能存在内存泄漏`);
						this.cleanupUnusedTimers();
					}

					// 检查消息队列长度
					if (this.messageQueue && this.messageQueue.length > 100) {
						console.warn(`消息队列过长: ${this.messageQueue.length}条，清理旧消息`);
						this.messageQueue = this.messageQueue.slice(-50); // 只保留最新50条
					}

					// 检查用户颜色缓存
		
					// 定期触发垃圾回收
					if (Date.now() - this.lastPerformanceCheck > 60000) { // 每分钟一次
						this.triggerGarbageCollection();
						this.lastPerformanceCheck = Date.now();
					}
				} catch (error) {
					console.error('内存检查失败:', error);
				}
			},



			// 强制内存清理
			forceMemoryCleanup() {
				console.log('执行强制内存清理');

				// 1. 清理视频播放器
				this.cleanupVideoPlayer();

				// 2. 清理大数据
				this.clearBigData();

				// 3. 强制垃圾回收（在支持的环境下）
				this.triggerGarbageCollection();
			},
			// 清理视频播放器
			cleanupVideoPlayer() {
				const videoId = `myVideo_${this.liveId}`;
				const videoContext = uni.createVideoContext(videoId, this);
				if (videoContext) {
					// 停止播放
					videoContext.stop();
					// 重置视频源
					setTimeout(() => {
						this.$set(this.liveItem, 'videoUrl', '');
						setTimeout(() => {
							this.$set(this.liveItem, 'videoUrl', this.getFreshVideoUrl());
							this.playVideo();
						}, 500);
					}, 100);
				}
			},
			// 获取带时间戳的新视频URL
			getFreshVideoUrl() {
				if (!this.liveItem.originalVideoUrl) {
					this.liveItem.originalVideoUrl = this.liveItem.videoUrl;
				}
				// 添加时间戳参数，避免缓存
				const separator = this.liveItem.originalVideoUrl.includes('?') ? '&' : '?';
				return this.liveItem.originalVideoUrl + separator + 't=' + Date.now();
			},
			// 清理大数据
			clearBigData() {
				if (this.$refs.chat && this.$refs.chat.trimTalklist) {
					this.$refs.chat.trimTalklist(50);
				}
				// 清理虚拟数据
				if (this.liveViewers.length > 100) {
					this.liveViewers = this.liveViewers.slice(-100);
				}
				// 强制垃圾回收（如果支持）
				if (typeof gc === 'function') {
					gc();
				}
			},


			// 触发垃圾回收（在支持的环境下）
			triggerGarbageCollection() {
				if (wx && wx.triggerGC) {
					wx.triggerGC();
				}
			},

			// 停止内存监控
			stopMemoryMonitor() {
				if (this.memoryMonitorTimer) {
					clearInterval(this.memoryMonitorTimer);
					this.memoryMonitorTimer = null;
				}
			},
			// 获取活跃定时器数量
			getActiveTimerCount() {
				const timers = [
					'trafficTimer', 'liveViewDataTimer',
					'scrollTimer', 'searchTimer', 'purchasePromptTimer',
					'welcomeTimer', 'redTimer', 'liveStartTimer', 'lotteryTimer',
					'memoryMonitorTimer', 'networkStatusTimer',
					'videoCleanupTimer', 'countdownTimer', 'watchTimeTimer', 'pointsRetryTimer'
				];
				return timers.filter(timer => this[timer] !== null).length;
			},

			// 清理未使用的定时器
			cleanupUnusedTimers() {
				// 检查并清理可能泄漏的定时器
				const timers = [
					'trafficTimer', 'liveViewDataTimer',
					'scrollTimer', 'searchTimer', 'purchasePromptTimer',
					'welcomeTimer', 'redTimer', 'liveStartTimer', 'lotteryTimer', 'noticeTimer',
					'networkStatusTimer',
					'videoCleanupTimer', 'countdownTimer', 'watchTimeTimer', 'memoryMonitorTimer',
					'pointsRetryTimer'
				];

				timers.forEach(timerName => {
					if (this[timerName] && typeof this[timerName] === 'number') {
						// 检查定时器是否还在运行
						if (timerName.includes('Interval') || timerName.includes('Timer')) {
							clearInterval(this[timerName]);
						} else {
							clearTimeout(this[timerName]);
						}
						this[timerName] = null;
						console.log(`清理了可能泄漏的定时器: ${timerName}`);
					}
				});
			},

			// 增强的定时器清理方法
			clearAllTimersEnhanced() {
				// 先调用原有的清理方法
				this.clearAllTimers();

				// 额外清理新增的定时器
				if (this.networkRetryTimer) {
					clearTimeout(this.networkRetryTimer);
					this.networkRetryTimer = null;
				}

				// 停止内存监控
				this.stopMemoryMonitor();

				this.shownEntryUsers.clear();

				this.lastPerformanceCheck = 0;

				console.log('增强清理完成：所有定时器和缓存已清理');
			},

			goMiniProgram() {
				uni.navigateTo({
					url: '/pages_user/user/integralGoodsList'
				})
			},
			// 阻止双击事件
			preventDoubleClick(e) {
				e.preventDefault();
				e.stopPropagation();
				return false;
			},

			// 清理所有定时器和内存
			clearAllTimers() {
				// 清理所有定时器
				const timers = [
					'scrollTimer',
					'liveViewDataTimer',
					'redTimer',
					'liveStartTimer',
					'lotteryTimer',
					'noticeTimer',
					'welcomeTimer',
					'trafficInterval',
					'lookTimer',
					'trafficTimer',
					'intervalId',
					'reconnectTimer',
					'searchTimer',
					'purchasePromptTimer',
					'heartBeatTimer',
					'pingTimeoutTimer',
					'videoCleanupTimer',
					'countdownTimer',
					'watchTimeTimer',
					'memoryMonitorTimer',
					'networkStatusTimer',
					'networkRetryTimer',
					'pointsRetryTimer'
				];
				timers.forEach((timer) => {
					if (this[timer]) {
						if (timer.includes('Interval') || timer.includes('Timer')) {
							clearInterval(this[timer]);
						} else {
							clearTimeout(this[timer]);
						}
						this[timer] = null;
					}
				});

				// 重置相关状态
				this.stayTime = 0;
				this.startTime = 0;
				this.totalTraffic = 0;
			},
			//课程计算流量
			// startTrafficCalculation() {
			// 	if (this.trafficTimer) {
			// 		clearInterval(this.trafficTimer);
			// 		this.trafficTimer = null;
			// 	}

			// 	this.startTime = Date.now();
			// 	var that = this;

			// 	// 计算码率
			// 	let bitrate = this.calculateBitrate();

			// 	this.trafficTimer = setInterval(() => {
			// 		that.calculateTraffic(bitrate);
			// 	}, 10000); // 每10秒计算一次
			// },
			//课程计算流量
			startTrafficCalculation() {
				// 检查必要数据
				if (!this.liveItem || !this.liveItem.videoFileSize) {
					console.warn('视频文件大小数据不完整，无法启动流量计算');
					return;
				}

				// 检查视频总时长
				const totalDuration = this.liveItem.videoDuration || this.liveItem.duration;
				if (!totalDuration) {
					console.warn('视频总时长数据不完整，无法启动流量计算');
					return;
				}

                // 如果流量计算已经在进行中，且 trafficStartTime 已存在，不重复启动
				// 避免重复累计流量
				if (this.trafficTimer && this.trafficStartTime > 0) {
					console.log('流量计算已在进行中，跳过重复启动');
					return;
				}
				// 清除已有定时器
				if (this.trafficTimer) {
					clearInterval(this.trafficTimer);
					this.trafficTimer = null;
				}

				// 如果之前有流量计算，先提交当前流量数据，避免丢失
				if (this.trafficStartTime > 0 && this.videoLoaded) {
					const watchDuration = Math.floor((this.getServerTimeNow() - this.trafficStartTime) / 1000);
					if (watchDuration > 0) {
						this.submitTraffic(watchDuration);
					}
				}

				// 重置总流量
				this.totalTraffic = 0;
				// 记录流量计算开始时间
				this.trafficStartTime = this.getServerTimeNow();
				var that = this;
				// 立即提交一次10s流量（模拟10秒观看）
				setTimeout(() => {
					that.submitTraffic(10);
				}, 100); // 延迟100ms确保数据已准备好

				// 启动定时器，每10秒计算并提交一次流量
				this.trafficTimer = setInterval(() => {
					that.calculateAndSubmitTraffic();
				}, 10000); // 每10秒计算一次
			},
			// 计算流量
			// calculateTraffic(bitrate) {
			// 	const currentTime = Date.now();
			// 	const duration = (currentTime - this.startTime) / 1000; // 持续时间（秒）
			// 	// 流量 = 码率 × 时间
			// 	// 码率单位: bps, 时间单位: 秒, 流量单位: 比特
			// 	const trafficBits = bitrate * duration;
			// 	// 转换为字节
			// 	this.totalTraffic = trafficBits / 8;
			// 	this.getLiveInternetTraffic();
			// },
			// calculateBitrate() {
			// 	// 如果接口返回了视频文件大小和时长，使用这些数据计算码率
			// 	if (this.liveItem.videoFileSize && this.liveItem.videoDuration) {
			// 		// 码率 = 文件大小(字节) / 时长(秒) × 8 (转换为bps) × 5
			// 		const calculatedBitrate = (this.liveItem.videoFileSize / this.liveItem.videoDuration) * 8 * 5;
			// 		console.log(
			// 			`使用接口数据计算码率: ${calculatedBitrate} bps (文件大小: ${this.liveItem.videoFileSize} 字节, 时长: ${this.liveItem.videoDuration} 秒)`
			// 		);
			// 		return calculatedBitrate;
			// 	} else {
			// 		// 如果任一字段为空，使用默认码率 1500 bps
			// 		console.log('接口数据不完整，使用默认码率: 1500 bps');
			// 		return 1500;
			// 	}
			// },
			// calculateTraffic(bitrate) {
			// 	const currentTime = Date.now();
			// 	const duration = (currentTime - this.startTime) / 1000; // 持续时间（秒）

			// 	// 流量 = 码率 × 时间
			// 	// 码率单位: bps, 时间单位: 秒, 流量单位: 比特
			// 	const trafficBits = bitrate * duration;

			// 	// 转换为字节
			// 	this.totalTraffic = trafficBits / 8;

			// 	// 调用流量上报接口
			// 	this.getLiveInternetTraffic();
			// },
			// 计算并提交流量
			calculateAndSubmitTraffic() {
				if (!this.liveItem || !this.liveItem.videoFileSize) {
					const totalDuration = this.liveItem.videoDuration || this.liveItem.duration;
					if (!totalDuration) {
						return;
					}
				}
				// 计算用户观看视频时长（秒）
				//const watchDuration = Math.floor((Date.now() - this.trafficStartTime) / 1000);
				const watchDuration = Math.floor((this.getServerTimeNow() - this.trafficStartTime) / 1000);
				// 获取视频总时长（秒）
				const totalDuration = this.liveItem.videoDuration || this.liveItem.duration || 0;

				// 获取视频文件大小（字节）
				const videoFileSize = this.liveItem.videoFileSize || 0;

				if (totalDuration <= 0 || videoFileSize <= 0) {
					console.warn('视频总时长或文件大小无效，无法计算流量');
					return;
				}

				// 流量计算方法：用户观看视频时长/视频总时长*视频文件大小
				const calculatedTraffic = (watchDuration / totalDuration) * videoFileSize;

				// 更新总流量
				this.totalTraffic = calculatedTraffic;

				// 提交流量数据
				this.submitTraffic(watchDuration);
			},
			// 提交流量数据到后端
			submitTraffic(watchDuration) {
				if (!this.liveId || !this.userInfo || !this.userInfo.userId) {
					return;
				}
				const now = Date.now();
				if (now - this.lastTrafficSubmitAt < 8000) {
					return;
				}
				this.lastTrafficSubmitAt = now;

				// 计算当前观看时长对应的流量
				const totalDuration = this.liveItem.videoDuration || this.liveItem.duration || 0;
				const videoFileSize = this.liveItem.videoFileSize || 0;

				if (totalDuration <= 0 || videoFileSize <= 0) {
					console.warn('视频总时长或文件大小无效，无法提交流量', {
						totalDuration,
						videoFileSize,
						videoDuration: this.liveItem.videoDuration,
						duration: this.liveItem.duration
					});
					return;
				}

				// 流量 = 用户观看视频时长/视频总时长*视频文件大小
				const traffic = (watchDuration / totalDuration) * videoFileSize;

				const param = {
					userId: this.userInfo.userId || '',
					liveId: this.liveId || '',
					uuId: dayjs().format('YYYYMMDD') + this.uuId,
					internetTraffic: Math.round(traffic), // 四舍五入到整数
					watchDuration: watchDuration, // 观看时长（秒）
					totalDuration: totalDuration, // 视频总时长（秒）
					videoFileSize: videoFileSize // 视频文件大小（字节）
				};

				//console.log('提交流量数据:', param);
				liveInternetTraffic(param).catch(err => {
					console.error('流量数据提交失败:', err);
				});
			},
			startTimer() {
				this.startTime = Date.now();
				this.lookTimer = setInterval(() => {
					this.stayTime = Math.floor((Date.now() - this.startTime) / 1000);
				}, 1000);
			},

			//课程、录播缓冲
			getLiveInternetTraffic() {
				if (!this.liveId) return;
				const currentTime = (this.stayTime / this.liveItem.duration) * 100;
				const param = {
					userId: this.userInfo.userId || '',
					liveId: this.liveId || '',
					uuId: dayjs().format('YYYYMMDD') + this.uuId,
					internetTraffic: this.totalTraffic
				};
				liveInternetTraffic(param);
			},
			// 回放、预告缓冲
			getInternetTraffic() {
				if (!this.liveId || !this.liveId || !this.userInfo.userId || !this.uuId) return;
				const currentTime = (this.stayTime / this.liveItem.duration) * 100;
				const param = {
					videoType: this.liveItem.videoType,
					videoId: this.liveItem.videoId,
					userId: this.userInfo.userId,
					liveId: this.liveId,
					uuId: dayjs().format('YYYYMMDD') + this.uuId,
					duration: this.liveItem.duration,
					bufferRate: currentTime
				};
				if (this.liveItem.status == 1) {
					param.videoType = this.liveItem.previewVideoType || '';
					param.videoId = this.liveItem.previewVideoId || '';
				}
				if (this.liveItem.liveType == 1) {
					param.bufferRate = this.totalTraffic;
				}
				//internetTraffic(param);
			},
			// 启动内存监控
			startMemoryMonitor() {
				// 清理之前的监控
				if (this.memoryMonitorTimer) {
					clearInterval(this.memoryMonitorTimer);
				}
				// 每5分钟检查一次内存使用情况
				this.memoryMonitorTimer = setInterval(() => {
					this.checkAndCleanMemory();
				}, 5 * 60 * 1000); // 5分钟
			},

			// 检查并清理内存
			checkAndCleanMemory() {
				try {
					// 清理过多的聊天消息
					if (this.$refs.chat && this.$refs.chat.trimTalklist) {
						this.$refs.chat.trimTalklist(20);
					}

					// 清理用户颜色缓存（保留最近的50个）
							// 清理已显示用户集合（保留最近的100个）
					if (this.shownEntryUsers && this.shownEntryUsers.size > 100) {
						const array = Array.from(this.shownEntryUsers);
						this.shownEntryUsers.clear();
						array.slice(-100).forEach((id) => this.shownEntryUsers.add(id));
					}

					console.log('内存清理完成——————————————————————',this.shownEntryUsers);
				} catch (error) {
					console.error('内存清理失败:', error);
				}
			},
			// 恢复页面活动
			async resumePageActivity() {
				if (!this.liveId || !this.isOnload) {
					if (!this.isSocketAvailable()) {
						this.initSocket();
					}
					return;
				}
				await this.getliving(this.liveId, { skipSecondary: true });
				this.startTimeTimer(this.liveItem);
				if (!this.isSocketAvailable()) {
					this.initSocket();
				}
			},
			async getUserInfo(refresh = false) {
				try {
					const res = await fetchLiveUserInfo(refresh);
					if (res.code == 200) {
						this.userInfo = res.user;
						this.isNow = dayjs(this.userInfo.updateTime).isSame(dayjs(), 'day');
					} else {
						uni.showToast({
							icon: 'none',
							title: '请求失败'
						});
					}
				} catch (e) {
					console.error('getUserInfo failed', e);
				}
			},

			//订阅消息
			handleAgreement() {
				const templateId = this.templateId;
				if (this.hasSubscribed) return;
				uni.requestSubscribeMessage({
					tmplIds: [templateId],
					success: (res) => {
						if (res[templateId] === 'accept') {
							uni.showToast({
								title: '订阅成功，开播将提醒您',
								icon: 'none',
								duration: 2500 // 成功提示延长到2.5秒
							});
							// 订阅成功时
							this.hasSubscribed = true;
							uni.setStorageSync('subscribe_status_' + this.liveId, true);
							this.callSendMessageApi();
						} else if (res[templateId] === 'reject') {
							uni.showToast({
								title: '您已拒绝订阅，将无法收到提醒',
								icon: 'none',
								duration: 2500 // 成功提示延长到2.5秒
							});
						} else if (res[templateId] === 'ban') {
							uni.showToast({
								title: '您已关闭所有订阅权限，请在设置中开启',
								icon: 'none',
								duration: 2500 // 成功提示延长到2.5秒
							});
						}
					},
					fail: (err) => {
						console.error('订阅消息失败', err);
						uni.showToast({
							title: '订阅失败，请重试',
							icon: 'none',
							duration: 2500 // 成功提示延长到2.5秒
						});
					}
				});
			},
			async callSendMessageApi() {
				if (!this.userInfo.userId) return;
				const templateData = {
					liveId: this.liveId,
					userId: this.userInfo.userId,
					templateId: this.templateId, // 模板ID
					maOpenId: this.userInfo.maOpenId,
					appId: this.appid,
					data: {
						thing4: this.liveItem.liveName,
						time2: this.liveItem.startTime,
						date7: this.liveItem.startTime
					}
				};
				subNotifyLive(templateData).then(
					(res) => {
						if (res.code == 200) {
							this.isAgreement = true;
							uni.setStorageSync('isAgreement', true);
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					},
					(rej) => {}
				);
			},


			initNetworkStatusListener() {
				uni.getNetworkType({
					success: (res) => {
						this.networkType = res.networkType;
						this.isNetworkAvailable = res.networkType !== 'none';
					}
				});

				uni.onNetworkStatusChange((res) => {
					const oldNetworkAvailable = this.isNetworkAvailable;
					this.networkType = res.networkType;
					this.isNetworkAvailable = res.isConnected;

					if (!oldNetworkAvailable && res.isConnected) {
						setTimeout(() => {
							if (!this.isSocketAvailable()) {
								this.initSocket();
							}
						}, 1000);
					}

					if (res.isConnected) {
						this.adjustHeartBeatForNetworkType(res.networkType);
					}
				});
			},

			adjustHeartBeatForNetworkType(networkType) {
				this.liveSocket?.adjustHeartBeatForNetworkType(networkType);
			},
			//输入框
			hideGoodsCardForKeyboard() {
				if (this.isShowGoods) {
					this.goodsCardHiddenByKeyboard = true;
					this.isShowGoods = false;
				}
			},
			restoreGoodsCardAfterKeyboard() {
				if (!this.goodsCardHiddenByKeyboard) return;
				this.goodsCardHiddenByKeyboard = false;
				this.isShowGoods = true;
			},
			onMoreClick() {
				this.onShopOpenMore();
			},
			getTimeDifferenceInSeconds(createTimeStr, useServerTime = false) {
				if (!createTimeStr) return;
				// const createTime = new Date(createTimeStr.replace(/-/g, '/'));
				// 使用服务器时间或本地时间
				const now = useServerTime ? Number(this.getServerTimeNow()) : Date.now();
				const timeDiffMs = now - createTimeStr;
				const timeDiffSeconds = Math.floor(timeDiffMs / 1000);
				return Math.max(0, timeDiffSeconds);
			},
			// 录播时间点
			onVideoMetaLoaded(e) {
				console.log("录播时间点", e)
				const width = e.detail.width;
				const height = e.detail.height;
				const res = uni.getSystemInfoSync();
				const winH = res.windowHeight;
				const winW = res.windowWidth;
				//横屏
				const wW = (winW / winH) * 100;
				//竖屏
				if (height > width) {
					this.isHeight = true
				}
				const wH = (winH / winW) * 100;
				this.videoProgressKey = `videoProgress_${this.liveId}`;
				this.setVideoProgress();

				// 视频加载成功后，启动流量计算
				if (!this.videoLoaded) {
					this.videoLoaded = true;
					// 初始化视频更新时间
					this.lastVideoUpdateTime = Date.now();
					// 延迟一下确保数据已加载
					setTimeout(() => {
						// 只有在流量计算未启动时才启动，避免重复累计
						if (!this.trafficTimer || this.trafficStartTime === 0) {
							this.startTrafficCalculation();
						}
					}, 500);
				}
			},
			setVideoProgress() {
				// 只有录播和回放需要设置进度
				if (this.liveItem.liveType !== 2 && this.liveItem.liveType !== 3) {
					return;
				}
				let currentTime = 0;
				if (this.liveItem.liveType === 2) {
					// 录播：计算当前时间与开始时间的差值，对视频总时长取模
					const diff = this.getTimeDifferenceInSeconds(this.liveItem.serviceStartTime, true);
					if (diff > this.liveItem.duration) {
						const storedProgress = uni.getStorageSync(this.videoProgressKey) || 0;
						currentTime = storedProgress >= this.liveItem.duration ? 0 : storedProgress || 0;
						this.isPlayback = true;
						this.hasPlayback = true;
						if (this.isPlayback) {
							const hasWatchedKey = `hasWatchedReplay_${this.liveId}`;
							const hasWatched = uni.getStorageSync(hasWatchedKey);

							if (!hasWatched) {
								// 首次观看回放，从0开始
								currentTime = 0;
								uni.setStorageSync(hasWatchedKey, true);
							} else {
								// 非首次观看，从存储中获取进度
								const storedProgress = uni.getStorageSync(this.videoProgressKey);
								currentTime = storedProgress || 0;
							}
						}
					} else {
						currentTime = diff % this.liveItem.duration;
					}
				}
				const videoId = `myVideo_${this.liveId}`;
				const videoContext = uni.createVideoContext(videoId, this);
				if (videoContext) {
					videoContext.seek(currentTime);
				}
			},
			onVideoWaiting(e) {
				// console.log('视频等待加载', e);
				if (this.liveItem.liveType == 2) {
					// 录播：只有在流量计算未启动时才启动，避免重复累计
					if (!this.trafficTimer || this.trafficStartTime === 0) {
						this.startTrafficCalculation();
					}
				} else {
					let that = this;
					if (this.trafficInterval) {
						clearInterval(this.trafficInterval);
						this.trafficInterval = null;
					}
					this.trafficInterval = setInterval(function() {
						that.getInternetTraffic();
					}, 10000);
				}
				// 记录等待开始时间
				if (!this.waitingStartTime) {
					this.waitingStartTime = Date.now();
				}

				// 检测是否真的出现黑屏或卡顿（等待超过5秒且视频时间没有更新）
				if (!this.waitingTimer) {
					this.waitingTimer = setTimeout(() => {
						const waitingDuration = Date.now() - this.waitingStartTime;
						const timeSinceLastUpdate = Date.now() - this.lastVideoUpdateTime;
						const now = Date.now();
						const timeSinceLastToast = now - this.lastNetworkUnstableToastTime;

						// 只有在等待超过5秒，且视频时间超过3秒没有更新时，才认为是真正的卡顿/黑屏
						// 并且距离上次提示至少30秒，避免频繁弹出（特别是对于短时长的预告视频）
						if (waitingDuration >= 5000 && timeSinceLastUpdate >= 3000) {
							// 防抖：30秒内只弹出一次提示
							if (timeSinceLastToast >= 30000 || this.lastNetworkUnstableToastTime === 0) {
								this.$refs.customToast.show({
									title: '当前您的网络不稳定',
									duration: 2000
								});
								this.lastNetworkUnstableToastTime = now;
							}
						}
					}, 5000); // 延迟5秒检测
				}
			},

			// 视频时间更新
			onVideoTimeUpdate(e) {
				// 获取当前播放时间
				this.videoCurrentTime = e.detail.currentTime;
				// 更新视频最后更新时间（用于检测是否卡顿）
				this.lastVideoUpdateTime = Date.now();

				// 如果视频在更新，说明没有卡顿，清除等待状态
				if (this.waitingStartTime && this.lastVideoUpdateTime - this.waitingStartTime < 1000) {
					// 视频在1秒内恢复了，清除等待定时器
					if (this.waitingTimer) {
						clearTimeout(this.waitingTimer);
						this.waitingTimer = null;
					}
					this.waitingStartTime = 0;
				}
				// 每隔1秒保存一次进度（避免频繁存储）
				if (Math.floor(this.videoCurrentTime) % 1 === 0) {
					this.saveVideoProgress();
				}
				// 使用服务器时间判断课程是否结束
				const diff = this.getTimeDifferenceInSeconds(this.liveItem.serviceStartTime, true)
				if (diff >= this.liveItem.duration) {
					if (!this.hasPlayback) {
						this.hasPlayback = true;
						this.isPlayback = true;
						this.isEnd = true;
						if (this.videoProgressKey) {
							uni.removeStorageSync(this.videoProgressKey);
						}
						const videoId = `myVideo_${this.liveId}`;
						const videoContext = uni.createVideoContext(videoId, this);
						if (videoContext) {
							videoContext.seek(0);
						}
						this.playVideo();
					}
				}

				// 观看时间 ljx
				let currentTime = ''
				const storedProgress = uni.getStorageSync(this.videoProgressKey) || 0;
				currentTime = storedProgress >= this.liveItem.duration ? 0 : storedProgress || 0;
				this.$nextTick(() => {
					const difPlayback = currentTime;
					const totalSeconds = Math.floor(difPlayback);
					const hours = this.padZero(Math.floor(totalSeconds / 3600));
					const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
					const seconds = this.padZero(totalSeconds % 60);
					this.playbackTime = `${hours}:${minutes}:${seconds}`;
				});
			},

			// 视频暂停
			onVideoPause(e) {
				// 暂停时保存进度
				this.saveVideoProgress();

				// 录播视频自动恢复播放（避免用户误操作导致暂停）
				if (this.liveItem.liveType === 2 && !this.isManualPause) {
					const videoId = `myVideo_${this.liveId}`;
					const videoContext = uni.createVideoContext(videoId, this);
					if (videoContext) {
						// 延迟播放，避免立即触发导致循环
						setTimeout(() => {
							// 再次检查是否应该播放（防止用户手动暂停）
							if (!this.isManualPause && this.liveItem && this.liveItem.liveType === 2) {
								videoContext.play();
							}
						}, 200);
					}
				}
			},
			// 视频播放
			onVideoPlay(e) {
				//console.log("qxj onVideoPlay");
				// 重置手动暂停标志
				this.isManualPause = false;

				// 清除等待定时器
				if (this.waitingTimer) {
					clearTimeout(this.waitingTimer);
					this.waitingTimer = null;
				}
				this.waitingStartTime = 0;
				this.lastVideoUpdateTime = Date.now(); // 更新最后更新时间
				if (this.liveItem.status == 2) {
					//this.startCountdown();
					// 启动观看时长统计
					//this.startWatchDurationTracking();
				}
				if (this.watchTimeTimer) {
					clearInterval(this.watchTimeTimer);
					this.watchTimeTimer = null;
					this.saveWatchTime();
					console.log("视频开始播放")
				}
			},
			// 保存视频进度
			saveVideoProgress() {
				if (this.videoProgressKey) {
					uni.setStorage({
						key: this.videoProgressKey,
						data: this.videoCurrentTime,
						success: () => {},
						fail: (err) => {
							console.error('保存视频进度失败:', err);
						}
					});
				}
			},

			// 点击红包
			onRed() {
				if (!this.liveId) return;
				if (!this.redInfo?.redId) return;
				if (this.redTimer) {
					clearInterval(this.redTimer);
					this.redTimer = null;
				}
				let data = {
					liveId: this.liveId,
					userId: this.userInfo.userId,
					redId: this.redInfo.redId
				};
				liveRed(data).then((res) => {
						this.isShowRed = false;
						this.redCard = res;
						this.isShowRedCard = true;
					},
					(rej) => {}
				);
			},
			//领取优惠券
			onCoupon() {
				if (!this.couponInfo.couponIssueId) return;
				let data = {
					goodsId: this.couponInfo.goodsId,
					couponIssueId: this.couponInfo.couponIssueId,
					liveId: this.liveId
				};
				coupon(data).then((res) => {
						this.isShowCoupon = false;
						if (res.code == 200) {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					})
					.catch((rej) => {});
			},

			// 我的中奖名单
			getMyLottery() {
				this.winning = true;
				myLottery()
					.then((res) => {
						if (res.code == 200) {
							// console.log("我的中奖名单", res)
							this.prizeAll = res.data.list || {};
						} else {}
					})
					.catch((rej) => {});
			},
			// 抽奖
			onLottery() {
				if (!this.lotteryInfo) return;
				this.isShowLottery = false
				let data = {
					lotteryId: this.lotteryInfo.lotteryId
				};

				liveLottery(data)
					.then((res) => {
						if (res.code == 200) {
							const resData = res.data || {};
							this.lotteryList = Array.isArray(resData) ? resData : [];
							this.lotteryProducts = Array.isArray(resData.products) ? resData.products : [];

							if (resData.duration) {
								this.isShowLotteryPop = true;
							}
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
							this.lotteryList = [];
							this.lotteryProducts = [];
						}
					})
					.catch((rej) => {
						uni.showToast({
							title: '获取抽奖信息失败',
							icon: 'none'
						});
						// 失败时强制重置为数组
						this.lotteryList = [];
						this.lotteryProducts = [];
					});
			},
			// 参与抽奖
			onClaim() {
				let data = {
					liveId: this.liveId,
					lotteryId: this.lotteryInfo.lotteryId
				};
				claim(data).then(
					(res) => {
						if (res.code == 200) {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
							this.isShowLotteryPop = false;
							this.havePrize = true;
							uni.setStorageSync('havePrize', this.havePrize);
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					},
					(rej) => {}
				);
			},
			confirm() {
				this.isShowPrize = false;
				this.havePrize = false;
				uni.setStorageSync('havePrize', this.havePrize);
			},
			// 商品收藏
			onGoodsCollect(item) {
				if (!item || item.length === 0 || !item.goodsId) {
					return;
				}
				collectGoods(item.goodsId).then(
					(res) => {
						if (res.code == 200) {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
							item.isFavorite = !item.isFavorite;
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					},
					(rej) => {}
				);
			},

			onLiveStateChange(e, liveItem) {
				// 可以根据状态码处理不同的课程状态
				const stateCode = e.detail.code;
				if (e.detail.code == -2301 || e.detail.code == -2302) {
					this.playVideo();
				} else if (e.detail.code == 2004) {
					this.calculateTimeDiff(this.liveItem);
					// 课程：只有在流量计算未启动时才启动，避免重复累计
					if (!this.trafficTimer || this.trafficStartTime === 0) {
						this.startTrafficCalculation();
					}
				}
				// 2001: 已经连接服务器
				// 2002: 已经连接服务器,开始拉流
				// 2003: 网络接收到首个视频数据包(IDR)
				// 2004: 视频播放开始
				// 2005: 视频播放进度
				// 2006: 视频播放结束
				// 2007: 视频播放Loading
				// 2008: 解码器启动
				// -2301: 网络断连，且经多次重连抢救无效，更多重试请自行重启播放
				// -2302: 获取加速拉流地址失败
			}, // 课程错误事件
			onLiveError(e, liveItem) {
				this.videoError(e, liveItem);
				console.log('错误');
			},
			//  红包 卡片 抽奖
			applyCurrentActivities(refresh = false) {
				if (!this.liveId) return;
				fetchCurrentActivities(this.liveId, refresh).then(
					(res) => {
						if (res.code === 200) {
							// 提取数据（默认空数组/对象避免报错）
							this.redInfo = (Array.isArray(res.red) ? res.red : [])[0] || {};
							this.lotteryInfo = (Array.isArray(res.lottery) ? res.lottery : [])[0] || {};
							this.goodsCard = res.goods || {};
							this.notice = res.topMsg || {};

							this.isShowGoods = this.goodsCard && this.goodsCard.status == 1;
							this.isShowRed = this.redInfo && this.redInfo.redStatus == 1;
							this.isShowLottery = this.lotteryInfo && this.lotteryInfo.lotteryStatus == 1;

							if (this.notice.msg) {
								this.noticeTimer = setInterval(() => {
									const noticeCountdown = this.handleTime(this.notice.endTime, 0);
									if (!noticeCountdown) {
										this.isShowNotice = false;
										clearInterval(this.noticeTimer);
									} else {
										this.isShowNotice = true
									}
								}, 1000);
							}
							// if(this.notice.msg&&this.notice){
							// 	this.isShowNotice = true
							// }else{
							// 	this.isShowNotice = false
							// }
							if (this.isShowRed) {
								this.redTimer = setInterval(() => {
									const redCountdown = this.handleTime(this.redInfo.updateTime, this
										.redInfo
										.duration);
									if (!redCountdown) {
										this.isShowRed = false;
										clearInterval(this.redTimer);
									}
								}, 1000);
							}
							// 处理抽奖定时器
							if (this.isShowLottery) {
								this.lotteryTimer = setInterval(() => {
									this.countdown = this.handleTime(this.lotteryInfo.updateTime, this
										.lotteryInfo.duration);
								}, 1000);
							}
						} else {
							uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
					},
					(rej) => {}
				);
			},

			// 计算当前时间与 liveItem.startTime 的差值，并更新 totalTime
			calculateTimeDiff(item, type) {
				if (!item.startTime) return;
				// 提取对应场景的时间字符串（课程用startTime，抽奖用updateTime）
				let timeStr = item.startTime;

				// 转换时间格式（适配iOS，将 "-" 替换为 "/"）
				const time = new Date(timeStr.replace(/-/g, '/'));

				if (isNaN(time.getTime())) {
					return;
				}
				const now = new Date();
				let diffMs = Math.max(0, now.getTime() - time.getTime());
				// 转换为 时:分:秒（补零处理）
				const totalSeconds = Math.floor(diffMs / 1000);
				const hours = this.padZero(Math.floor(totalSeconds / 3600));
				const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
				const seconds = this.padZero(totalSeconds % 60);
				this.diffTotalTime = `${hours}:${minutes}:${seconds}`;
				if (type) {
					return `${hours}:${minutes}:${seconds}`;
				}
			},


			// 启动当前课程间的时间差值定时器
			startTimeTimer(item) {
				if (!item) return;
				// 立即计算一次（避免等待1秒才显示）
				const totalTime = this.calculateTimeDiff(item);
				item.timeTimer = setInterval(() => {
					const totalTime = this.calculateTimeDiff(item);
				}, 1000);
			},

			// toggleViewerList() {
			// 	const now = Date.now();
			// 	if (now - this.lastClickTime > this.clickDelay) {
			// 		this.showadd = !this.showadd;
			// 		if (this.showadd) {
			// 			this.getliveUser(false); // 加载第一页观众
			// 		}
			// 		this.lastClickTime = now;
			// 	}
			// },
			// 播放视频
			playVideo() {
				if (!this.liveItem) {
					console.log('liveItem 为空，无法播放视频');
					return;
				}
				try {
					// 使用 $nextTick 确保 DOM 已更新
					this.$nextTick(() => {
						if (this.liveItem.liveType === 1 && this.liveItem.livingUrl && this.liveItem.status == 2) {
							// 课程流处理
							return;
						} else if (this.liveItem.status == 1 && this.liveItem.previewUrl) {
							const videoId = `myVideo_${this.liveId}`;
							this._playVideoWithRetry(videoId, 0);
						} else if (this.liveItem.liveType === 2 && this.liveItem.videoUrl && this.liveItem
							.status == 2) {
							const videoId = `myVideo_${this.liveId}`;
							this._playVideoWithRetry(videoId, 0);
						} else if (this.liveItem.liveType === 3 && this.liveItem.videoUrl && this.liveItem
							.status == 4) {
							const videoId = `myVideo_${this.liveId}`;
							this._playVideoWithRetry(videoId, 0);
						}
					});
				} catch (error) {
					console.error('播放视频失败:', error);
				}
			},
			// 带重试的视频播放方法
			_playVideoWithRetry(videoId, retryCount) {
				if (retryCount >= 3) {
					console.error('视频播放失败，已达到最大重试次数');
					uni.showToast({
						title: '视频加载失败，请稍后重试',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				const videoContext = uni.createVideoContext(videoId, this);
				if (!videoContext) {
					// 如果视频上下文不存在，延迟重试
					setTimeout(() => {
						this._playVideoWithRetry(videoId, retryCount + 1);
					}, 300);
					return;
				}

				// 检查视频元素是否存在（使用 uni-app 的方式）
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select(`#${videoId}`).boundingClientRect((data) => {
						if (!data && retryCount < 2) {
							// 视频元素可能还未渲染，延迟重试
							setTimeout(() => {
								this._playVideoWithRetry(videoId, retryCount + 1);
							}, 500);
							return;
						}

						// 尝试播放视频
						try {
							videoContext.play();
							console.log('视频播放成功');
						} catch (error) {
							console.error('调用 play() 失败:', error);
							// 延迟重试
							setTimeout(() => {
								this._playVideoWithRetry(videoId, retryCount + 1);
							}, 500);
						}
					}).exec();
				});
			},
			pauseVideo() {
				if (!this.liveItem) return;

				try {
					if (this.liveItem.status == 1) {
						const videoId = `myVideo_${this.liveId}`;
						const videoContext = uni.createVideoContext(videoId, this);
						if (videoContext) {
							videoContext.pause();
						}
					} else if (this.liveItem.status == 2) {
						if (this.liveItem.liveType === 1) {
							const livePlayerId = `myLivePlayer_${this.liveId}`;
							const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
							if (livePlayerContext) {
								livePlayerContext.pause();
							}
						} else if (this.liveItem.liveType === 2) {
							const videoId = `myVideo_${this.liveId}`;
							const videoContext = uni.createVideoContext(videoId, this);
							if (videoContext) {
								videoContext.pause();
							}
						}
					}
				} catch (error) {
					console.error('暂停视频失败:', error);
				}
			},
			// 视频错误处理
			videoError(e, liveItem) {
				if (!liveItem || !this.liveId) return;
				// 初始化重试计数
				if (this.videoRetryCounts[liveItem.liveId] === undefined) {
					this.videoRetryCounts[liveItem.liveId] = 0;
				}
				// 限制重试次数
				if (this.videoRetryCounts[liveItem.liveId] >= 3) {
					console.error(`课程间 ${this.liveId} 视频加载失败，停止重试`);
					// 显示错误提示
					uni.showToast({
						title: '视频加载失败，请检查网络',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				this.videoRetryCounts[this.liveId]++;

				// 延迟重试
				setTimeout(() => {
					if (this.liveId === this.liveId) {
						console.log(`第${this.videoRetryCounts[this.liveId]}次重试播放视频`);
						this.playVideo();
					}
				}, 2000);
			},

			// 显示购买提示信息
			showPurchaseMessage() {
				// 清除之前的定时器
				if (this.purchasePromptTimer) {
					clearTimeout(this.purchasePromptTimer);
				}

				// 显示提示
				this.showPurchasePrompt = true;

				// 2秒后自动隐藏
				this.purchasePromptTimer = setTimeout(() => {
					this.showPurchasePrompt = false;
				}, 2000);
			},

			//名字超过省略
			truncateString(str, maxLength) {
				if (typeof str !== 'string' || str.length <= maxLength) {
					return str;
				}
				return str.slice(0, maxLength) + '...'; // 截断后加省略号
			},
			// 跳转页面
			navgetTo(url) {
				uni.navigateTo({
					url: url
				});
			},
			// 查询用户积分领取记录（供外部刷新时调用）
			completionRecords() {
				this.loadCompletionRecords();
			},

			// 修改获取课程信息方法
			async getliving(liveId, options = {}) {
				const { skipSecondary = false, refresh = false } = options;
				if (!liveId) return;
				if (this.isLoadingLiveInfo) {
					console.log('正在加载课程间信息，跳过重复请求');
					return;
				}
				this.isLoadingLiveInfo = true;
				try {
					const res = await fetchLiveRoom(liveId, refresh);
					if (res.code !== 200) {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
						return;
					}
					uni.setNavigationBarTitle({
					    title: res.data.liveName
					  });
					this.liveItem = Object.assign({}, this.liveItem, res.data);
          if(this.liveItem != null && this.liveItem.idDel != null && 1 == this.liveItem.idDel){
            uni.showToast({
              title: '课程间已删除',
              icon: 'none'
            });
            return;
          }
					// 保存服务器时间对应的本地时间，用于计算服务器时间差值
					if (res.serviceTime) {
						this.liveItem._localTimeWhenReceived = Date.now();
						this.$set(this.liveItem, 'serviceTime', res.serviceTime);
					}
					if (res.serviceStartTime) {
						this.$set(this.liveItem, 'serviceStartTime', res.serviceStartTime);
					}
					if (res.wsUrl) {
						this.wsBaseUrl = String(res.wsUrl).split('?')[0];
					}
					if (res.data.globalVisible || res.data.singleVisible) {
						this.myselfFlag = true;
					}
					//this.talklist = Array.isArray((res.data || {}).talklist) ? res.data.talklist : [];
					//this.startTimeTimer(this.liveItem);

					// 清除旧定时器（如预告倒计时）
					if (this.liveStartTimer) {
						clearInterval(this.liveStartTimer);
						this.liveStartTimer = null;
					}
					if (res.data.status == 1) {
						// 课程预告
						this.liveStartTimer = setInterval(async () => {
							this.liveCountdown = this.handleTime(res.data.startTime, 0);
							if (!this.liveCountdown) {
								uni.removeStorageSync('isAgreement');
								await this.getliving(this.liveId);
								clearInterval(this.liveStartTimer);
							}
						}, 1000);
						this.$set(this.liveItem, 'previewUrl', res.data.previewUrl);
						this.$set(this.liveItem, 'livingUrl', ''); // 清空课程流
						this.$set(this.liveItem, 'videoUrl', ''); // 清空回放视频
					} else if (res.data.status == 2) {
						if (res.data.liveType == 1) { // 课程流
							let cTime = Math.floor(Math.random() * 10000) + 1;
							let livingUrl = res.data.flvHlsUrl + '&t=' + cTime;
							console.log('地址在', this.liveItem.livingUrl);
							this.$set(this.liveItem, 'livingUrl', livingUrl);
							this.$set(this.liveItem, 'videoUrl', ''); // 清空回放视频
						} else if (res.data.liveType === 2) {
							// 回放视频   2录播 3课程回放
							// let urlStr = 'https://fs-1319721001.cos.ap-chongqing.myqcloud.com/10%E6%9C%8820%E6%97%A5%20%281%29.m3u8'
							// this.$set(this.liveItem, 'videoUrl', urlStr);
							this.$set(this.liveItem, 'videoUrl', res.data.videoUrl);
							this.$set(this.liveItem, 'livingUrl', '');
						}
					} else if (res.data.status == 4 && res.data.liveType == 3) {
						this.$set(this.liveItem, 'videoUrl', res.data.videoUrl);
						this.$set(this.liveItem, 'livingUrl', '');
					} else {
						// 未开播
						this.$set(this.liveItem, 'livingUrl', '');
						this.$set(this.liveItem, 'videoUrl', '');
					}
					if (this.liveItem.configJson) {
						this.completionRate = JSON.parse(this.liveItem.configJson).completionRate * 0.01
					}
					console.log("查询当前用户当前课程间领取积分的剩余时长", this.liveId)
					if (!skipSecondary) {
						this.loadSecondaryLiveData(refresh);
					}
					this.$set(this.liveItem, 'autoplay', res.data.liveType !== 0);
					this.$set(this.liveItem, 'showType', res.data.showType);
					this.storeId = res.storeId;

					console.log("qxj living", this.liveItem);

					// 使用服务器时间计算时间差，确保设备时间不一致时也能正确判断
					this.diffLiveStartTime = this.calculateLiveTimeDiff(this.liveItem.serviceStartTime, true);
					if (this.diffLiveStartTime < 0) { //预告
						this.isPreview = true;
						this.liveBeginWatchTime = this.getServerTimeNow();
					} else {
						// 课程已开始（基于服务器时间），确保 isPreview 为 false
						this.isPreview = false;
						if (!this.hasLiveEnd) { //没经历过课程结束
							this.liveBeginWatchTime = this.getServerTimeNow();
						}
					}
					// 初始化观看时间统计
					this.initWatchTime();
					const diff = this.calculateLiveTimeDiff(this.liveItem.serviceStartTime, true)
					if (diff >= this.liveItem.duration) {
						// 首播已结束，直接进入回放
						this.hasPlayback = true;
						this.isPlayback = true;
						this.isEnd = true;
						this.playVideo();
						this.resumeWatchDurationTracking();
					} else {
						// 课程还未结束，正常播放
						this.playVideo();
					}
					// 确保在获取课程信息后启动倒计时，使用服务器时间正确判断状态
					this.$nextTick(() => {
						if (this.liveItem.completionPointsEnabled) {
							this.startCountdown();
						}
					});
				} catch (err) {
					console.error('获取课程信息失败:', err);
					uni.showToast({
						title: '获取课程信息失败',
						icon: 'none'
					});
				} finally {
					this.isLoadingLiveInfo = false;
				}
			},
			getPureDecimal(num, precision = 6) {
				const decimalPart = Math.abs(num).toFixed(precision).split('.')[1];
				return decimalPart?.replace(/0+$/, '') || ''; // 移除末尾多余的0
			},
			goBack() {
				// 暂停当前视频
				if (this.liveItem) {
					this.pauseVideo();
				}
				// 关闭WebSocket连接
				this.closeWebSocket(true);
				// 导航返回
				// const pages = getCurrentPages();
				// if (pages.length > 1) {
				// 	uni.navigateBack();
				// } else {
				// 	uni.reLaunch({
				// 		url: '/pages_course/livingList'
				// 	});
				// }
                uni.navigateBack();
				//const pages = getCurrentPages();
				// uni.reLaunch({
				// 	url: '/pages/home/newindex'
				// });
			},
			openLiveQuizSheet() {
				if (!this.liveQuizCanSubmit) {
					return;
				}
				this.liveQuizSheetVisible = true;
			},
			closeLiveQuizSheet() {
				this.liveQuizSheetVisible = false;
			},
			numberToLetter(num) {
				return String.fromCharCode(Number(num) + 65);
			},
			isQuizOptionSelected(opt) {
				if (!opt || opt.key == null) return false;
				if (this.liveQuiz && Number(this.liveQuiz.type) === 2) {
					return this.liveQuizSelectedKeys.indexOf(opt.key) !== -1;
				}
				return this.liveQuizSelectedKey === opt.key;
			},
			selectQuizOption(opt) {
				if (!this.liveQuizCanSubmit || !opt) return;
				if (Number(this.liveQuiz.type) === 2) {
					const k = opt.key;
					const i = this.liveQuizSelectedKeys.indexOf(k);
					if (i >= 0) {
						this.liveQuizSelectedKeys.splice(i, 1);
					} else {
						this.liveQuizSelectedKeys.push(k);
					}
				} else {
					this.liveQuizSelectedKey = opt.key;
				}
			},
			async submitLiveQuizAnswer() {
				if (!this.liveQuizCanSubmit || !this.hasQuizSelection) return;
				const keys = Number(this.liveQuiz.type) === 2
					? [...this.liveQuizSelectedKeys]
					: [this.liveQuizSelectedKey];
				try {
					const res = await submitLiveQuiz({
						liveId: this.liveId,
						relId: this.liveQuiz.relId,
						questionBankId: this.liveQuiz.questionBankId,
						type: this.liveQuiz.type,
						answerKeys: keys
					});
					if (res && res.code === 200) {
						if (res.correct === false) {
							uni.showToast({ title: res.msg || '回答错误', icon: 'none' });
						} else {
							uni.showToast({ title: res.msg || '已提交', icon: 'success' });
							this.liveQuizSheetVisible = false;
						}
					} else {
						uni.showToast({ title: (res && res.msg) || '提交失败', icon: 'none' });
					}
				} catch (e) {
					console.error('submitLiveQuizAnswer', e);
					uni.showToast({ title: '网络异常', icon: 'none' });
				}
			},
			// 点赞
			async onLike() {
				if (!this.liveId) return;
				try {
					const res = await liveDataLike(this.liveId);
					if (res?.like) {
						this.liveViewData.like++; //只更新当前课程间的点赞数
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('点赞失败:', error);
				}
			},

			//课程间点赞、关注、在线人数数据
			getliveViewData(refresh = false) {
				if (!this.liveId) return;

				return fetchLiveViewData(this.liveId, refresh).then((res) => {
					if (res.code == 200) {
						// 强制响应式更新，确保数据实时显示
						this.liveViewData = res;
					}
					return res;
				}).catch((error) => {
					console.error('获取课程间数据失败:', error);
					// 失败时兜底，避免显示异常
					this.liveViewData = {
						like: 0,
						watchCount: 0
					};
					throw error;
				});
			},
			// 30秒刷新一下课程间点赞数
			// startLiveViewDataTimer() {
			// 	// 先清除旧定时器（防止重复创建）
			// 	if (this.liveViewDataTimer) {
			// 		clearInterval(this.liveViewDataTimer);
			// 		this.liveViewDataTimer = null;
			// 	}
			// 	this.getliveViewData();
			// 	this.liveViewDataTimer = setInterval(() => {
			// 		// 安全校验：确保liveItem和liveId存在（避免无效请求）
			// 		if (this.liveId) {
			// 			this.getliveViewData();
			// 		}
			// 	}, 20000);
			// },
			openCart() {
				this.onShopOpenCart();
			},
			closeMore() {
				this.isMore = false;
			},
			closeWin() {
				this.winning = false;
			},
			closeIntegralPopup() {
				this.integral.status = false;
			},
			onPrizeFillAddress() {
				this.navgetTo('/pages_shopping/live/confirmCreateOrder?type=win&productId=' +
					this.getCurrentUserPrizeProductId + '&liveId=' + this.liveId + '&recordId=' +
					this.getCurrentUserPrizeRecordId);
				this.confirm();
			},
			onWinningFillAddress(item) {
				this.navgetTo('/pages_shopping/live/confirmCreateOrder?type=win&productId=' +
					item.productId + '&liveId=' + this.liveId + '&recordId=' + item.id);
				this.winning = false;
			},
			onMoreIntegral() {
				this.navgetTo('/pages_shopping/live/integral?liveId' + this.liveId);
				this.isMore = false;
			},
			onMoreExchange() {
				this.goMiniProgram();
				this.isMore = false;
			},
			onMoreWinningRecord() {
				this.getMyLottery();
				this.isMore = false;
				this.winning = true;
			},
			handleTime(time, duration) {
				let timeStamp;

				if (typeof time === 'number' && time > 0 && time < 9999999999999) {
					timeStamp = time;
				} else if (typeof time === 'string' && time.trim() !== '') {
					// 手动解析 CST 时间字符串
					const match = time.match(
						/^(\w{3}) (\w{3}) (\d{1,2}) (\d{1,2}):(\d{2}):(\d{2}) CST (\d{4})$/
					);

					if (match) {
						const [, day, month, date, hours, minutes, seconds, year] = match;

						// 月份映射
						const monthMap = {
							'Jan': 0,
							'Feb': 1,
							'Mar': 2,
							'Apr': 3,
							'May': 4,
							'Jun': 5,
							'Jul': 6,
							'Aug': 7,
							'Sep': 8,
							'Oct': 9,
							'Nov': 10,
							'Dec': 11
						};

						// 创建日期对象（CST 是 UTC+8，与中国时区一致）
						const jsDate = new Date(
							parseInt(year),
							monthMap[month],
							parseInt(date),
							parseInt(hours),
							parseInt(minutes),
							parseInt(seconds)
						);
						timeStamp = jsDate.getTime();
					} else {
						// 如果不是预期格式，回退到普通解析
						const date = new Date(time);
						if (!isNaN(date.getTime())) {
							timeStamp = date.getTime();
						} else {
							console.error('无效的日期格式:', time);
							return false;
						}
					}
				} else {
					console.error('time参数必须是有效的时间戳（数字）或日期字符串');
					return false;
				}

				const targetTimestamp = timeStamp + duration * 60 * 1000;
				const currentTimestamp = this.getServerTimeNow();
				const timeDiffMs = targetTimestamp - currentTimestamp;

				if (timeDiffMs <= 0) {
					return false;
				}

				const hours = Math.floor(timeDiffMs / (1000 * 60 * 60));
				const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60));
				const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000);

				const formatNum = (num) => num.toString().padStart(2, '0');
				return {
					hours: formatNum(hours),
					minutes: formatNum(minutes),
					seconds: formatNum(seconds)
				};
			},
			// 处理Socket消息
			ensureP2Activity() {
				if (!this.modules.p2Activity) {
					this.modules.p2Activity = true;
				}
			},
			async handleSocketMessage(message) {
				try {
					const parsed = parseWsEnvelope(message?.data ?? message);
					if (!parsed || !parsed.socketMessage) {
						return;
					}
					const { socketMessage, msg: envelopeMsg } = parsed;
					if (['red', 'coupon', 'lottery', 'goods', 'sendTopMsg', 'LotteryDetail'].includes(socketMessage.cmd)) {
						this.ensureP2Activity();
					}
					if (isSuccessEnvelope(parsed)) {
						const messageData = {
							...socketMessage,
							cmd: socketMessage.cmd || '',
							ts: Date.now()
						};
						if (socketMessage.cmd == 'sendMsg' || socketMessage.cmd == 'replyUser') {
							if (this.$refs.chat && this.$refs.chat.shouldAppendSocketMessage(socketMessage)) {
								this.$refs.chat.appendMessage(messageData);
							}
						} else if (socketMessage.cmd == 'red') {
							const redData = parseJsonField(socketMessage.data, {});
							this.redInfo = redData || {};
							this.isShowRed = socketMessage.status === 1;
							if (this.isShowRed) {
								this.redTimer = setInterval(() => {
									const redCountdown = this.handleTime(this
										.redInfo.updateTime, this.redInfo
										.duration);
									if (!redCountdown) {
										this.isShowRed = false;
										clearInterval(this.redTimer);
									}
								}, 1000);
							}
						} else if (socketMessage.cmd == 'goods') {
							const goodsData = parseJsonField(socketMessage.data, {});
							this.goodsCard = goodsData || {};
							if (socketMessage.status == 1) {
								if (this.isFocus || this.isKeyboardShow) {
									this.goodsCardHiddenByKeyboard = true;
									this.isShowGoods = false;
								} else {
									this.isShowGoods = true;
									this.goodsCardHiddenByKeyboard = false;
								}
							} else {
								this.isShowGoods = false;
								this.goodsCardHiddenByKeyboard = false;
							}
						} else if (socketMessage.cmd == 'coupon') {
							const couponData = parseJsonField(socketMessage.data, {});
							this.couponInfo = couponData || {};
							this.isShowCoupon = socketMessage.status === 1;
							if (this.isShowCoupon) {}
						} else if (socketMessage.cmd == 'likeDetail') {
							this.liveViewData.like = parseNumericField(socketMessage.data, 0);
						} else if (socketMessage.cmd == 'lottery') {
							const lotteryData = parseJsonField(socketMessage.data, {});
							this.lotteryInfo = lotteryData || {};
							this.isShowLottery = socketMessage.status === 1;
							if (socketMessage.status != 1) {
								this.isShowLotteryPop = false;
							}
							// 清除已有定时器（无论状态是否为1，先清掉旧的）
							clearInterval(this.lotteryTimer);
							if (this.isShowLottery) {
								this.lotteryTimer = setInterval(() => {
									this.countdown = this.handleTime(this
										.lotteryInfo.updateTime, this
										.lotteryInfo.duration);
									if (!this.countdown) {
										console.log('倒计时', this.countdown);
										this.isShowLottery = false;
										this.isShowLotteryPop = false;
										clearInterval(this.lotteryTimer);
									}
								}, 1000);
							} else {
								this.isShowLottery = false;
							}
						} else if (socketMessage.cmd == 'globalVisible' || socketMessage.cmd == 'singleVisible') {
							//  status = 1的时候，用户消息自可见，其他消息丢失}
							if (socketMessage.status == 1) {
								this.myselfFlag = true;
							} else {
								this.myselfFlag = false;
							}

						} else if (socketMessage.cmd == 'sendPopMsg') {
							this.popMsg = socketMessage.msg
							this.isShowPopMsg = true
						} else if (socketMessage.cmd == 'sendTopMsg') {
							clearInterval(this.noticeTimer);
							const noticeData = parseJsonField(socketMessage.data, {});
							this.notice = noticeData || {};
							this.isShowNotice = true
							if (this.isShowNotice) {
								this.noticeTimer = setInterval(() => {
									const noticeCountdown = this.handleTime(this
										.notice.endTime, 0);
									if (!noticeCountdown) {
										this.isShowNotice = false;
										clearInterval(this.noticeTimer);
									}
								}, 1000);
							}

						} else if (socketMessage.cmd == 'entry') {
							try {
								if (!this.liveUserCalled) {
									this.liveUserCalled = true;
								}
								const userIdToEntry = socketMessage.userId;
								const existingIndex = this.liveViewersData.findIndex((
										item) => item.userId ===
									userIdToEntry);

								if (existingIndex === -1) {
									const liveViewers = {
										userId: socketMessage.userId,
										nickName: socketMessage.nickName,
										avatar: socketMessage.avatar
									};
									this.liveViewersData.push(liveViewers);
									this.liveUserTotal++;
								}

								// 解析用户ID（根据实际接口字段调整，此处假设data含userId）
								const userInfo = parseJsonField(socketMessage.data, {});
								const userId = userInfo.userId || socketMessage
									.userId; // 兼容不同字段
								if (!userId) return; // 无用户ID不处理

								// 仅新用户（未显示过）才触发提示
								// if (!this.shownEntryUsers.has(userId)) {
								// 	this.inAndOut = socketMessage;
								// 	this.showWelcomeMessage = true;
								// 	this.shownEntryUsers.add(userId); // 加入已显示集合
								// 	messageData.msg = '来了'
								// 	this.addToTalkList(messageData);

								// 	// 3秒后隐藏提示（可调整时长）
								// 	if (this.welcomeTimer) clearTimeout(this.welcomeTimer);
								// 	this.welcomeTimer = setTimeout(() => {
								// 		this.showWelcomeMessage = false;
								// 	}, 3000);
								// }
							} catch (err) {
								console.error('解析entry用户数据失败:', err);
							}
						} else if (socketMessage.cmd == 'out') {
							if (this.liveUserTotal > 0) {
								const userIdToRemove = socketMessage.userId;
								const index = this.liveViewersData.findIndex((item) => item
									.userId === userIdToRemove);
								if (index !== -1) {
									this.liveViewersData.splice(index, 1);
									this.liveUserTotal--; // 根据userId删除对应的用户数据
								}
							}
							this.inAndOut = socketMessage;
							this.showWelcomeMessage = true;

							// 3秒后隐藏提示
							if (this.welcomeTimer) clearTimeout(this.welcomeTimer);
							this.welcomeTimer = setTimeout(() => {
								this.showWelcomeMessage = false;
							}, 3000);
						} else if (socketMessage.cmd == 'live_start' || socketMessage.cmd == 'live_end') {
							// 开始课程,关闭课程
							if (this.liveStartTimer) {
								clearInterval(this.liveStartTimer);
								this.liveStartTimer = null;
							}
							if (this.redTimer) {
								clearInterval(this.redTimer);
								this.redTimer = null;
							}
							if (socketMessage.cmd == 'live_start') {
								this.liveBeginWatchTime = this.getServerTimeNow();
							}
							if (socketMessage.cmd == 'live_end') {
								this.hasLiveEnd = true;
							}
							//  请求最新课程间数据
							this.$nextTick(() => {
								this.getliving(this.liveId);
							});

						} else if (socketMessage.cmd == 'Integral') {
							this.integral = {
								msg: socketMessage.msg,
								status: true
							};
						}
						// else if (socketMessage.cmd == 'completionPoints') {
						// 	uni.showToast({
						// 		title: socketMessage.msg,
						// 		icon: 'none',
						// 		duration: 3000
						// 	});
						// 	this.completionUnreceived()
						// }
						// else if (socketMessage.cmd == 'completionPoints') {
						// 	// 先显示toast
						// 	uni.showToast({
						// 		title: socketMessage.msg,
						// 		icon: 'none',
						// 		duration: 3000
						// 	});

						// 	// 1秒后关闭弹窗并执行completionUnreceived
						// 	setTimeout(() => {
						// 		// 如果需要手动关闭toast（虽然设置了3秒自动关闭，但这里提前关闭）
						// 		uni.hideToast();

						// 		// 执行completionUnreceived方法
						// 		this.completionUnreceived();
						// 	}, 1000); // 1000毫秒 = 1秒
						// }
						else if (socketMessage.cmd == 'userCount') {
							this.virtualHuman = parseNumericField(socketMessage.data, 0) * 10

						} else if (socketMessage.cmd == 'deleteMsg') {
							if (this.$refs.chat) {
								this.$refs.chat.removeMessageByMsgId(socketMessage.msg);
							}
						} else if (socketMessage.cmd == 'LotteryDetail') {
							try {
								const prizeList = parseJsonField(socketMessage.data, []);
								this.prizeInfo = Array.isArray(prizeList) ? prizeList : [];
							} catch (err) {
								console.error('解析抽奖结果失败:', err);
								this.prizeInfo = [];
							}
							this.isShowPrize = true;
							this.isShowLottery = false;
							this.isShowLotteryPop = false;
						} else if (socketMessage.cmd == 'blockUser') {
							uni.removeStorage({
								key: 'AppToken',
								success: () => {
									uni.reLaunch({
										url: '/pages/auth/login'
									});
								}
							});
						} else if (socketMessage.cmd == 'liveQuizStart') {
							try {
								const raw = parseJsonField(socketMessage.data, {});
								this.liveQuiz = {
									title: raw.title || '',
									type: raw.type != null ? Number(raw.type) : 1,
									options: Array.isArray(raw.options) ? raw.options : [],
									relId: raw.relId != null ? raw.relId : null,
									questionBankId: raw.questionBankId != null ? raw.questionBankId : null
								};
								this.liveQuizSelectedKey = null;
								this.liveQuizSelectedKeys = [];
								this.liveQuizShowEntry = true;
								this.liveQuizCanSubmit = true;
							} catch (err) {
								console.error('liveQuizStart 解析失败:', err);
							}
						} else if (socketMessage.cmd == 'liveQuizClose') {
							this.liveQuizShowEntry = false;
							this.liveQuizSheetVisible = false;
							this.liveQuizCanSubmit = false;
						}
					} else {
						uni.showToast({
							title: envelopeMsg || '操作失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('Socket消息处理失败:', error);
				}
			},

			formatUserNum() {

				let userTotal = 0;
				if (!this.liveUserTotal) {
					this.liveUserTotal = 0;
				}
				if (this.liveUserTotal > 0) {
					userTotal = this.liveUserTotal = 0;
				}
				if (this.liveUserTotal > 10000) {
					userTotal = (this.liveUserTotal / 10000.0).toFixed(1);
					userTotal = userTotal + "万";
				}
				console.log("qxj userTotal", userTotal);
				return userTotal;


			},
		}

	};
</script>
<style scoped lang="scss">
	// 弹窗
	.custom-toast {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 999999;
	}

	.toast-content {
		background-color: rgba(0, 0, 0, 0.7);
		color: white;
		padding: 20rpx 40rpx;
		border-radius: 16rpx;
		max-width: 80vw;
		text-align: center;
		line-height: 1.5;
		font-weight: 500;
		font-size: 32rpx;
	}

	/* 退出全屏按钮 */
	.fullscreen-exit-btn {
		position: fixed;
		bottom: 40rpx;
		left: 82vh;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 100001;
		background: rgba(57, 57, 57, 0.6);
		border-radius: 40rpx;
		padding: 20rpx 24rpx;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.95);
			background: rgba(50, 50, 50, 0.6);
		}

		.exit-fullscreen-icon {
			width: 40rpx;
			height: 40rpx;
			margin-bottom: 10rpx;
		}

		.exit-text {
			color: #ffffff;
			font-size: 22rpx;
			white-space: nowrap;
		}
	}

	.video-container.fullscreen-mode .fullscreen-exit-btn {
		z-index: 999999 !important;
	}

	.fullscreen-mode {
		background-color: #000 !important;
	}

	/* 全屏模式样式 */
	.video-container.fullscreen-mode {
		// width: auto !important;
		// height: auto !important;
		z-index: 99999 !important;
		background-color: #000 !important;
		transform: rotate(90deg) !important;
		transform-origin: center center !important;

		.video-player {
			width: 100vh !important;
			height: 100vw !important;
			// object-fit: contain !important;
		}
	}

	/* 全屏时隐藏其他元素 */
	.video-container.fullscreen-mode~* {
		display: none !important;
	}

	.video-container {
		position: relative;
		bottom: -1px;
		transition: all 0.3s ease;
	}

	.video-container2 {
		position: relative;
		bottom: -1px;
		transition: all 0.3s ease;
	}

	.video-player.fullscreen {
		width: 100vh !important;
		height: 100vw !important;
		object-fit: contain !important;
	}



	/* 全屏按钮样式优化 */
	.custom-controls {
		position: absolute;
		bottom: 24rpx;
		right: 40rpx;
		z-index: 9999;
		background: rgba(0, 0, 0, 0.6);
		border-radius: 50%;
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.95);
			background: rgba(0, 0, 0, 0.8);
		}
	}

	.control-icon {
		width: 46rpx;
		height: 46rpx;
	}



	@media screen and (orientation: landscape) {
		.video-container.horizontal-layout {
			width: 100%;
			height: 100%;
		}

		// .video-player {
		// 	width: 100vh !important;
		// 	height: 100vw !important;
		// }
	}




	// 重置按钮样式
	.button-reset {
		background-color: transparent !important;
		padding: 0 !important;
		line-height: 1 !important;
		margin: 0 !important;
		width: auto !important;
		// font-weight: 500 !important;
		border-radius: none !important;

		&::after {
			border: none !important;
			padding: 0 !important;
			margin: 0 !important;
		}
	}

	// :deep(.u-tabs__wrapper__nav) {
	// 	background-color: #fff !important;
	// }

	.swiper-wrapper {
		/* 深色主题变量 */
		--bottom-color: transparent;
		--bg-color: #242424;
		--text-color: #ffffff;
		--name-color: #8CE7FF;
		--normal-bg: rgba(0, 0, 0, 0.3);
		--input-bg: rgba(0, 0, 0, 0.3);
		--chat-bg: transparent;
		--video-height: 100vh;
		--chat-height: 30vh;
		--pop-bg: #333333;
		--notice-bg: rgba(9, 9, 9, 0.4);
	}

	.swiper-wrapper.horizontal {
		--notice-bg: #fefae8;
		--pop-bg: #ECF5F4;
		/* 默认变量（浅色主题） */
		--bottom-color: #fff;
		--name-color: #666666;
		--bg-color: #ffffff;
		--text-color: #333333;
		--normal-bg: #fff;
		--input-bg: #F5F7FA;
		--chat-bg: #ECF5F4; //对话聊天
		--video-height: 500rpx;
		--chat-height: auto;
	}



	// 主容器
	.swiper-wrapper {
		position: relative;
		width: 100%;
		height: 100vh;
		overflow: hidden;
		/* 应用变量 */
		background: var(--bg-color);
		color: var(--text-color);

		.container {
			width: 100%;
			height: 100%;
			position: relative;
			transition: opacity 0.3s ease;
			transform: translateZ(0);
			will-change: opacity;

			// 预告课程盒子
			.trailer-box {
				width: calc(100% - 80rpx);
				background: var(--pop-bg);
				border-radius: 24rpx;
				position: absolute;
				top: 120rpx;
				left: 50%;
				transform: translateX(-50%);
				display: flex;
				flex-direction: column;
				align-items: center;
				color: var(--text-color);
				padding: 20rpx;
				z-index: 999;
				box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.12);
				transition: box-shadow 0.3s ease;

				.trailer-video {
					width: 100%;
					height: 100%;
					position: absolute;
					z-index: 1;
					border-radius: 20rpx;
				}

				.trailer-placeholder {
					margin-bottom: 40rpx;
					width: 240rpx;
					height: 240rpx;
				}

				.countdown-container {
					margin: 20rpx 0;
					display: flex;
					flex-direction: column;
					align-items: center;

					.live-name {
						font-weight: 600;
						font-size: 36rpx;
					}

					.countdown-display {
						display: flex;
						align-items: center;
						margin: 30rpx 0;

						.countdown-label {
							font-size: 24rpx;
							color: #999999;
						}

						.countdown-separator {
							font-size: 24rpx;
							color: #999999;
						}

						.countdown-unit {
							width: 40rpx;
							height: 40rpx;
							background: #4D4D4D;
							border-radius: 8rpx;
							text-align: center;
							overflow: hidden;
							margin: 0 8rpx;
							font-weight: 500;
							font-size: 28rpx;
							color: #FFFFFF;
							line-height: 40rpx;
						}
					}
				}

				.trailer-actions {
					display: flex;
					justify-content: center;
					align-items: center;

					.action-button {
						width: 280rpx;
						height: 72rpx;
						border-radius: 36rpx;
						line-height: 72rpx;
						text-align: center;
						color: #fff;

						&.reserve-button {
							background: linear-gradient(136deg, #38D97D 0%, #02B176 100%);
						}

						&:not(.reserve-button) {
							background: #F4A007;
						}

						.button-icon {
							width: 32rpx;
							height: 32rpx;
						}
					}
				}

				.no-live-title {
					margin-top: 30rpx;
					font-size: 42rpx;
					font-weight: 500;
				}
			}

			// 新预告课程盒子
			.trailer-box2 {
				width: 100%;
				position: absolute;
				top: 100rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				z-index: 999;
				transition: box-shadow 0.3s ease;
				height: 400rpx;

				.trailer-video {
					width: 100%;
					height: 100%;
					position: absolute;
					z-index: 1;
				}

				.trailer-placeholder {

					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					z-index: -1;
					/* 置于内容下方 */
				}

				.countdown-container {
					padding-top: 15%;
					margin: 20rpx 0;
					display: flex;
					flex-direction: column;
					align-items: center;

					.live-name {
						font-weight: 600;
						font-size: 36rpx;
					}

					.countdown-display {
						display: flex;
						align-items: center;
						margin: 30rpx 0;

						.countdown-label {
							font-size: 32rpx;
							color: rgba(250, 214, 176, 1);
							//color:#fff
						}

						.countdown-separator {
							font-size: 24rpx;
							color: rgba(250, 214, 176, 1);
						}

						.countdown-unit {
							width: 60rpx;
							height: 60rpx;
							background: rgba(255, 246, 214, 1);
							border-radius: 8rpx;
							text-align: center;
							overflow: hidden;
							margin: 0 8rpx;
							font-weight: 500;
							font-size: 36rpx;
							//color: #a30c0b;
							color: rgba(0, 75, 59, 1);
							line-height: 60rpx;
						}
					}
				}

				.trailer-actions {
					display: flex;
					justify-content: center;
					align-items: center;

					.action-button {
						width: 280rpx;
						height: 72rpx;
						border-radius: 36rpx;
						display: flex;
						justify-content: center;
						align-items: center;
						text-align: center;
						//border: 1px solid rgba(151, 151, 151, 1);
						border: 1px solid rgba(255, 246, 214, 1);
						font-size: 36rpx;
						font-weight: bold;

						&.reserve-button {
							color: rgba(0, 110, 80, 1);
							//color: #a30c0b;
							background: linear-gradient(231.51deg, rgba(249, 215, 178, 1) 0%, rgba(255, 255, 191, 1) 47.83%, rgba(255, 250, 229, 1) 65.77%, rgba(248, 214, 178, 1) 100%);

						}

						&:not(.reserve-button) {
							color: rgba(255, 246, 214, 1);
							background: rgba(0, 110, 80, 1);
							// color: #fff;
							//    background: #a30c0b;
						}

						.button-icon {
							width: 32rpx;
							height: 32rpx;
						}
					}
				}

				.no-live-title {
					margin-top: 30rpx;
					font-size: 42rpx;
					font-weight: 500;
				}
			}

			// 主要内容区域
			.content {
				position: relative;
				z-index: 2;
				height: 100%;
				width: 100%;
				top: 0;
				left: 0;
				display: flex;
				flex-direction: column;
				min-height: 0;
				overflow: hidden;


				&.horizontal-content {
					z-index: 999;
				}

				&.trailer-content {
					justify-content: space-between;
				}
			}

			// 侧边（答题入口 + LiveSideActions 共用定位）
			.slide-group {
				position: absolute;
				right: 20rpx;
				top: 60%;
				z-index: 9000;

				.action-button-group {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 50rpx;
				}

				&.live-quiz-entry-wrap {
					top: calc(60% + 240rpx);
				}
			}

			.live-quiz-entry-btn {
				padding: 20rpx 28rpx;
				background: linear-gradient(270deg, #02B176, #04d68f);
				color: #fff;
				font-size: 26rpx;
				border-radius: 40rpx;
				font-weight: 500;
				box-shadow: 0 8rpx 24rpx rgba(2, 177, 118, 0.35);
				white-space: nowrap;
			}
		}
	}
</style>
