<template>
	<view class="video-player-container">
		<!-- 直播状态显示 -->
		<view class="videolist" v-if="liveItem.status == 2" :class="isFullscreen ? 'screen' : ''">
			<view class="video" :class="{'video_row': liveItem.showType == 1,'fullscreen-mode': isFullscreen}">
				<!-- 直播 -->
				<live-player v-if="liveItem.livingUrl && liveItem.liveType == 1" :id="'myLivePlayer_' + liveId"
					:src="liveItem.livingUrl" autoplay mode="live" object-fit="cover" :muted="false"
					orientation="vertical" :enable-play-gesture="false" min-cache="1" max-cache="3"
					@statechange="onLiveStateChange" @error="onLiveError" class="item"></live-player>

				<!-- 录播 -->
				<video v-if="liveItem.videoUrl && liveItem.liveType == 2" :id="`myVideo_${liveId}`" :autoplay="true"
					class="item" :src="liveItem.videoUrl" :controls="false"
					:object-fit="liveItem.showType==2||isFullscreen?'contain':'fill'" :custom-cache="false"
					:enable-progress-gesture="false" vslide-gesture-in-fullscreen="false" :show-center-play-btn="false"
					:http-cache="false" loop @error="videoError" @timeupdate="onVideoTimeUpdate"
					@loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause" @play="onVideoPlay"
					@waiting="onVideoWaiting" :enable-play-gesture="false" :play-strategy="1"
					@dblclick="preventDoubleClick" preload="auto" :enable-stash-buffer="false" :stash-initial-size="0"
					:stash-max-size="0" :stash-time="0" type="application/x-mpegURL"></video>
				<view v-if="liveItem.videoUrl && liveItem.liveType == 2" class="time"
					:class="isFullscreen ? 'look-time' : 'time'">{{ diffTotalTime }}</view>
				<view class="custom-controls" @click.stop="toggleFullscreen">
					<image src="https://cdn.his.cdwjyyh.com/images/full_screen.png" class="control-icon" />
				</view>
				<!-- 全屏返回按钮 - 只在全屏状态下显示 -->
				<view v-if="isFullscreen" class="fullscreen-exit-btn" @click="exitFullscreen">
					<image src="https://cdn.his.cdwjyyh.com/images/half_screen.png" class="exit-fullscreen-icon" />
					<text class="exit-text">退出全屏</text>
				</view>
			</view>

		</view>

		<!-- 直播结束状态 -->
		<view class="videolist" v-if="liveItem.status == 3">
			<view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
				<view class="end">直播已结束</view>
			</view>
		</view>

		<!-- 直播回放状态 -->
		<view class="videolist" v-if="liveItem.status == 4">
			<view class="video" :class="liveItem.showType == 1 ? 'video_row' : ''">
				<!-- 直播回放 -->
				<video v-if="liveItem.videoUrl && liveItem.liveType == 3" :id="`myVideo_${liveId}`" class="item"
					:src="liveItem.videoUrl" :autoplay="true" :controls="true" object-fit="cover" :custom-cache="false"
					:enable-progress-gesture="liveItem.isSpeedAllowed" vslide-gesture-in-fullscreen="true"
					:show-center-play-btn="true" :http-cache="false" loop @error="videoError"
					@timeupdate="onVideoTimeUpdate" @loadedmetadata="onVideoMetaLoaded" @pause="onVideoPause"
					@play="onVideoPlay" :enable-play-gesture="true" preload="auto" @waiting="onVideoWaiting"
					type="application/x-mpegURL"></video>
				<view v-if="liveItem.videoUrl && liveItem.liveType == 3" class="lable">直播回放</view>
			</view>

		</view>
		<view class="trailer-box" v-if="liveItem.status == 1">
			<video v-if="liveItem.previewUrl" :id="`myVideo_${liveId}`" class="trailer-video" :src="liveItem.previewUrl"
				:autoplay="true" :loop="false" object-fit="cover" :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>
			<image v-if="liveItem.status == 1 && !liveItem.previewUrl" class="trailer-placeholder"
				src="https://bjzmky-1323137866.cos.ap-chongqing.myqcloud.com/userapp/images/no_live.png">
			</image>
			<view class="countdown-container" v-if="liveItem.status == 1 && liveCountdown">
				<view class="live-name">{{ 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 class="trailer-actions">
				<button open-type="share" class="button-reset share-button">
					<view class="action-button mr18" @click="handleAgreement">
						<text>分享给好友</text>
					</view>
				</button>

				<view class="action-button reserve-button" @click="handleAgreement">
					<image class="button-icon mr8" src="https://cdn.his.cdwjyyh.com/images/trailer.png"></image>
					<text>预约直播</text>
				</view>
			</view>
		</view>

		<!-- 无直播状态 -->
		<view class="trailer-box" v-if="!liveItem">
			<image class="img" src="https://cdn.his.cdwjyyh.com/images/no_live.png"></image>
			<view class="title">暂无直播</view>
		</view>
	</view>
</template>

<script>
	import {
		generateRandomString
	} from '@/utils/common.js';
	import dayjs from 'dayjs';
	import {
		internetTraffic,
		liveInternetTraffic
	} from '@/api/living.js';
	import {
		getUserInfo
	} from '@/api/user';

	export default {
		name: 'LiveVideoPlayer',
		props: {
			liveItem: {
				type: Object,
				default: () => ({})
			},
			liveId: {
				type: [String, Number],
				default: ''
			},
			userData: {
				type: Object,
				default: () => ({})
			},
			isAgreement: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				isFullscreen: false,
				isVideoRotated: false,
				showNonVideoElementsFlag: true,
				showCustomControls: true,
				videoContext: null,

				// 流量计算相关
				uuId: '',
				totalTraffic: 0,
				bitrate: 800,
				bitrateLive: 1600,

				// 定时器
				trafficTimer: null,
				liveStartTimer: null,
				trafficInterval: null,
				lookTimer: null,

				// 状态数据
				liveCountdown: {},
				diffTotalTime: '',
				videoCurrentTime: 0,
				videoProgressKey: '',
				startTime: 0,
				stayTime: 0,
				// 内部状态跟踪
				hasInitialized: false,
				lastLiveItemStatus: null
			};
		},
		watch: {
			// 深度监听 liveItem 的所有变化
			liveItem: {
				handler(newVal, oldVal) {
					if (newVal && newVal.status === 1 && newVal.startTime) {
						// 如果是预告状态且有开始时间，立即启动倒计时
						this.startLiveCountdown();
					}
				},
				deep: true,
				immediate: true // 立即执行一次
			},

			// 单独监听 status 变化作为备用
			'liveItem.status': {
				handler(newStatus, oldStatus) {
					console.log('状态变化:', oldStatus, '->', newStatus);

					if (newStatus === 1 && this.liveItem.startTime) {
						this.startLiveCountdown();
					} else if (newStatus === 2) {
						this.startTimeTimer(this.liveItem);
					}
				},
				immediate: true
			}
		},
		async created() {
			// 最早的可执行时机
			if (this.liveItem && Object.keys(this.liveItem).length > 0) {
				await this.initializeComponent();
			}
		},
		// async mounted() {
		// 	await this.initializeComponent();
		// },
		computed: {
			shouldShowNonVideoElements() {
				return !this.isFullscreen && this.showNonVideoElementsFlag;
			},

			// 控制是否显示全屏按钮
			shouldShowFullscreenButton() {
				return this.liveItem.showType == 1 && !this.isFullscreen;
			},
		},
		beforeUnmount() {
			this.cleanup();
			// 强制退出全屏
			this.isFullscreen = false;
			this.showCustomControls = true;
		},

		methods: {
			// 退出全屏
			exitFullscreen() {
				console.log('执行退出全屏');

				this.isFullscreen = false;

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

				// 强制页面重排
				this.$nextTick(() => {
					this.$forceUpdate();
					this.$emit('fullscreen-change', this.isFullscreen);
				});
			},

			// 恢复videolist盒子
			restoreVideoList() {
				this.isVideoRotated = false;
				this.isFullscreen = false;
			},

			// 切换全屏
			toggleFullscreen() {
				// console.log('自定义全屏按钮被点击');

				if (this.isFullscreen) {
					// 退出全屏
					this.exitFullscreen();
				} else {
					// 进入全屏
					this.enterFullscreen();
				}

			}, // 进入全屏
			enterFullscreen() {
				console.log('执行进入全屏');
				this.isFullscreen = true;
				// 设置横屏样式
				this.rotateVideoList();

				// 隐藏非videolist元素
				this.hideNonVideoElements();
				this.$emit('fullscreen-change', this.isFullscreen);
				// 强制页面重排
				this.$forceUpdate();
			},
			// 隐藏非videolist元素
			hideNonVideoElements() {
				this.showNonVideoElementsFlag = false;
				console.log('隐藏非视频元素');
			},
			// 显示非videolist元素
			showNonVideoElements() {
				this.showNonVideoElementsFlag = true;
			},
			// 防止默认全屏事件
			onFullscreenChange(e) {
				// 阻止默认全屏行为
				e.preventDefault();

				// 如果有video进入全屏，立即退出
				if (e.detail && e.detail.fullScreen) {
					const videoContext = uni.createVideoContext(`myVideo_${this.liveId}`, this);
					if (videoContext) {
						setTimeout(() => {
							videoContext.exitFullScreen();
						}, 100);
					}
				}
			},

			// 旋转videolist盒子
			rotateVideoList() {
				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);
				}
				// 方法2：检测横屏（备用）
				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 {
					plus.screen.unlockOrientation();
				} catch (e) {
					console.log('解锁屏幕方向失败:', e);
					// 备用方案
					try {
						if (screen.orientation && screen.orientation.unlock) {
							screen.orientation.unlock();
						}
					} catch (err) {
						console.log('备用解锁方案也失败了:', err);
					}
				}
			},



			handleAgreement() {
				console.log('预约直播点击');
				this.$emit('agreementClick');
			}, // 播放视频
			playVideo() {
				if (!this.liveItem) {
					console.log('liveItem 为空，无法播放视频');
					return;
				}
				try {
					// 直播流使用live-player
					if (this.liveItem.liveType === 1 && this.liveItem.livingUrl && this.liveItem.status == 2) {
						const livePlayerId = `myLivePlayer_${this.liveId}`;
						const livePlayerContext = uni.createLivePlayerContext(livePlayerId, this);
						// console.log("直播")
						if (livePlayerContext) {
							livePlayerContext.play();
						}
					} else if (this.liveItem.status == 1 && this.liveItem.previewUrl) {
						const videoId = `myVideo_${this.liveId}`;
						const videoContext = uni.createVideoContext(videoId, this);

						if (videoContext) {
							videoContext.play();
						}
					} else if (this.liveItem.liveType === 2 && this.liveItem.videoUrl && this.liveItem.status == 2) {
						const videoId = `myVideo_${this.liveId}`;
						const videoContext = uni.createVideoContext(videoId, this);
						// console.log("录播")
						if (videoContext) {
							videoContext.play();
						}
					} // 回放视频使用video
					else if (this.liveItem.liveType === 3 && this.liveItem.videoUrl && this.liveItem.status == 4) {
						const videoId = `myVideo_${this.liveId}`;
						const videoContext = uni.createVideoContext(videoId, this);
						// console.log("回放")
						if (videoContext) {
							videoContext.play();
						}
					}
				} catch (error) {
					console.error('播放视频失败:', error);
				}
			},

			pauseVideo() {
				if (!this.liveItem) return;

				try {
					// 直播流使用live-player
					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);
			}, // 视频暂停
			onVideoPause(e) {
				if (this.liveItem.liveType === 2) {
					const videoId = `myVideo_${this.liveId}`;
					const videoContext = uni.createVideoContext(videoId, this);
					setTimeout(() => {
						videoContext.play();
					}, 100);
				}
				// 暂停时保存进度
				this.saveVideoProgress();
			}, //直播、录播缓冲
			getLiveInternetTraffic() {
				if (!this.liveId) return;
				const currentTime = (this.stayTime / this.liveItem.duration) * 100;
				const param = {
					userId: this.userData.userId || '',
					liveId: this.liveId || '',
					uuId: dayjs().format('YYYYMMDD') + this.uuId,
					internetTraffic: this.totalTraffic
				};
				liveInternetTraffic(param);
			},
			startTimer() {
				this.startTime = Date.now();
				this.lookTimer = setInterval(() => {
					this.stayTime = Math.floor((Date.now() - this.startTime) / 1000);
				}, 1000);
			},
			// 计算流量
			// calculateTraffic(bitrate) {
			// 	const currentTime = Date.now();
			// 	const duration = (currentTime - this.startTime) / 1000; // 持续时间（秒）
			// 	// 流量 = 码率 × 时间
			// 	// 码率单位: bps, 时间单位: 秒, 流量单位: 比特
			// 	const trafficBits = bitrate * duration;
			// 	// 转换为字节
			// 	this.totalTraffic = trafficBits / 8;
			// 	this.getLiveInternetTraffic();
			// },
			// 计算流量
			calculateTraffic(bitrate) {
				const currentTime = Date.now();
				const duration = (currentTime - this.startTime) / 1000; // 持续时间（秒）

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

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

				// 调用流量上报接口
				this.getLiveInternetTraffic();
			},
			//直播计算流量
			// startTrafficCalculation(bitrate) {
			// 	if (this.trafficTimer) {
			// 		clearInterval(this.trafficTimer);
			// 		this.trafficTimer = null;
			// 	}
			// 	this.startTime = Date.now();
			// 	var that = this;
			// 	this.trafficTimer = setInterval(() => {
			// 		that.calculateTraffic(bitrate);
			// 	}, 10000); // 每10秒计算一次
			// },
			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秒计算一次
			}, // 计算码率
			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 800;
				}
			},

			// 回放、预告缓冲
			getInternetTraffic() {
				if (!this.liveId || !this.liveId || !this.userData.userId || !this.uuId) return;
				const currentTime = (this.stayTime / this.liveItem.duration) * 100;
				const param = {
					videoType: this.liveItem.videoType,
					videoId: this.liveItem.videoId,
					userId: this.userData.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);
			},
			saveVideoProgress() {
				if (this.videoProgressKey) {
					uni.setStorage({
						key: this.videoProgressKey,
						data: this.videoCurrentTime,
						success: () => {},
						fail: (err) => {
							console.error('保存视频进度失败:', err);
						}
					});
				}
			},
			getTimeDifferenceInSeconds(createTimeStr) {
				const createTime = new Date(createTimeStr.replace(/-/g, '/'));
				const now = new Date();
				const timeDiffMs = now - createTime;
				const timeDiffSeconds = Math.floor(timeDiffMs / 1000);
				return Math.max(0, timeDiffSeconds);
			},
			// onVideoWaiting(e) {
			// 	// console.log('视频等待加载', e);
			// 	if (this.liveItem.liveType == 2) {
			// 		this.startTrafficCalculation(this.bitrate);
			// 	} else {
			// 		let that = this;
			// 		if (this.trafficInterval) {
			// 			clearInterval(this.trafficInterval);
			// 			this.trafficInterval = null;
			// 		}
			// 		this.trafficInterval = setInterval(function() {
			// 			that.getInternetTraffic();
			// 		}, 10000);
			// 	}
			// },
			onVideoWaiting(e) {
				// console.log('视频等待加载', e);
				if (this.liveItem.liveType == 2) {
					// 修改这里：不再传入固定码率，而是在方法内部计算
					this.startTrafficCalculation();
				} else {
					let that = this;
					if (this.trafficInterval) {
						clearInterval(this.trafficInterval);
						this.trafficInterval = null;
					}
					this.trafficInterval = setInterval(function() {
						that.getInternetTraffic();
					}, 10000);
				}
			},
			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.startTime);
					if (diff > this.liveItem.duration) {
						console.log("开始断点续播了")
						const storedProgress = uni.getStorageSync(this.videoProgressKey) || 0;
						console.log("开始断点续播了storedProgress", storedProgress)
						currentTime = storedProgress >= this.liveItem.duration ? 0 : storedProgress || 0;
						console.log("开始断点续播了currentTime", currentTime)
					} else {
						currentTime = diff % this.liveItem.duration;
					}

					// currentTime = diff % this.liveItem.duration;
				} else if (this.liveItem.liveType === 3) {
					// 回放：从存储中获取进度
					const storedProgress = uni.getStorageSync(this.videoProgressKey);
					currentTime = storedProgress || 0;
				}
				const videoId = `myVideo_${this.liveId}`;
				const videoContext = uni.createVideoContext(videoId, this);
				if (videoContext) {
					videoContext.seek(currentTime);
				}
			}, // 视频播放
			onVideoPlay(e) {},
			// 录播时间点
			onVideoMetaLoaded(e) {
				console.log("录播时间点", e)
				this.videoProgressKey = `videoProgress_${this.liveId}`;
				this.setVideoProgress();
			},
			// 视频时间更新
			onVideoTimeUpdate(e) {
				// 获取当前播放时间
				this.videoCurrentTime = e.detail.currentTime;
				// 每隔10秒保存一次进度（避免频繁存储）
				if (Math.floor(this.videoCurrentTime) % 10 === 0) {
					this.saveVideoProgress();
				}
			},
			// 初始化组件 - 增强版本
			async initializeComponent() {
				console.log('初始化视频组件:', {
					liveId: this.liveId,
					liveItem: this.liveItem,
					状态: this.liveItem?.status,
					开始时间: this.liveItem?.startTime
				});

				this.uuId = generateRandomString(16);
				this.isAgreement = uni.getStorageSync('isAgreement');

				// 立即检查当前状态并启动相应功能
				if (this.liveItem?.status === 1 && this.liveItem.startTime) {
					console.log('检测到预告状态，立即启动倒计时');
					this.startLiveCountdown();
				} else if (this.liveItem?.status === 2) {
					this.startTimeTimer(this.liveItem);
					this.playVideo();
				}

				this.startTimer();
				this.hasInitialized = true;
			},

			// 启动直播倒计时 - 增强版本
			startLiveCountdown() {
				console.log('启动直播倒计时:', this.liveItem.startTime);

				// 清理旧定时器
				if (this.liveStartTimer) {
					clearInterval(this.liveStartTimer);
					this.liveStartTimer = null;
				}

				// 立即计算一次倒计时
				this.liveCountdown = this.handleTime(this.liveItem.startTime, 0);
				console.log('初始倒计时:', this.liveCountdown);

				// 如果倒计时已结束，触发直播开始事件
				if (!this.liveCountdown) {
					console.log('倒计时已结束，触发直播开始');
					this.$emit('liveStart');
					return;
				}

				// 启动定时器
				this.liveStartTimer = setInterval(() => {
					const previousCountdown = JSON.stringify(this.liveCountdown);
					this.liveCountdown = this.handleTime(this.liveItem.startTime, 0);

					// 记录倒计时变化（用于调试）
					if (previousCountdown !== JSON.stringify(this.liveCountdown)) {
						console.log('倒计时更新:', this.liveCountdown);
					}

					if (!this.liveCountdown) {
						console.log('倒计时结束，触发直播开始');
						this.$emit('liveStart');
						clearInterval(this.liveStartTimer);
						this.liveStartTimer = null;
					}
				}, 1000);
			},

			// 时间处理函数 - 增强错误处理
			handleTime(time, duration) {
				if (!time) {
					console.error('时间参数为空');
					return false;
				}

				let timeStamp;

				try {
					if (typeof time === 'number' && time > 0 && time < 9999999999999) {
						timeStamp = time;
					} else if (typeof time === 'string' && time.trim() !== '') {
						const isoTime = time.replace(' ', 'T');
						const date = new Date(isoTime);
						if (!isNaN(date.getTime())) {
							timeStamp = date.getTime();
						} else {
							console.error('无效的日期格式:', time);
							return false;
						}
					} else {
						console.error('time参数必须是有效的时间戳或日期字符串');
						return false;
					}

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

					if (timeDiffMs <= 0) {
						return false;
					}
					const hours = Math.floor(timeDiffMs / (1000 * 60 * 60));
					const minutes = Math.floor((timeDiffMs % (1000 * 60 * 60)) / (1000 * 60));
					const seconds = Math.floor((timeDiffMs % (1000 * 60)) / 1000);

					const formatNum = (num) => num.toString().padStart(2, '0');
					return {
						hours: formatNum(hours),
						minutes: formatNum(minutes),
						seconds: formatNum(seconds),
						rawMs: timeDiffMs // 添加原始毫秒数用于调试
					};
				} catch (error) {
					console.error('时间处理错误:', error);
					return false;
				}
			},

			// 其他方法保持不变...
			startTimeTimer(item) {
				if (!item) return;

				this.calculateTimeDiff(item);

				if (item.timeTimer) {
					clearInterval(item.timeTimer);
				}

				item.timeTimer = setInterval(() => {
					this.calculateTimeDiff(item);
				}, 1000);
			},

			calculateTimeDiff(item) {
				if (!item.startTime) return;

				const time = new Date(item.startTime.replace(/-/g, '/'));
				if (isNaN(time.getTime())) return;

				const now = new Date();
				let diffMs = Math.max(0, now.getTime() - time.getTime());

				const totalSeconds = Math.floor(diffMs / 1000);
				const hours = this.padZero(Math.floor(totalSeconds / 3600));
				const minutes = this.padZero(Math.floor((totalSeconds % 3600) / 60));
				const seconds = this.padZero(totalSeconds % 60);

				this.diffTotalTime = `${hours}:${minutes}:${seconds}`;
			},

			padZero(num) {
				return num < 10 ? `0${num}` : num;
			},

			// 清理方法
			cleanup() {
				if (this.liveStartTimer) {
					clearInterval(this.liveStartTimer);
					this.liveStartTimer = null;
				}
				if (this.trafficTimer) {
					clearInterval(this.trafficTimer);
					this.trafficTimer = null;
				}

				if (this.trafficInterval) {
					clearInterval(this.trafficInterval);
					this.trafficInterval = null;
				}
				if (this.lookTimer) {
					clearInterval(this.lookTimer);
					this.lookTimer = null;
				}
				if (this.liveItem && this.liveItem.timeTimer) {
					clearInterval(this.liveItem.timeTimer);
					this.liveItem.timeTimer = null;
				}
			}
		}
	};
