<template>

	<el-row>
		<el-col :span="24">
			<div class="grid-content">
				<!--顶部-->
				<el-row>
					<el-col :span="24">
						<div class="top">

						</div>
					</el-col>
				</el-row>
				<!--	中间-->
				<el-row>
					<el-col :span="24">

					</el-col>
				</el-row>
				<!--	底部-->

				<el-row>
					<el-col :span="24">

					</el-col>
				</el-row>

			</div>
		</el-col>
	</el-row>


</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { Connection, FullScreen, VideoCamera, Message, Back } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

const route = useRoute()

// 获取系统ID
const sysId = computed(() => {
	const params = route.params as Record<string, any>
	return 'id' in params ? (Array.isArray(params.id) ? params.id[0] : params.id ?? '') : ''
})

// 状态数据
const state = reactive({
	POWER_STATUS: { data: null as any },
	SYS_STATUS: { data: null as any },
	GPS_STATUS: { data: null as any },
	HEARTBEAT: { data: null as any },
	ATTITUDE: { data: null as any },
	VFR_HUD: { data: null as any },
	GLOBAL_POSITION_INT: { data: null as any },
	MISSION_CURRENT: { data: null as any },
	BATTERY_STATUS: { data: null as any },
	EKF_STATUS_REPORT: { data: null as any }
})

// 视频流URL
const videoUrl = ref('')
// WebSocket连接
const ws = ref<WebSocket | null>(null)
// 消息日志
const messages = ref<string[]>([])
// 连接状态
const isConnected = ref(false)
// 地图实例
const mapInstance = ref<any>(null)
// 地图容器引用
const mapContainer = ref<HTMLElement | null>(null)
// 计算属性
const systemStatusText = computed(() => {
	if (!state.HEARTBEAT.data) return '未知'
	const status = state.HEARTBEAT.data.system_status
	if (status === 3) return '待机'
	if (status === 4) return '活动中'
	if (status === 5) return '关键'
	return '未知'
})

const systemStatusType = computed(() => {
	if (!state.HEARTBEAT.data) return 'info'
	const status = state.HEARTBEAT.data.system_status
	if (status === 3) return 'warning'
	if (status === 4) return 'success'
	if (status === 5) return 'danger'
	return 'info'
})

const ekfHealth = computed(() => {
	return state.EKF_STATUS_REPORT.data?.health || 0
})

const ekfStatus = computed(() => {
	const health = ekfHealth.value
	if (health > 80) return 'success'
	if (health > 50) return 'warning'
	return 'exception'
})

const horizonStyle = computed(() => {
	const pitch = state.ATTITUDE.data?.pitch || 0
	const roll = state.ATTITUDE.data?.roll || 0
	return {
		transform: `rotate(${roll}deg) translateY(${pitch * 5}px)`
	}
})

const yawStyle = computed(() => {
	const yaw = state.ATTITUDE.data?.yaw || 0
	return {
		transform: `rotate(${yaw}deg)`
	}
})

// 方法
function getFixType(type: number) {
	const types = ['无', '无', '2D', '3D']
	return types[type] || '未知'
}

function getSystemMode(mode: number) {
	// 这里需要根据MAVLink协议解析模式
	return mode ? `模式 ${mode}` : '未知'
}

function getFlightStatus(status: number) {
	const statusMap = {
		0: '未知',
		1: '启动',
		2: '校准',
		3: '待机',
		4: '活动中',
		5: '关键',
		6: '紧急'
	}
	return statusMap[status] || '未知'
}

function connectWebSocket() {
	const wsUrl = `ws://localhost:8000/ws/mavlink/heartbeat/1/`
	ws.value = new WebSocket(wsUrl)

	ws.value.onopen = () => {
		isConnected.value = true
		addMessage('WebSocket 已连接')
	}

	ws.value.onmessage = (event) => {
		try {
			const data = JSON.parse(event.data)
			handleMavlinkMessage(data)
		} catch (error) {
			console.error('消息解析失败:', error)
			addMessage('消息解析失败')
		}
	}

	ws.value.onclose = () => {
		isConnected.value = false
		addMessage('WebSocket 已断开')
	}

	ws.value.onerror = (err) => {
		addMessage('WebSocket 错误')
	}
}

