<template>
	<view class="container">
		<!-- 设备头部信息区域 -->
		<view class="device-header">
			<view class="device-info-row">
				<view class="device-name-container">
					<text class="device-name">{{ deviceInfo.name }}</text>
					<view class="status-tag" :class="deviceInfo.status === 1 ? 'status-online' : 'status-offline'">
						<view class="status-dot" :class="{'offline-dot': deviceInfo.status === 0}"></view>
						{{ deviceInfo.status === 1 ? '在线' : '离线' }}
					</view>
				</view>

				<view class="refresh-btn" :class="{'refreshing': isRefreshing}" @tap="refreshData">
					<image src="/static/icons/refresh_icon.png" mode="aspectFit" style="width: 22px; height: 22px;">
					</image>
				</view>
			</view>

			<view class="device-meta-row">
				<view class="device-meta-item">
					<view class="meta-icon">
						<image src="/static/icons/device_icon.png" mode="aspectFit"
							style="width: 36rpx; height: 36rpx;"></image>
					</view>
					<text class="meta-label">设备编号：</text>
					<text class="meta-value">{{ deviceInfo.deviceId }}</text>
				</view>

				<view class="device-meta-item">
					<view class="meta-icon">
						<image src="/static/icons/location_icon.png" mode="aspectFit"
							style="width: 36rpx; height: 36rpx;"></image>
					</view>
					<text class="meta-label">安装位置：</text>
					<text class="meta-value">{{ deviceInfo.location }}</text>
				</view>

				<view class="device-meta-item">
					<view class="meta-icon">
						<image src="/static/icons/clock_icon.png" mode="aspectFit" style="width: 36rpx; height: 36rpx;">
						</image>
					</view>
					<text class="meta-label">最近更新：</text>
					<text class="meta-value">{{ formatDate(deviceInfo.lastUpdate) }}</text>
				</view>
			</view>
		</view>

		<!-- 视频预览区域 -->
		<view class="video-section">
			<view class="video-container" :class="{'fullscreen-mode': isFullscreen}">
				<image v-if="!isPlaying" src="/static/images/video-placeholder.jpg" mode="aspectFill"
					class="video-placeholder"></image>

				<!-- 使用跨平台视频播放组件 -->
				<!-- #ifdef H5 -->
				<view v-if="isPlaying" class="h5-video-wrapper">
					<Jessibuca ref="jessibucaRef" :videoUrl="getH5StreamUrl" :hasAudio="true" @error="onVideoError" />
				</view>
				<!-- #endif -->

				<!--wx-->
				<!-- <live-player v-if="isPlaying" id="videoPlayer" :src="getMiniProgramStreamUrl" mode="live"
					:autoplay="true" :muted="isMuted" object-fit="contain" @statechange="onStateChange"
					@error="onVideoError" @fullscreenchange="onFullscreenChange" class="video-player"></live-player> -->
				

				<!-- #ifndef H5 -->
				<!-- <live-player v-if="isPlaying" id="appVideoPlayer" :src="getAppStreamUrl" mode="live"
					:autoplay="true" :muted="isMuted" object-fit="contain" @statechange="onStateChange"
					@error="onVideoError" @fullscreenchange="onFullscreenChange" 
					:enable-danmu="false"
					:show-center-play-btn="false"
					:show-play-btn="false"
					class="video-player"></live-player> -->
					<video class="video-player" v-if="isPlaying" id="myVideo" :src="getAppStreamUrl" :autoplay="true" controls></video>
				<!-- #endif -->

				<!-- 视频控制层 -->
				<view class="video-controls">
					<view class="control-row top-controls">
						<view class="signal-indicator">
							<image src="/static/icons/signal_icon.png" mode="aspectFit"
								style="width: 16px; height: 16px;"></image>
							<text class="signal-text">信号良好</text>
						</view>

						<view class="fullscreen-button" @click="toggleFullscreen">
							<image src="/static/icons/resize_icon.png" mode="aspectFit"
								style="width: 20px; height: 20px;"></image>
						</view>
					</view>

					<view class="control-row center-controls">
						<view v-if="!isPlaying" class="play-button" @click="togglePlayState">
							<image src="/static/icons/play_icon.png" mode="aspectFit"
								style="width: 32px; height: 32px;"></image>
						</view>
						<view v-else class="center-button-container" @click="togglePlayState">
							<view class="pause-icon">
								<image src="/static/icons/pause_icon.png" mode="aspectFit"
									style="width: 24px; height: 24px;"></image>
							</view>
						</view>
					</view>

					<view class="control-row bottom-controls">
						<view class="video-time">{{ currentTime }}</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 告警信息列表 -->
		<view class="alerts-section">
			<view class="section-title">
				<text>告警信息</text>
				<view class="alert-badge" v-if="getUnhandledAlerts.length > 0">{{ getUnhandledAlerts.length }}</view>
			</view>

			<view class="alerts-list" v-if="getUnhandledAlerts.length > 0">
				<view v-for="(item, index) in getUnhandledAlerts.slice(0, 3)" :key="index" class="alert-item" :class="{
            'alert-urgent': item.level === 3, 
            'alert-warning': item.level === 2, 
            'alert-info': item.level === 1
          }">
					<view class="alert-item-icon">
						<image v-if="item.level === 3" src="/static/icons/warning_icon.png" mode="aspectFit"
							style="width: 24px; height: 24px;"></image>
						<image v-else-if="item.level === 2" src="/static/icons/info_icon.png" mode="aspectFit"
							style="width: 24px; height: 24px;"></image>
						<image v-else src="/static/icons/success_icon.png" mode="aspectFit"
							style="width: 24px; height: 24px;"></image>
					</view>

					<view class="alert-item-info">
						<text class="alert-item-type">{{ item.type }}</text>
						<text class="alert-item-level">
							{{ item.level === 3 ? '紧急' : item.level === 2 ? '警告' : '提示' }}
						</text>
					</view>

					<view class="alert-item-time">{{ formatSmartTime(item.time) }}</view>
				</view>
			</view>

			<view v-else class="empty-alert">
				<text class="empty-text">暂无告警信息</text>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
	import {
		getDeviceCollectorDetail,
		getChannels,
		playStart,
		pause
	} from "@/api/services/device.js"
	import {
		formatSmartTime,
		formatDate,
		getFormattedTime
	} from '@/utils/dateUtils'
	import {
		buildPlatformStreamUrls
	} from '@/utils/media-utils'
	import config from '@/config/config'
	// 导入Jessibuca组件
	// #ifdef H5
	import Jessibuca from '@/components/common/jessibuca.vue'
	// #endif

	// 响应式数据
	const deviceInfo = reactive({
		deviceId: '',
		name: '设备加载中...',
		status: '',
		location: '正在获取位置...',
		lastUpdate: '',
		deviceType: 'weather', // 默认类型，会根据API返回更新
		deviceTypeId: null,
		streamUrl: '',
		channelId: null, // 当前通道ID
		originalStreamUrl: '',
	})

	const isPlaying = ref(false)
	const isMuted = ref(false)
	const isRecording = ref(false)
	const isFullscreen = ref(false)
	const isVoiceActive = ref(false)
	const isGridView = ref(false)
	const isZoomMode = ref(false)
	const currentTime = ref('14:30:25')
	
	// 模拟历史录像数据
	const recordHistory = ref([{
			id: 1,
			startTime: '今天 12:30',
			duration: '00:15:30',
			url: ''
		},
		{
			id: 2,
			startTime: '今天 10:15',
			duration: '00:05:22',
			url: ''
		},
		{
			id: 3,
			startTime: '昨天 18:45',
			duration: '00:30:10',
			url: ''
		},
		{
			id: 4,
			startTime: '昨天 14:20',
			duration: '00:10:05',
			url: ''
		}
	])
	
	// 模拟告警数据
	const alertHistory = ref([])
	const livePlayerContext = ref(null) // 小程序视频上下文
	const appLivePlayerContext = ref(null) // App端视频上下文
	const isRefreshing = ref(false)
	const jessibucaRef = ref(null)

	// 计算属性
	// 获取所有未处理的告警
	const getUnhandledAlerts = computed(() => {
		return alertHistory.value.filter(alert => alert.status === 0)
	})
	
	// 获取H5环境使用的流地址
	const getH5StreamUrl = computed(() => {
		// 确保使用安全的 WSS 协议
		let url = deviceInfo.originalStreamUrl
		if (url && url.startsWith('ws://')) {
			console.warn('检测到不安全的 ws:// 协议，自动转换为 wss://')
			url = url.replace('ws://', 'wss://')
		}
		return url
	})

	// 获取小程序环境使用的流地址
	const getMiniProgramStreamUrl = computed(() => {
		const {
			streamServer
		} = config

		if (deviceInfo.rtmpUrl) {
			return deviceInfo.rtmpUrl
		}

		if (deviceInfo.hlsUrl) {
			return deviceInfo.hlsUrl
		}

		return streamServer.rtmpServer || streamServer.hlsServer
	})

	// 获取App（安卓/鸿蒙）环境使用的流地址
	const getAppStreamUrl = computed(() => {
		const {
			streamServer
		} = config

		// // App端优先使用 RTMP 或 HLS 流
		// if (deviceInfo.rtmpUrl) {
		// 	return deviceInfo.rtmpUrl
		// }

		// if (deviceInfo.hlsUrl) {
		// 	return deviceInfo.hlsUrl
		// }

		// 如果有原始流地址，尝试转换为 RTMP 或 HLS
		if (deviceInfo.originalStreamUrl) {
			// 如果是 ws-flv 格式，转换为 RTMP
			// if (deviceInfo.originalStreamUrl.includes('.flv')) {
			// 	const rtmpUrl = deviceInfo.originalStreamUrl
			// 		.replace('ws://', 'rtmp://')
			// 		.replace(':6080/rtp/', ':1935/live/')
			// 		.replace('.live.flv', '')
			// 	return rtmpUrl
			// }
			console.log("deviceInfo.originalStreamUrl",deviceInfo.originalStreamUrl);
		}

		// return streamServer.rtmpServer || streamServer.hlsServer
		return deviceInfo.originalStreamUrl
	})

	// 方法
	// 刷新数据
	const refreshData = () => {
		isRefreshing.value = true
		fetchDeviceInfo()
		setTimeout(() => {
			isRefreshing.value = false
		}, 1000)
	}

	// 加载Jessibuca脚本
	const loadJessibucaScript = () => {
		// #ifdef H5
		const script = document.createElement('script')
		script.src = '/static/js/jessibuca/jessibuca.js'
		script.onload = () => {
			console.log('Jessibuca 脚本加载成功')
		}
		script.onerror = (error) => {
			console.error('Jessibuca 脚本加载失败:', error)
		}
		document.head.appendChild(script)
		// #endif
		// #ifndef H5
		// 非 H5 平台不支持 Jessibuca 视频播放
		// console.warn('当前平台不支持 Jessibuca 视频播放，请使用 uni-app video 组件')
		// #endif
	}
	
	// 获取设备信息
	const fetchDeviceInfo = () => {
		console.log('获取设备信息：', deviceInfo.deviceId)
		getDeviceCollectorDetail(deviceInfo.deviceId)
			.then(res => {
				if (res.data.data && res.data.code === 200) {
					const detail = res.data.data
					deviceInfo.lastUpdate = getFormattedTime()
					uni.setNavigationBarTitle({
						title: deviceInfo.name
					})
					if (detail.alertRecordList && detail.alertRecordList.length > 0) {
						alertHistory.value = detail.alertRecordList.map(alert => ({
							id: alert.alertId,
							time: alert.alertTime,
							type: alert.alertContent,
							status: alert.processStatus,
							level: alert.alertLevel
						}))
					}
				}
			})
	}

	// 根据设备id获取通道列表
	const queryChannels = () => {
		getChannels(deviceInfo.deviceId)
			.then(response => {
				console.log('获取通道列表:', response)
				const res = response.data
				if (res.code === 0 && res.data.total > 0) {
					const channels = res.data.list
					deviceInfo.channelId = channels[0].deviceId
					playStart(deviceInfo.deviceId, deviceInfo.channelId).then(res => {
						if (res.data.code !== 0) {
							console.error('播放开始失败:', res.message)
							uni.showToast({
								title: '播放失败: ' + res.message,
								icon: 'none'
							})
							return
						}
						console.log('播放开始:', res)
						// #ifdef H5
						let streamUrl = res.data.data.wss_flv
						
						if (streamUrl) {
							const urlObj = new URL(streamUrl)
							// 替换 hostname
							urlObj.hostname = 'nxy.gbdfarm.com'
							// 替换端口
							urlObj.port = '9000'
							
							deviceInfo.originalStreamUrl = urlObj.toString()
							console.log("queryChannels - deviceInfo.originalStreamUrl", deviceInfo.originalStreamUrl)
						} else {
							console.warn('未获取到 wss_flv 流地址')
						}
						// #endif
						// #ifndef H5
						deviceInfo.originalStreamUrl = res.data.data.fmp4 || deviceInfo.originalStreamUrl
						// #endif
					}).catch(err => {
						console.error('播放开始失败:', err)
					})
				} else {
					uni.showToast({
						title: '获取通道列表失败: ' + res.data.message,
						icon: 'none'
					})
					return
				}
			})
			.catch(err => {
				console.error('获取通道列表错误:', err)
			})
	}
	
	// 播放/暂停切换
	const togglePlayState = () => {
		if (!isPlaying.value) {
			isPlaying.value = true

			// wx
			// setTimeout(() => {
			// 	if (livePlayerContext.value) {
			// 		livePlayerContext.value.play({
			// 			success: () => {
			// 				console.log('小程序视频播放成功')
			// 				uni.vibrateShort()
			// 			},
			// 			fail: (err) => {
			// 				console.error('小程序视频播放失败:', err)
			// 				uni.showToast({
			// 					title: '视频播放失败',
			// 					icon: 'none'
			// 				})
			// 			}
			// 		})
			// 	}
			// }, 300)
			

			// #ifndef H5
			setTimeout(() => {
				if (appLivePlayerContext.value) {
					appLivePlayerContext.value.play({
						success: () => {
							console.log('App视频播放成功')
							uni.vibrateShort()
						},
						fail: (err) => {
							console.error('App视频播放失败:', err)
							uni.showToast({
								title: '视频播放失败',
								icon: 'none'
							})
						}
					})
				}
			}, 300)
			// #endif

			// #ifdef H5
			setTimeout(() => {
				playStart(deviceInfo.deviceId, deviceInfo.channelId).then(res => {
					if (res.data.code !== 0) {
						console.error('播放开始失败:', res.message)
						uni.showToast({
							title: '播放失败: ' + res.message,
							icon: 'none'
						})
						return
					}
					console.log('播放开始:', res)
					
					// 使用 wss_flv 并替换域名和端口
					let streamUrl = res.data.data.wss_flv
					if (streamUrl) {
						const urlObj = new URL(streamUrl)
						urlObj.hostname = 'nxy.gbdfarm.com'
						urlObj.port = '9000'
						deviceInfo.originalStreamUrl = urlObj.toString()
						console.log("togglePlayState - deviceInfo.originalStreamUrl", deviceInfo.originalStreamUrl)
					}
				}).catch(err => {
					console.error('播放开始失败:', err)
				})
				uni.vibrateShort()
			}, 300)
			// #endif
		} else {
			// #ifdef H5
			if (jessibucaRef.value) {
				jessibucaRef.value.pause()
			}
			// #endif

			// wx
			// if (livePlayerContext.value) {
			// 	livePlayerContext.value.pause()
			// }
			

			// #ifndef H5
			if (appLivePlayerContext.value) {
				appLivePlayerContext.value.pause()
			}
			// #endif

			isPlaying.value = false

			uni.showToast({
				title: '视频已暂停',
				icon: 'none',
				duration: 1500
			})
		}
	}

	// 静音切换
	const toggleMute = () => {
		isMuted.value = !isMuted.value

		// #ifdef H5
		if (jessibucaRef.value) {
			if (isMuted.value) {
				jessibucaRef.value.mute()
			} else {
				jessibucaRef.value.cancelMute()
			}
		}
		// #endif

		// #ifndef H5
		// App端的静音通过 live-player 的 muted 属性控制，会自动响应
		uni.showToast({
			title: isMuted.value ? '已静音' : '已取消静音',
			icon: 'none'
		})
		// #endif
	}

	// 全屏切换
	const toggleFullscreen = () => {
		if (!isPlaying.value) {
			togglePlayState()
			setTimeout(() => {
				setFullscreen(true)
			}, 500)
		} else {
			setFullscreen(!isFullscreen.value)
		}
	}

	// 设置全屏状态
	const setFullscreen = (fullscreen) => {
		isFullscreen.value = fullscreen

		// #ifdef H5
		if (isFullscreen.value) {
			const ua = navigator.userAgent.toLowerCase()
			const isMobile = /mobile|android|iphone|ipad/.test(ua)

			if (isMobile && jessibucaRef.value) {
				jessibucaRef.value.fullscreenSwich()
			} else {
				setTimeout(() => {
					if (jessibucaRef.value) {
						jessibucaRef.value.resize()
					}
				}, 300)
			}

			if (window.screen && window.screen.orientation && window.screen.orientation.lock) {
				window.screen.orientation.lock('landscape').catch(err => {
					console.error('无法锁定屏幕方向:', err)
				})
			}
		} else {
			if (jessibucaRef.value) {
				if (jessibucaRef.value.isFullscreen()) {
					jessibucaRef.value.fullscreenSwich()
				}

				setTimeout(() => {
					if (jessibucaRef.value) {
						jessibucaRef.value.resize()
					}
				}, 300)
			}

			if (window.screen && window.screen.orientation && window.screen.orientation.unlock) {
				window.screen.orientation.unlock()
			}
		}
		// #endif

		//wx
		// if (livePlayerContext.value) {
		// 	if (isFullscreen.value) {
		// 		livePlayerContext.value.requestFullScreen({
		// 			direction: 90,
		// 			success: () => {
		// 				console.log('进入全屏模式成功')
		// 			},
		// 			fail: (err) => {
		// 				console.error('进入全屏模式失败:', err)
		// 			}
		// 		})
		// 	} else {
		// 		livePlayerContext.value.exitFullScreen({
		// 			success: () => {
		// 				console.log('退出全屏模式成功')
		// 			},
		// 			fail: (err) => {
		// 				console.error('退出全屏模式失败:', err)
		// 			}
		// 		})
		// 	}
		// }
		

		// #ifndef H5
		if (appLivePlayerContext.value) {
			if (isFullscreen.value) {
				appLivePlayerContext.value.requestFullScreen({
					direction: 90,
					success: () => {
						console.log('App进入全屏模式成功')
					},
					fail: (err) => {
						console.error('App进入全屏模式失败:', err)
					}
				})
			} else {
				appLivePlayerContext.value.exitFullScreen({
					success: () => {
						console.log('App退出全屏模式成功')
					},
					fail: (err) => {
						console.error('App退出全屏模式失败:', err)
					}
				})
			}
		}
		// #endif
	}

	// 截图
	const takeScreenshot = () => {
		// #ifdef H5
		if (jessibucaRef.value && isPlaying.value) {
			jessibucaRef.value.screenshot()
			uni.showToast({
				title: '截图已保存',
				icon: 'success'
			})
		} else {
			uni.showToast({
				title: '请先播放视频',
				icon: 'none'
			})
		}
		// #endif

		
		// if (livePlayerContext.value && isPlaying.value) {
		// 	livePlayerContext.value.snapshot({
		// 		success: (res) => {
		// 			console.log('截图成功:', res.tempImagePath)
		// 			uni.saveImageToPhotosAlbum({
		// 				filePath: res.tempImagePath,
		// 				success: () => {
		// 					uni.showToast({
		// 						title: '截图已保存到相册',
		// 						icon: 'success'
		// 					})
		// 				},
		// 				fail: (err) => {
		// 					console.error('保存截图失败:', err)
		// 					uni.showToast({
		// 						title: '保存截图失败',
		// 						icon: 'none'
		// 					})
		// 				}
		// 			})
		// 		},
		// 		fail: (err) => {
		// 			console.error('截图失败:', err)
		// 			uni.showToast({
		// 				title: '截图失败',
		// 				icon: 'none'
		// 			})
		// 		}
		// 	})
		// } else {
		// 	uni.showToast({
		// 		title: '请先播放视频',
		// 		icon: 'none'
		// 	})
		// }
		

		// #ifndef H5
		if (appLivePlayerContext.value && isPlaying.value) {
			appLivePlayerContext.value.snapshot({
				success: (res) => {
					console.log('App截图成功:', res.tempImagePath)
					uni.saveImageToPhotosAlbum({
						filePath: res.tempImagePath,
						success: () => {
							uni.showToast({
								title: '截图已保存到相册',
								icon: 'success'
							})
						},
						fail: (err) => {
							console.error('App保存截图失败:', err)
							uni.showToast({
								title: '保存截图失败',
								icon: 'none'
							})
						}
					})
				},
				fail: (err) => {
					console.error('App截图失败:', err)
					uni.showToast({
						title: '截图失败',
						icon: 'none'
					})
				}
			})
		} else {
			uni.showToast({
				title: '请先播放视频',
				icon: 'none'
			})
		}
		// #endif
	}

	// 小程序播放器状态变化处理
	const onStateChange = (e) => {
		console.log('播放器状态变化:', e.detail)
		const state = e.detail.code
		switch (state) {
			case 2001:
				console.log('已连接服务器')
				break
			case 2002:
				console.log('开始拉流')
				break
			case 2003:
				console.log('网络接收到首个视频帧')
				break
			case 2004:
				console.log('视频播放开始')
				break
			case 2005:
				console.log('视频播放进度')
				break
			case 2006:
				console.log('视频播放结束')
				isPlaying.value = false
				break
			case 2007:
				console.log('视频播放Loading')
				break
			case 2008:
				console.log('解码器启动')
				break
			case 2009:
				console.log('视频分辨率改变')
				break
			case -2301:
				console.error('网络断连，且重新连接亦不能恢复，播放器已停止')
				isPlaying.value = false
				uni.showToast({
					title: '网络断连，请重试',
					icon: 'none'
				})
				break
			case -2302:
				console.error('获取加速拉流地址失败')
				break
			case 2101:
				console.error('当前视频帧解码失败')
				break
			case 2102:
				console.error('当前音频帧解码失败')
				break
			case 2103:
				console.warn('网络断连, 已启动自动重连')
				break
			case 2104:
				console.warn('网络断连, 重连中...')
				break
			case 2105:
				console.log('网络断连, 重连成功')
				break
			case 2106:
				console.error('网络断连, 重连失败')
				break
			case 2107:
				console.error('播放器连接超时')
				break
			case 2108:
				console.error('获取点播文件信息失败')
				break
			default:
				console.log('其他状态:', state)
		}
	}

	// 小程序全屏状态变化
	const onFullscreenChange = (e) => {
		isFullscreen.value = e.detail.fullScreen
		console.log('全屏状态变化:', isFullscreen.value)
	}

	// 初始化流地址
	const initStreamUrl = () => {
		const originalUrl = deviceInfo.originalStreamUrl
		const streamUrls = buildPlatformStreamUrls(originalUrl, {
			streamServer: config.streamServer,
			fallbackToHls: true
		})

		// #ifdef H5
		deviceInfo.streamUrl = streamUrls.h5Url
		// #endif

		// #ifdef MP-WEIXIN
		// if (streamUrls.miniProgramUrl) {
		// 	deviceInfo.streamUrl = streamUrls.miniProgramUrl
		// } else {
		// 	uni.showToast({
		// 		title: '当前视频流不支持小程序播放',
		// 		icon: 'none',
		// 		duration: 3000
		// 	})
		// }
		// #endif

		// #ifndef H5
		if (streamUrls.miniProgramUrl) {
			deviceInfo.streamUrl = streamUrls.miniProgramUrl
		} else {
			// App端尝试使用 RTMP 或 HLS
			const rtmpUrl = originalUrl
				.replace('ws://', 'rtmp://')
				.replace(':6080/rtp/', ':1935/live/')
				.replace('.live.flv', '')
			deviceInfo.streamUrl = rtmpUrl || config.streamServer.rtmpServer
		}
		// #endif

		console.log('初始化流地址:', deviceInfo.streamUrl)
	}

	// 切换九宫格视图
	const toggleGridView = () => {
		isGridView.value = !isGridView.value
		uni.showToast({
			title: isGridView.value ? '切换到多画面模式' : '切换到单画面模式',
			icon: 'none'
		})
	}

	// 语音对讲
	const toggleVoiceIntercom = () => {
		isVoiceActive.value = !isVoiceActive.value

		if (isVoiceActive.value) {
			uni.showToast({
				title: '语音对讲已开启',
				icon: 'none'
			})
		} else {
			uni.showToast({
				title: '语音对讲已关闭',
				icon: 'none'
			})
		}
	}

	// 云台控制
	const controlPTZ = (direction, isStart) => {
		if (isStart) {
			console.log(`开始控制云台: ${direction}`)
			uni.vibrateShort()
		} else {
			console.log(`停止控制云台: ${direction}`)
		}
	}

	// 云台复位
	const resetPTZ = () => {
		console.log('云台复位')
		uni.vibrateShort()
		uni.showToast({
			title: '云台已复位',
			icon: 'none'
		})
	}

	// 变焦控制
	const controlZoom = (type, isStart) => {
		if (isStart) {
			console.log(`开始控制变焦: ${type}`)
			uni.vibrateShort()
		} else {
			console.log(`停止控制变焦: ${type}`)
		}
	}

	// 切换缩放模式
	const toggleZoom = () => {
		isZoomMode.value = !isZoomMode.value
		uni.showToast({
			title: isZoomMode.value ? '进入缩放模式' : '退出缩放模式',
			icon: 'none'
		})
	}

	// 添加预设位
	const addPreset = () => {
		uni.showModal({
			title: '添加预设位',
			content: '是否保存当前位置为预设位？',
			success: (res) => {
				if (res.confirm) {
					uni.showToast({
						title: '预设位已保存',
						icon: 'success'
					})
				}
			}
		})
	}

	// 处理告警点击
	const handleAlert = (item) => {
		uni.navigateTo({
			url: `/pages/alerts/alert-detail?alertId=${item.id}&deviceId=${deviceInfo.deviceId}`
		})
	}

	// 跳转到历史视频页面
	const navigateToHistory = () => {
		uni.navigateTo({
			url: `/pages/video/history?deviceId=${deviceInfo.deviceId}`
		})
	}

	// 视频播放错误处理
	const onVideoError = (e) => {
		console.error('视频播放错误:', e)
		uni.showToast({
			title: '视频加载失败，请检查网络连接',
			icon: 'none',
			duration: 2000
		})

		// #ifdef H5
		setTimeout(() => {
			if (isPlaying.value && jessibucaRef.value) {
				console.log('尝试重新加载视频流')
				if (deviceInfo.originalStreamUrl !== config.streamServer.wsFlvServer) {
					deviceInfo.streamUrl = config.streamServer.wsFlvServer
				}
			}
		}, 3000)
		// #endif
	}

	// 更新时间
	const startTimeUpdate = () => {
		setInterval(() => {
			const now = new Date()
			const hours = String(now.getHours()).padStart(2, '0')
			const minutes = String(now.getMinutes()).padStart(2, '0')
			const seconds = String(now.getSeconds()).padStart(2, '0')
			currentTime.value = `${hours}:${minutes}:${seconds}`
		}, 1000)
	}
	
	// 设置全屏状态监听
	const setupFullscreenListener = () => {
		// Placeholder for fullscreen listener setup
	}

	// 设置键盘监听
	const setupKeyboardListener = () => {
		// Placeholder for keyboard listener setup
	}

	// 生命周期钩子
	onMounted(() => {
		uni.setNavigationBarTitle({
			title: deviceInfo.name
		})

		startTimeUpdate()

		// #ifdef MP-WEIXIN
		// livePlayerContext.value = uni.createLivePlayerContext('videoPlayer')
		// #endif

		// #ifdef APP-PLUS || APP-HARMONY
		// appLivePlayerContext.value = uni.createLivePlayerContext('appVideoPlayer')
		// #endif

		// #ifdef H5
		loadJessibucaScript()
		// #endif

		setupFullscreenListener()
		setupKeyboardListener()
		initStreamUrl()
	})

	onBeforeUnmount(() => {
		console.log("停止点播")
		pause(deviceInfo.deviceId, deviceInfo.channelId).then(res => {
			if (res.data.code !== 0) {
				console.error('暂停失败:', res.message)
			} else {
				console.log('视频已暂停')
			}
		}).catch(err => {
			console.error('暂停请求错误:', err)
		})
	})

	// uni-app 生命周期
	uni.$once('passDeviceData', (data) => {
		console.log('接收到数据', data)
		if (data && data.deviceId) {
			deviceInfo.deviceId = data.deviceId
			deviceInfo.location = data.fieldName
			deviceInfo.name = data.deviceName
			deviceInfo.status = data.status
			deviceInfo.deviceTypeId = data.deviceTypeId || ''

			fetchDeviceInfo()
			queryChannels()
		}
	})
