#!/usr/bin/env python3
# 无人机状态卡片组件

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel,
                            QFrame, QGridLayout)
from PyQt5.QtCore import Qt, pyqtSignal, QTimer
from PyQt5.QtGui import QFont, QColor, QPalette
import math


class UAVCard(QFrame):
    """无人机状态卡片组件"""
    
    clicked = pyqtSignal(int)  # 点击信号，传递无人机ID
    
    def __init__(self, uav_id, parent=None):
        super().__init__(parent)
        self.uav_id = uav_id
        self.selected = False  # 选中状态
        self.setup_ui()
        self.setup_styles()
        
        # 关键修复：确保卡片初始化为可见状态
        self.setVisible(True)
        self.setEnabled(True)
        
    def mousePressEvent(self, event):
        """鼠标点击事件处理"""
        if event.button() == Qt.LeftButton:
            self.clicked.emit(self.uav_id)
        super().mousePressEvent(event)
        
    def setup_ui(self):
        """设置UI布局"""
        # 设置卡片样式 - 更小的现代圆角设计
        self.setFrameStyle(QFrame.NoFrame)
        self.setMinimumWidth(220)
        self.setMaximumWidth(250)
        self.setMinimumHeight(180)  # 恢复较小高度，因为移除了按钮
        
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(6)
        
        # 标题栏
        title_layout = QHBoxLayout()
        title_layout.setContentsMargins(0, 0, 0, 0)
        
        # 无人机图标和ID
        icon_label = QLabel("✈️")
        icon_label.setFont(QFont("Arial", 20))
        title_layout.addWidget(icon_label)
        
        self.title_label = QLabel(f"Drone {self.uav_id}")
        title_font = QFont()
        title_font.setBold(True)
        title_font.setPointSize(18)
        self.title_label.setFont(title_font)
        title_layout.addWidget(self.title_label)
        
        title_layout.addStretch()
        
        # 连接状态指示器
        self.connection_label = QLabel("●")
        self.connection_label.setAlignment(Qt.AlignRight)
        self.connection_label.setFont(QFont("Arial", 14))
        title_layout.addWidget(self.connection_label)
        
        main_layout.addLayout(title_layout)
        
        # 分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        separator.setStyleSheet("background-color: #e0e0e0; margin: 4px 0;")
        main_layout.addWidget(separator)
        
        # 状态信息网格布局
        grid_layout = QGridLayout()
        grid_layout.setContentsMargins(0, 4, 0, 4)
        grid_layout.setSpacing(4)
        grid_layout.setColumnStretch(1, 1)
        
        # 第一行：电量和飞行模式
        grid_layout.addWidget(QLabel("🔋 电压:"), 0, 0)
        self.battery_label = QLabel("0.00 V")
        grid_layout.addWidget(self.battery_label, 0, 1)
        
        grid_layout.addWidget(QLabel("🔄 模式:"), 1, 0)
        self.mode_label = QLabel("未知")
        grid_layout.addWidget(self.mode_label, 1, 1)
        
        # 第二行：本地位置
        grid_layout.addWidget(QLabel("📍 本地:"), 2, 0)
        self.local_pos_label = QLabel("X: 0.00, Y: 0.00, Z: 0.00")
        grid_layout.addWidget(self.local_pos_label, 2, 1)
        
        # 第三行：全局位置
        grid_layout.addWidget(QLabel("🌍 全局:"), 3, 0)
        self.global_pos_label = QLabel("Lat: 0.000, Lon: 0.000, Alt: 0.00")
        grid_layout.addWidget(self.global_pos_label, 3, 1)
        
        # 第四行：连接状态
        grid_layout.addWidget(QLabel("📡 连接:"), 4, 0)
        self.status_label = QLabel("未连接")
        grid_layout.addWidget(self.status_label, 4, 1)
        
        main_layout.addLayout(grid_layout)
        
    def setup_styles(self):
        """设置样式"""
        # 设置基础样式
        self.setStyleSheet("""
            UAVCard {
                background-color: #ffffff;
                border: 1px solid #e0e0e0;
                border-radius: 10px;
                padding: 0px;
            }
            QLabel {
                color: #333333;
                font-size: 11px;
            }
            QLabel[objectName="title_label"] {
                color: #2c3e50;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton {
                background-color: #4a90e2;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 4px 6px;
                font-size: 9px;
                font-weight: bold;
                min-height: 20px;
            }
            QPushButton:hover {
                background-color: #357abd;
            }
            QPushButton:pressed {
                background-color: #2c5aa0;
            }
            QPushButton:disabled {
                background-color: #cccccc;
                color: #666666;
            }
        """)
        
        # 设置连接状态颜色
        self.set_connection_status(False)
        
    def connect_button_signals(self):
        """连接按钮信号"""
        self.takeoff_btn.clicked.connect(lambda: self.on_button_clicked("takeoff"))
        self.hover_btn.clicked.connect(lambda: self.on_button_clicked("hover"))
        self.land_btn.clicked.connect(lambda: self.on_button_clicked("land"))
        self.return_btn.clicked.connect(lambda: self.on_button_clicked("return"))
        self.lock_btn.clicked.connect(lambda: self.on_button_clicked("lock"))
        self.select_btn.clicked.connect(lambda: self.on_button_clicked("select"))
        self.deselect_btn.clicked.connect(lambda: self.on_button_clicked("deselect"))
        
    def on_button_clicked(self, action):
        """按钮点击处理"""
        print(f"UAV {self.uav_id}: {action} button clicked")
        # 这里可以添加实际的无人机控制逻辑
        
        # 处理选中/不选中按钮
        if action == "select":
            self.set_selected(True)
        elif action == "deselect":
            self.set_selected(False)
            
    def set_selected(self, selected):
        """设置选中状态"""
        self.selected = selected
        if selected:
            self.setStyleSheet("""
                UAVCard {
                    background-color: #ffffff;
                    border: 2px solid #ff6b6b;
                    border-radius: 10px;
                    padding: 0px;
                }
                QLabel {
                    color: #333333;
                    font-size: 11px;
                }
                QLabel[objectName="title_label"] {
                    color: #2c3e50;
                    font-size: 14px;
                    font-weight: bold;
                }
            """)
        else:
            self.set_connection_status(self.uav_data.get('connected', False) if hasattr(self, 'uav_data') else False)
        
    def set_connection_status(self, connected):
        """设置连接状态"""
        if connected:
            self.connection_label.setStyleSheet("color: #27ae60; font-weight: bold;")
            self.status_label.setText("已连接")
            self.status_label.setStyleSheet("color: #27ae60; font-weight: bold;")
            # 连接状态下的卡片样式
            if not self.selected:
                self.setStyleSheet("""
                    UAVCard {
                        background-color: #ffffff;
                        border: 2px solid #27ae60;
                        border-radius: 10px;
                        padding: 0px;
                    }
                    QLabel {
                        color: #333333;
                        font-size: 11px;
                    }
                    QLabel[objectName="title_label"] {
                        color: #2c3e50;
                        font-size: 14px;
                        font-weight: bold;
                    }
                    QPushButton {
                        background-color: #4a90e2;
                        color: white;
                        border: none;
                        border-radius: 6px;
                        padding: 4px 6px;
                        font-size: 9px;
                        font-weight: bold;
                        min-height: 20px;
                    }
                    QPushButton:hover {
                        background-color: #357abd;
                    }
                    QPushButton:pressed {
                        background-color: #2c5aa0;
                    }
                    QPushButton:disabled {
                        background-color: #cccccc;
                        color: #666666;
                    }
                """)
        else:
            self.connection_label.setStyleSheet("color: #e74c3c; font-weight: bold;")
            self.status_label.setText("未连接")
            self.status_label.setStyleSheet("color: #e74c3c; font-weight: bold;")
            # 未连接状态下的卡片样式
            if not self.selected:
                self.setStyleSheet("""
                    UAVCard {
                        background-color: #f8f9fa;
                        border: 1px solid #e0e0e0;
                        border-radius: 10px;
                        padding: 0px;
                    }
                    QLabel {
                        color: #666666;
                        font-size: 11px;
                    }
                    QLabel[objectName="title_label"] {
                        color: #7f8c8d;
                        font-size: 14px;
                        font-weight: bold;
                    }
                    QPushButton {
                        background-color: #cccccc;
                        color: #666666;
                        border: none;
                        border-radius: 6px;
                        padding: 4px 6px;
                        font-size: 9px;
                        font-weight: bold;
                        min-height: 20px;
                    }
                    QPushButton:hover {
                        background-color: #bbbbbb;
                    }
                    QPushButton:pressed {
                        background-color: #aaaaaa;
                    }
                """)
            
    def set_battery_voltage(self, voltage):
        """设置电池电压"""
        self.battery_label.setText(f"{voltage:.2f} V")
        
        # 根据电压设置颜色和图标
        if voltage >= 12.0:
            color = "#27ae60"  # 绿色
        elif voltage >= 11.0:
            color = "#f39c12"  # 橙色
        else:
            color = "#e74c3c"  # 红色
            
        self.battery_label.setStyleSheet(f"color: {color}; font-weight: bold;")
        
    def set_flight_mode(self, mode):
        """设置飞行模式"""
        # 如果mode已经是字符串，直接使用
        if isinstance(mode, str):
            self.mode_label.setText(mode)
        else:
            # 如果是数字，转换为字符串（使用与控制器一致的映射）
            mode_texts = {
                0: "手动",
                1: "高度",
                2: "位置",
                3: "任务",
                4: "保持",
                5: "返回",
                6: "Offboard",
                7: "稳定",
                8: "起飞",
                9: "降落",
                10: "跟随",
                11: "盘旋",
                12: "垂直起降起飞",
                13: "自动准备",
                14: "自动预降落",
                15: "下降",
                16: "终止",
                17: "Offboard2",
            }
            mode_text = mode_texts.get(mode, f"未知({mode})")
            self.mode_label.setText(mode_text)
        
    def set_local_position(self, x, y, z):
        """设置本地位置"""
        self.local_pos_label.setText(f"X: {x:.2f}, Y: {y:.2f}, Z: {z:.2f}")
        
    def set_global_position(self, lat, lon, alt):
        """设置全局位置"""
        self.global_pos_label.setText(f"Lat: {lat:.3f}, Lon: {lon:.3f}, Alt: {alt:.2f}")
        
    def update_data(self, data):
        """更新所有数据"""
        if data.get('connected', False):
            self.set_connection_status(True)
            # 兼容旧字段名 'battery' 和新字段名 'battery_voltage'
            voltage = data.get('battery_voltage', data.get('battery', 0))
            self.set_battery_voltage(voltage)
            # 兼容旧字段名 'flight_mode_str' 和新字段名 'flight_mode'
            flight_mode = data.get('flight_mode_str', data.get('flight_mode', 'Unknown'))
            self.set_flight_mode(flight_mode)
            self.set_local_position(
                data.get('local_x', 0),
                data.get('local_y', 0),
                data.get('local_z', 0)
            )
            self.set_global_position(
                data.get('global_lat', 0),
                data.get('global_lon', 0),
                data.get('global_alt', 0)
            )
        else:
            self.set_connection_status(False)
            # 重置为默认值
            self.set_battery_voltage(0)
            self.set_flight_mode(0)
            self.set_local_position(0, 0, 0)
            self.set_global_position(0, 0, 0)