function handleMavlinkMessage(data: any) {
	if (!data.msg_type) return

	// 更新对应状态
	if (state[data.msg_type as keyof typeof state] !== undefined) {
		state[data.msg_type as keyof typeof state].data = data
	}

	// 特殊处理某些消息
	switch (data.msg_type) {
		case 'HEARTBEAT':
			addMessage(`心跳: 系统状态 ${getFlightStatus(data.system_status)}`)
			break
		case 'GPS_STATUS':
			if (data.fix_type >= 3) {
				updateMapPosition()
			}
			break
	}
}

function sendHeartbeat() {
	if (ws.value && isConnected.value) {
		ws.value.send(JSON.stringify({ type: 'heartbeat' }))
		addMessage('已发送心跳检测')
	}
}

function addMessage(msg: string) {
	messages.value.push(msg)
	if (messages.value.length > 100) {
		messages.value.shift()
	}
}

function formatTime(date: Date) {
	return date.toLocaleTimeString()
}

function toggleFullscreen() {
	if (!document.fullscreenElement) {
		document.documentElement.requestFullscreen()
	} else {
		if (document.exitFullscreen) {
			document.exitFullscreen()
		}
	}
}

function initMap() {
	if (!mapContainer.value) return

	// 初始化地图
	mapInstance.value = echarts.init(mapContainer.value)

	const option = {
		backgroundColor: 'transparent',
		tooltip: {
			trigger: 'item',
			formatter: '{b}'
		},
		series: [{
			type: 'graph',
			layout: 'none',
			coordinateSystem: 'none',
			symbolSize: 50,
			roam: true,
			label: {
				show: true
			},
			edgeSymbol: ['circle', 'arrow'],
			edgeSymbolSize: [4, 10],
			edgeLabel: {
				fontSize: 20
			},
			data: [{
				name: '无人机',
				x: 0,
				y: 0,
				symbolSize: 30,
				itemStyle: {
					color: '#409EFF'
				}
			}],
			links: [],
			lineStyle: {
				opacity: 0.9,
				width: 2,
				curveness: 0
			}
		}]
	}

	mapInstance.value.setOption(option)
}

function updateMapPosition() {
	if (!mapInstance.value || !state.GLOBAL_POSITION_INT.data) return

	const lon = state.GLOBAL_POSITION_INT.data.lon / 1e7
	const lat = state.GLOBAL_POSITION_INT.data.lat / 1e7

	const option = {
		series: [{
			data: [{
				name: '无人机',
				x: lon,
				y: lat,
				symbolSize: 30,
				itemStyle: {
					color: '#409EFF'
				}
			}]
		}]
	}

	mapInstance.value.setOption(option)
}

// 无人机控制方法
function takeoff() {
	if (ws.value && isConnected.value) {
		ws.value.send(JSON.stringify({ command: 'takeoff' }))
		addMessage('发送起飞指令')
	}
}

function land() {
	if (ws.value && isConnected.value) {
		ws.value.send(JSON.stringify({ command: 'land' }))
		addMessage('发送降落指令')
	}
}

function returnToLaunch() {
	if (ws.value && isConnected.value) {
		ws.value.send(JSON.stringify({ command: 'rtl' }))
		addMessage('发送返航指令')
	}
}

function setMode(mode: string) {
	if (ws.value && isConnected.value) {
		ws.value.send(JSON.stringify({ command: 'set_mode', mode }))
		addMessage(`设置模式: ${mode}`)
	}
}

// 生命周期钩子
onMounted(() => {
	connectWebSocket()
	initMap()

	// 模拟视频流
	setTimeout(() => {
		videoUrl.value = 'https://example.com/uav-video-stream'
	}, 2000)
})

onUnmounted(() => {
	if (ws.value) ws.value.close()
	if (mapInstance.value) mapInstance.value.dispose()
})
</script>

<style scoped>
.grid-content {
	height: 100vh;
	width: 100%;
	background-image: url('uav/bg.png');
	background-size: cover; /* 确保图片覆盖整个区域 */
}
.top{
	height: 50px;
	width: 69%;
	background-color: #00dc82;
	margin-left: auto;
}
</style>

<route lang="json">
{
"meta": {
"layout": "notFound"
}
}
</route>