</script>

<style scoped lang="scss">
	.video-player-container {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.videolist {
		position: relative;
		height: 100vh;
		width: 100%;

		&.screen {
			width: 100%;
			height: 100%;
		}

		.video {
			height: 100vh;
			width: 100%;

			.item {
				width: 100%;
				height: 100%;
			}

			.time {
				color: #ffffff;
				font-size: 20rpx;
				margin-left: 10rpx;
			}

			.look-time {
				position: absolute;
				left: 10vh;
				bottom: 24rpx;
				font-size: 20rpx;
				background-color: rgba(57, 57, 57, 0.6);
				border-radius: 15rpx;
				z-index: 999999 !important;
				padding: 10rpx 16rpx;
				color: #fff;
			}

			.end {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				font-size: 36rpx;
				color: #fff;
			}

			.lable {
				position: absolute;
				top: 50rpx;
				right: 16rpx;
				background-color: rgba(57, 57, 57, 0.6);
				padding: 4rpx 10rpx;
				color: #fff;
				border-radius: 15rpx;
			}
		}

		.video_row {
			position: absolute;
			top: 380rpx;
			max-height: 450rpx;
			z-index: 99;

			/* ==== 全屏模式样式 ==== */
			&.fullscreen-mode {
				// position: fixed !important;
				// top: 0 !important;
				// left: 0 !important;
				top: 0;
				width: 0;
				height: auto;
				z-index: 99999 !important;
				background-color: #000 !important;
				transform: rotate(90deg) !important;
				transform-origin: center center !important;
				// transform: rotate(0) ;
				// transform: rotate(90deg) translateY(-100%) !important;
				// transform-origin: left top !important;

				.item {
					position: absolute;
					bottom: 0;
					width: 100vh !important;
					height: 100vw !important;
					// transform: rotate(-90deg) !important;
					transform-origin: center center !important;
					object-fit: contain !important;
				}

				.custom-controls {
					transform: rotate(-90deg) !important;
					transform-origin: center center !important;
					bottom: auto !important;
					top: 40rpx !important;
					right: 40rpx !important;
				}

				.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;
					}
				}
			}

			/* 全屏按钮样式优化 */
			.custom-controls {
				position: absolute;
				bottom: 10%;
				right: 40rpx;
				z-index: 99999999;
				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;

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

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

	// 重置按钮样式
	.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;
		}
	}

	.trailer-box {
		width: calc(100% - 80rpx);
		background: #333333;
		border-radius: 24rpx;
		position: absolute;
		top: 320rpx;
		left: 50%;
		transform: translateX(-50%);
		display: flex;
		flex-direction: column;
		align-items: center;
		color: #fff;
		padding: 20rpx;
		z-index: 99999;
		box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.12);
		transition: box-shadow 0.3s ease;

		.trailer-video {
			width: 100%;
			height: 400rpx;
		}

		.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;
		}
	}
</style>