#!D:/IDE/anaconda3/envs python
# -*- coding: UTF-8 -*-
"""
 @Author: Administrator
 @FileName：HitBotControlView.py\n
 @DateTime: 2025/7/17 17:26\n
 @Author  ：xsh
"""
from PyQt5 import Qt
from AppSettings.Settings import SIGNAL_CONNECTION_TYPE
from AppCore.Levels import *
from AppCore.DBModels import *
from AppUtils.UiUtils import UiUtils
from AppInterfaces.UiInterface import UiInterface, AppUiProperty, AppUtils, AppConvert
from AppInterfaces.globalSlot import globalSlot, AppSlot

class HitBotControlView(Qt.QWidget, UiInterface):
    valueChanged: Qt.pyqtSignal = Qt.pyqtSignal(object)
    valueUpdated: Qt.pyqtSignal = Qt.pyqtSignal(object)
    Model: HitBotModel = None
    ClickTimer: Qt.QTimer = None  # 添加定时器属性
    current_button: Qt.QPushButton
    # UI组件属性声明
    # XY平面按钮
    btn_y_plus: Qt.QPushButton = None  # Y+按钮
    btn_y_minus: Qt.QPushButton = None  # Y-按钮
    btn_x_plus: Qt.QPushButton = None  # X+按钮
    btn_x_minus: Qt.QPushButton = None  # X-按钮
    # ZR平面按钮
    btn_z_plus: Qt.QPushButton = None  # Z+按钮
    btn_z_minus: Qt.QPushButton = None  # Z-按钮
    btn_r_plus: Qt.QPushButton = None  # R+按钮
    btn_r_minus: Qt.QPushButton = None  # R-按钮
    # 角度按钮
    btn_angle1_plus: Qt.QPushButton = None  # A1+按钮
    btn_angle1_minus: Qt.QPushButton = None  # A1-按钮
    btn_angle2_plus: Qt.QPushButton = None  # A2+按钮
    btn_angle2_minus: Qt.QPushButton = None  # A2-按钮

    move_type_label: Qt.QLabel = None
    move_type_button: Qt.QComboBox = None
    speed_label: Qt.QLabel = None  # 速度显示标签
    move_speed_button: Qt.QComboBox = None  # 移动速度
    gripper_on_button: Qt.QPushButton = None  # 夹抓打开
    gripper_off_button: Qt.QPushButton = None  # 夹抓关闭
    move_step_label: Qt.QLabel = None  # 移动步长标签
    move_step_button: Qt.QComboBox = None  # 移动步长
    angle_step_label: Qt.QLabel = None  # 角度步长
    angle_step_button: Qt.QComboBox = None  # 角度步长

    def __init__(self, parent: Qt.QWidget = None):
        super(HitBotControlView, self).__init__(parent=parent)
        self.Initialization('HitBotControlView', self, parent)
        self.initWidgetStyle()

    def initWidgetStyle(self):
        from AppUtils.UiUtils import UiUtils
        # self.setStyleSheet(UiUtils.getWidgetStyle())

    def initValue(self):
        super(HitBotControlView, self).initValue()
        self.current_button = None
        self.initModel()
        self.initClickTimer()

    def initProperty(self):
        super(HitBotControlView, self).initProperty()

    @property
    def has_current_button(self) -> bool:
        return hasattr(self, 'current_button') and isinstance(self.current_button, Qt.QPushButton)

    @property
    def has_ClickTimer(self):
        return hasattr(self, 'ClickTimer') and isinstance(self.ClickTimer, Qt.QTimer)

    @property
    def has_Model(self):
        return hasattr(self, 'Model') and isinstance(self.Model, HitBotModelInterface)

    def initModel(self):
        if not self.has_Model:
            self.Model = HitBotModel.instance(movetype=2, xPosition=0.0, yPosition=0.0, zPosition=0.0, rPosition=0.0,
                                              speed=300.0, efg_distance=None)

    def initClickTimer(self):
        # 初始化定时器
        if self.has_ClickTimer:
            return
        self.ClickTimer = Qt.QTimer()
        self.ClickTimer.setInterval(200)  # 设置超时时间为200ms
        self.ClickTimer.timeout.connect(self._on_timer_timeout)

    def initLayouts(self):
        super(HitBotControlView, self).initLayouts()
        if not self.hasControl or self.layout() is not None:
            return
        box: Qt.QGroupBox = Qt.QGroupBox()
        box_layout: Qt.QVBoxLayout = Qt.QVBoxLayout()
        box_layout.setSpacing(5)  # 设置布局间距
        box_layout.setContentsMargins(5, 20, 5, 5)
        # box_layout.setAlignment(Qt.Qt.AlignTop)
        box.setTitle('机械臂位置')
        # 创建主布局
        main_layout = Qt.QVBoxLayout()
        main_layout.setSpacing(5)  # 设置布局间距
        # main_layout.setAlignment(Qt.Qt.AlignTop)
        # 创建三个十字布局的按钮组（横向排列）
        joystick_layout = Qt.QHBoxLayout()
        joystick_layout.setSpacing(5)  # 设置摇杆之间的间距

        # XY平面按钮组
        xy_layout = Qt.QGridLayout()
        xy_layout.setSpacing(5)  # 设置按钮间距
        self.btn_y_plus     = Qt.QPushButton("Y+ ▲")
        self.btn_y_minus    = Qt.QPushButton("Y- ▼")
        self.btn_x_plus     = Qt.QPushButton("X+ ▶")
        self.btn_x_minus    = Qt.QPushButton("X- ◀")

        # 为按钮设置固定大小（不使用样式表）
        for btn in [self.btn_y_plus, self.btn_y_minus, self.btn_x_plus, self.btn_x_minus]:
            btn.setFixedSize(70, 70)

        # 创建圆形布局
        xy_layout.setContentsMargins(20, 20, 20, 20)
        xy_layout.addWidget(self.btn_y_plus, 0, 1)
        xy_layout.addWidget(self.btn_y_minus, 2, 1)
        xy_layout.addWidget(self.btn_x_plus, 1, 2)
        xy_layout.addWidget(self.btn_x_minus, 1, 0)

        # ZR平面按钮组
        zr_layout = Qt.QGridLayout()
        zr_layout.setSpacing(5)
        self.btn_z_plus     = Qt.QPushButton("Z+ ▲")
        self.btn_z_minus    = Qt.QPushButton("Z- ▼")
        self.btn_r_plus     = Qt.QPushButton("R+ ▶")
        self.btn_r_minus    = Qt.QPushButton("R- ◀")

        self.btn_z_plus   .setProperty('nav', 'control')
        self.btn_z_minus  .setProperty('nav', 'control')
        self.btn_r_plus   .setProperty('nav', 'control')
        self.btn_r_minus  .setProperty('nav', 'control')
        self.btn_y_plus   .setProperty('nav', 'control')
        self.btn_y_minus  .setProperty('nav', 'control')
        self.btn_x_plus   .setProperty('nav', 'control')
        self.btn_x_minus  .setProperty('nav', 'control')

        # 为按钮设置固定大小（不使用样式表）
        for btn in [self.btn_z_plus, self.btn_z_minus, self.btn_r_plus, self.btn_r_minus]:
            btn.setFixedSize(70, 70)

        # 创建圆形布局
        zr_layout.setContentsMargins(20, 20, 20, 20)
        zr_layout.addWidget(self.btn_z_plus, 0, 1)
        zr_layout.addWidget(self.btn_z_minus, 2, 1)
        zr_layout.addWidget(self.btn_r_plus, 1, 2)
        zr_layout.addWidget(self.btn_r_minus, 1, 0)

        # 创建三个容器widget来包含每个圆形布局
        xy_widget = Qt.QWidget()
        xy_widget.setObjectName("xy_widget")
        xy_widget.setLayout(xy_layout)

        zr_widget = Qt.QWidget()
        zr_widget.setObjectName("zr_widget")
        zr_widget.setLayout(zr_layout)

        self.btn_z_plus .setStyleSheet(UiUtils.getControlButtonStyle())
        self.btn_z_minus.setStyleSheet(UiUtils.getControlButtonStyle())
        self.btn_r_plus .setStyleSheet(UiUtils.getControlButtonStyle())
        self.btn_r_minus.setStyleSheet(UiUtils.getControlButtonStyle())
        self.btn_y_plus .setStyleSheet(UiUtils.getControlButtonStyle())
        self.btn_y_minus.setStyleSheet(UiUtils.getControlButtonStyle())
        self.btn_x_plus .setStyleSheet(UiUtils.getControlButtonStyle())
        self.btn_x_minus.setStyleSheet(UiUtils.getControlButtonStyle())

        xy_widget.setStyleSheet(UiUtils.getControlWidgetStyle())
        zr_widget.setStyleSheet(UiUtils.getControlWidgetStyle())
        # 添加三个十字布局到横向布局
        joystick_layout.addWidget(xy_widget)
        joystick_layout.addWidget(zr_widget)

        # 创建控制面板（横向排列）
        control_panel = Qt.QWidget()

        self.gripper_on_button  = Qt.QPushButton('夹抓打开', self)
        self.gripper_off_button = Qt.QPushButton('夹抓关闭', self)
        self.move_type_label    = Qt.QLabel('移动模式', self)
        self.move_type_button   = Qt.QComboBox(self)
        self.speed_label        = Qt.QLabel('移动速度', self)
        self.move_speed_button  = Qt.QComboBox(self)
        self.move_step_label    = Qt.QLabel('移动步长', self)
        self.move_step_button   = Qt.QComboBox(self)
        self.angle_step_label   = Qt.QLabel('旋转角度', self)
        self.angle_step_button  = Qt.QComboBox(self)

        self.move_type_button   .addItems(list(HitBotMoveType.toItem().keys()))
        self.move_speed_button  .addItems(['50.0', '10.0', '100.0', '150.0', '200.0', '300.0'])
        self.move_step_button   .addItems(['1.0mm', '0.1mm', '0.2mm', '0.5mm', '2.0mm', '5.0mm', '10.0mm'])
        self.angle_step_button  .addItems(['90', '45', '180'])
        self.move_type_button.setCurrentText(HitBotMoveType.toString(HitBotMoveType.LMove_XYZR_G))
        control_panel_layout: Qt.QVBoxLayout = Qt.QVBoxLayout()
        control_panel_layout.setSpacing(1)
        control_panel_layout.setContentsMargins(5, 5, 5, 5)

        row_1: Qt.QHBoxLayout = Qt.QHBoxLayout()
        row_2: Qt.QHBoxLayout = Qt.QHBoxLayout()
        row_3: Qt.QHBoxLayout = Qt.QHBoxLayout()
        row_1.setSpacing(1)
        row_1.setContentsMargins(5, 5, 5, 5)
        row_2.setSpacing(1)
        row_2.setContentsMargins(5, 5, 5, 5)
        row_3.setSpacing(1)
        row_3.setContentsMargins(5, 5, 5, 5)

        row_1.addWidget(self.move_type_label)
        row_1.addWidget(self.move_type_button)
        row_1.addWidget(self.speed_label)
        row_1.addWidget(self.move_speed_button)

        row_2.addWidget(self.move_step_label)
        row_2.addWidget(self.move_step_button)
        row_2.addWidget(self.angle_step_label)
        row_2.addWidget(self.angle_step_button)

        row_3.addWidget(self.gripper_on_button)
        row_3.addWidget(self.gripper_off_button)

        control_panel_layout.addLayout(row_1)
        control_panel_layout.addLayout(row_2)
        control_panel_layout.addLayout(row_3)
        control_panel.setLayout(control_panel_layout)

        box_layout.addLayout(joystick_layout)
        box_layout.addWidget(control_panel)
        box.setLayout(box_layout)

        # 添加所有布局到主布局
        main_layout.addWidget(box)

        self.move_type_label    .setStyleSheet(UiUtils.getButtonStyle())
        self.move_type_button   .setStyleSheet(UiUtils.getButtonStyle())
        self.speed_label        .setStyleSheet(UiUtils.getButtonStyle())
        self.move_speed_button  .setStyleSheet(UiUtils.getButtonStyle())
        self.gripper_on_button  .setStyleSheet(UiUtils.getButtonStyle())
        self.gripper_off_button .setStyleSheet(UiUtils.getButtonStyle())
        self.move_step_label    .setStyleSheet(UiUtils.getButtonStyle())
        self.move_step_button   .setStyleSheet(UiUtils.getButtonStyle())
        self.angle_step_label   .setStyleSheet(UiUtils.getButtonStyle())
        self.angle_step_button  .setStyleSheet(UiUtils.getButtonStyle())

        self.move_type_label    .setFixedWidth(100)
        self.move_type_button   .setFixedWidth(200)
        self.speed_label        .setFixedWidth(100)
        self.move_speed_button  .setFixedWidth(200)
        self.gripper_on_button  .setMinimumWidth(100)
        self.gripper_off_button .setMinimumWidth(100)
        self.move_step_label    .setFixedWidth(100)
        self.move_step_button   .setFixedWidth(200)
        self.angle_step_label   .setFixedWidth(100)
        self.angle_step_button  .setFixedWidth(200)
        # 设置主布局
        self.setLayout(main_layout)

    def initConnect(self):
        super(HitBotControlView, self).initConnect()
        TYPE: Qt.Qt.ConnectionType = Qt.Qt.ConnectionType(Qt.Qt.AutoConnection | Qt.Qt.UniqueConnection)
        AppSlot.currentHitBotDataChanged.connect(slot=self.SlotCurrentHitBotDataChanged, type=TYPE)
        self.valueUpdated.connect(slot=self.slot_valueUpdated, type=TYPE)
        # 连接XY平面按钮信号
        self.btn_y_plus.pressed.connect(lambda: self._on_button_pressed(self.btn_y_plus))
        self.btn_y_plus.released.connect(self._on_button_released)
        self.btn_y_minus.pressed.connect(lambda: self._on_button_pressed(self.btn_y_minus))
        self.btn_y_minus.released.connect(self._on_button_released)
        self.btn_x_plus.pressed.connect(lambda: self._on_button_pressed(self.btn_x_plus))
        self.btn_x_plus.released.connect(self._on_button_released)
        self.btn_x_minus.pressed.connect(lambda: self._on_button_pressed(self.btn_x_minus))
        self.btn_x_minus.released.connect(self._on_button_released)

        # 连接ZR平面按钮信号
        self.btn_z_plus.pressed.connect(lambda: self._on_button_pressed(self.btn_z_plus))
        self.btn_z_plus.released.connect(self._on_button_released)
        self.btn_z_minus.pressed.connect(lambda: self._on_button_pressed(self.btn_z_minus))
        self.btn_z_minus.released.connect(self._on_button_released)
        self.btn_r_plus.pressed.connect(lambda: self._on_button_pressed(self.btn_r_plus))
        self.btn_r_plus.released.connect(self._on_button_released)
        self.btn_r_minus.pressed.connect(lambda: self._on_button_pressed(self.btn_r_minus))
        self.btn_r_minus.released.connect(self._on_button_released)

        # self.gripper_on_button.clicked.connect(self._on_gripper_on_button)
        # self.gripper_off_button.clicked.connect(self._on_gripper_off_button)

    def _on_timer_timeout(self):
        # 定时器超时时的处理
        if self.current_button:
            if isinstance(self.current_button, Qt.QPushButton):
                # 根据按钮类型调用相应的处理函数
                if self.current_button in [self.btn_y_plus, self.btn_y_minus, self.btn_x_plus, self.btn_x_minus]:
                    if self.current_button == self.btn_y_plus:
                        self._on_xy_button_pressed(0, 1)
                    elif self.current_button == self.btn_y_minus:
                        self._on_xy_button_pressed(0, -1)
                    elif self.current_button == self.btn_x_plus:
                        self._on_xy_button_pressed(1, 0)
                    elif self.current_button == self.btn_x_minus:
                        self._on_xy_button_pressed(-1, 0)
                elif self.current_button in [self.btn_z_plus, self.btn_z_minus, self.btn_r_plus, self.btn_r_minus]:
                    if self.current_button == self.btn_z_plus:
                        self._on_zr_button_pressed(1, 0)

                    elif self.current_button == self.btn_z_minus:
                        self._on_zr_button_pressed(-1, 0)
                    elif self.current_button == self.btn_r_plus:
                        self._on_zr_button_pressed(0, 1)
                    elif self.current_button == self.btn_r_minus:
                        self._on_zr_button_pressed(0, -1)

    def _on_button_pressed(self, button):
        # 按钮按下时的处理
        self.current_button = button
        self._on_timer_timeout()
        self.ClickTimer.start()

    def _on_button_released(self):
        # 按钮释放时的处理
        self.ClickTimer.stop()
        self.current_button = None
        self._update_robot_position()

    def _on_xy_button_pressed(self, x, y):
        self.initModel()
        step = self.get_move_step_value()  # 获取当前步长
        if not isinstance(step, (float, int)):
            return
        if not self.Model.has_xPosition:
            self.Model.xPosition = step
        else:
            if x > 0:
                self.Model.xPosition += step
            elif x < 0:
                self.Model.xPosition -= step
        if not self.Model.has_yPosition:
            self.Model.yPosition = step
        else:
            if y > 0:
                self.Model.yPosition += step
            elif y < 0:
                self.Model.yPosition -= step
        self._update_robot_position()

    def _on_zr_button_pressed(self, z, r):
        self.initModel()
        z_step = self.get_move_step_value()  # 获取当前步长
        r_step = self.get_angle_step_value()
        if not isinstance(z_step, (float, int)):
            return
        if not self.Model.has_zPosition:
            self.Model.zPosition = z_step
        else:
            if z > 0:
                self.Model.zPosition += z_step  # Z轴使用步长控件值
            elif z < 0:
                self.Model.zPosition -= z_step  # Z轴使用步长控件值
        if not isinstance(r_step, (float, int)):
            return
        if not self.Model.has_rPosition:
            self.Model.rPosition = r_step
        else:
            if r > 0:
                self.Model.rPosition += r_step  # R轴保持5.0的步长
            elif r < 0:
                self.Model.rPosition -= r_step  # R轴保持5.0的步长
        self._update_robot_position()

    def _on_gripper_on_button(self):
        self.initModel()
        self.Model.setGripperON()

    def _on_gripper_off_button(self):
        self.initModel()
        self.Model.setGripperOFF()

    def get_move_step_value(self) -> float:
        # 获取当前选择的步长值
        step_text = self.move_step_button.currentText()
        return AppConvert.ObjectConvert(step_text.replace('mm', ''), float)

    def get_move_speed_value(self) -> float:
        step_text = self.move_speed_button.currentText()
        return float(step_text.replace('mm', ''))

    def get_angle_step_value(self) -> float:
        step_text = self.angle_step_button.currentText()
        return float(step_text.replace('mm', ''))

    def get_move_type_value(self) -> int:
        text = self.move_type_button.currentText()
        return HitBotMoveType.toValue(text)

    def slot_valueUpdated(self, buffer: HitBotModelInterface):
        self.setModel(buffer)
    def SlotCurrentHitBotDataChanged(self, data, model):
        self.initModel()
        if isinstance(data, HitBotModelInterface):
            self.setModel(data)
        elif isinstance(model, HitBotModelInterface):
            self.setModel(model)

    def setModel(self, model: HitBotModelInterface):
        if not model or not isinstance(model, HitBotModelInterface):
            return
        self.initModel()
        self.Model.as_field(model.to_field())

    def get_robot_position(self) -> HitBotModelInterface:
        self.initModel()
        # 更新RequestData的值
        speed: float = self.get_move_speed_value()
        movetype: float = self.get_move_type_value()
        if isinstance(speed, (float, int)):
            self.Model.speed = speed
        if isinstance(movetype, (float, int)):
            self.Model.movetype = movetype
        self.Model.efg_distance = None


        return self.Model.copy()

    def _update_robot_position(self):
        self.valueChanged.emit(self.get_robot_position())

    def deleConnect(self):
        super(HitBotControlView, self).deleConnect()