</script>

<style>
	/* 基础样式 */
	.container {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
		background-color: #F8FCF9;
		padding-bottom: 30rpx;
	}

	/* 设备头部样式 */
	.device-header {
		background-color: #FFFFFF;
		border-radius: 20rpx;
		padding: 26rpx 30rpx 30rpx;
		margin: 20rpx 30rpx 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
	}

	.device-info-row {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 24rpx;
	}

	.device-name-container {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
	}

	.device-name {
		font-size: 34rpx;
		color: #333333;
		font-weight: 600;
		margin-bottom: 10rpx;
	}

	.status-tag {
		padding: 4rpx 12rpx 4rpx 24rpx;
		border-radius: 30rpx;
		font-size: 22rpx;
		font-weight: 500;
		flex-shrink: 0;
		position: relative;
		overflow: hidden;
	}

	.status-online {
		background-color: rgba(76, 175, 80, 0.1);
		color: #3BB44A;
	}

	.status-offline {
		background-color: rgba(245, 108, 108, 0.1);
		color: #F56C6C;
		padding-left: 24rpx;
	}

	.status-dot {
		position: absolute;
		width: 6rpx;
		height: 6rpx;
		background-color: #3BB44A;
		border-radius: 50%;
		top: 50%;
		left: 12rpx;
		transform: translateY(-50%);
		box-shadow: 0 0 4rpx rgba(76, 175, 80, 0.8);
		animation: blink 1.5s infinite;
		display: inline-block;
	}

	.status-dot.offline-dot {
		background-color: #F56C6C;
		box-shadow: 0 0 4rpx rgba(245, 108, 108, 0.8);
	}

	@keyframes blink {
		0% {
			opacity: 0.4;
		}

		50% {
			opacity: 1;
		}

		100% {
			opacity: 0.4;
		}
	}

	.device-meta-row {
		display: flex;
		flex-direction: column;
	}

	.device-meta-item {
		display: flex;
		align-items: center;
		font-size: 26rpx;
		margin-top: 18rpx;
	}

	.meta-icon {
		width: 36rpx;
		height: 36rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 8rpx;
	}

	.meta-label {
		color: #999999;
		min-width: 140rpx;
		font-size: 26rpx;
	}

	.meta-value {
		color: #333333;
		flex: 1;
		font-size: 26rpx;
	}

	/* 视频预览区域 */
	.video-section {
		margin: 0 30rpx 20rpx;
		position: relative;
		z-index: 1;
	}

	.video-container {
		position: relative;
		width: 100%;
		height: 420rpx;
		background-color: #000000;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
		transition: all 0.3s ease;
	}

	.video-container.fullscreen-mode {
		position: fixed;
		top: 0;
		left: 0;
		width: 100vw;
		height: 100vh;
		margin: 0;
		z-index: 9999;
		border-radius: 0;
	}

	.video-container.fullscreen-mode .video-controls {
		padding: 30rpx;
	}

	.video-container.fullscreen-mode .top-controls,
	.video-container.fullscreen-mode .bottom-controls {
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.video-container.fullscreen-mode:hover .top-controls,
	.video-container.fullscreen-mode:hover .bottom-controls {
		opacity: 1;
	}

	.video-player,
	.video-placeholder {
		width: 100%;
		height: 100%;
		object-fit: contain;
	}

	.h5-video-wrapper {
		width: 100%;
		height: 100%;
	}

	/* App端视频播放器样式优化 */
	/* #ifdef APP-PLUS || APP-HARMONY */
	#appVideoPlayer {
		width: 100%;
		height: 100%;
		background-color: #000000;
	}
	/* #endif */

	.video-controls {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		padding: 20rpx;
		box-sizing: border-box;
		background: linear-gradient(to bottom, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0) 30%, rgba(0, 0, 0, 0) 70%, rgba(0, 0, 0, 0.4) 100%);
	}

	.control-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
	}

	.top-controls {
		height: 80rpx;
	}

	.center-controls {
		height: 120rpx;
		justify-content: center;
		align-items: center;
	}

	.bottom-controls {
		height: 80rpx;
	}

	.signal-indicator {
		display: flex;
		align-items: center;
		color: #FFFFFF;
		font-size: 24rpx;
		background-color: rgba(0, 0, 0, 0.5);
		padding: 8rpx 16rpx;
		border-radius: 30rpx;
	}

	.signal-indicator svg {
		margin-right: 8rpx;
	}

	.signal-text {
		font-weight: 500;
	}

	.fullscreen-button {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #FFFFFF;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		transition: all 0.2s;
	}

	.fullscreen-button:active {
		background-color: rgba(76, 175, 80, 0.7);
		transform: scale(0.9);
	}

	.video-time {
		color: #FFFFFF;
		font-size: 26rpx;
		background-color: rgba(0, 0, 0, 0.5);
		padding: 6rpx 16rpx;
		border-radius: 30rpx;
		font-weight: 500;
	}

	.play-button {
		width: 100rpx;
		height: 100rpx;
		border-radius: 50%;
		background-color: rgba(255, 255, 255, 0.9);
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.5);
		transition: all 0.2s;
		transform: scale(1);
	}

	.play-button:active {
		transform: scale(0.92);
		background-color: rgba(255, 255, 255, 1);
	}

	.center-button-container {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.pause-icon {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		opacity: 0;
		transition: opacity 0.3s;
	}

	.center-button-container:active .pause-icon {
		opacity: 1;
		background-color: rgba(76, 175, 80, 0.7);
	}

	.refresh-btn {
		width: 48rpx;
		height: 48rpx;
		background-color: rgba(76, 175, 80, 0.1);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 12rpx;
		transition: transform 0.3s ease;
	}

	.refresh-btn:active {
		transform: rotate(180deg);
	}

	.section-title {
		font-size: 30rpx;
		font-weight: 600;
		color: #333333;
		margin-bottom: 20rpx;
		padding: 0 10rpx;
		display: flex;
		align-items: center;
	}

	.alert-badge {
		background-color: #F56C6C;
		color: #FFFFFF;
		font-size: 22rpx;
		border-radius: 30rpx;
		padding: 2rpx 12rpx;
		margin-left: 12rpx;
		font-weight: normal;
		min-width: 32rpx;
		text-align: center;
	}

	/* 告警信息列表 */
	.alerts-section {
		margin: 0 30rpx;
		background-color: #FFFFFF;
		border-radius: 20rpx;
		padding: 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);
	}

	.alerts-list {
		display: flex;
		flex-direction: column;
	}

	.alert-item {
		display: flex;
		align-items: center;
		padding: 24rpx 20rpx;
		border-radius: 12rpx;
		margin-bottom: 16rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		position: relative;
	}

	.alert-urgent {
		background-color: #FEF3F3;
		border-left: 4rpx solid #F56C6C;
	}

	.alert-warning {
		background-color: #FFF8E6;
		border-left: 4rpx solid #E6A23C;
	}

	.alert-info {
		background-color: #F2FAF5;
		border-left: 4rpx solid #67C23A;
	}

	.alert-item-icon {
		width: 50rpx;
		height: 50rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 16rpx;
	}

	.alert-item-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.alert-item-type {
		font-size: 28rpx;
		color: #333333;
		font-weight: 500;
		margin-bottom: 8rpx;
	}

	.alert-item-level {
		font-size: 24rpx;
		color: #999999;
	}

	.alert-item-time {
		font-size: 24rpx;
		color: #999999;
		margin-left: 16rpx;
		min-width: 100rpx;
		text-align: right;
	}

	.empty-alert {
		padding: 60rpx 0;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.empty-text {
		font-size: 28rpx;
		color: #999999;
	}
</style>
