#!D:/IDE/anaconda3/envs python
# -*- coding: UTF-8 -*-
"""
 @Author: Administrator
 @FileName：MotionControlView.py\n
 @DateTime: 2025/7/26 9:09\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


class MotionControlView(Qt.QWidget, UiInterface):
    valueChanged            : Qt.pyqtSignal = Qt.pyqtSignal(object)
    valueUpdated            : Qt.pyqtSignal = Qt.pyqtSignal(object)
    currentDataUpdated      : Qt.pyqtSignal = Qt.pyqtSignal(object)
    Model                   : SlideModel = 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-按钮


    x_move_step_label           : Qt.QLabel     = None  # 移动步长
    x_move_step_button          : Qt.QComboBox  = None  # 移动步长
    y_move_step_label           : Qt.QLabel     = None  # 移动步长
    y_move_step_button          : Qt.QComboBox  = None  # 移动步长
    z_move_step_label           : Qt.QLabel     = None  # 移动步长
    z_move_step_button          : Qt.QComboBox  = None  # 移动步长
    z_move_range_label          : Qt.QLabel             #
    z_move_range_Button         : Qt.QPushButton        #
    camera_view_button          : Qt.QPushButton        # 相机画面
    motion_init_button          : Qt.QPushButton        # 载玻台状态
    camera_image_button         : Qt.QPushButton        #
    low_scanning_slide_button   : Qt.QPushButton        # 快扫玻片
    scanning_slide_button       : Qt.QPushButton        # 扫描玻片
    oil_switch_button           : Qt.QPushButton        # 油泵开关
    def __init__(self, parent: Qt.QWidget = None):
        super(MotionControlView, self).__init__(parent=parent)
        self.Initialization('MotionControlView', self, parent)
        self.initWidgetStyle()

    def initWidgetStyle(self):
        from AppUtils.UiUtils import UiUtils
        self.setStyleSheet(UiUtils.getWindowStyle())
    def initValue(self):
        super(MotionControlView, self).initValue()
        self.current_button = None
        self.initModel()
        self.initClickTimer()

    def initProperty(self):
        super(MotionControlView, 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, SlideModelInterface)

    def initModel(self):
        if not self.has_Model:
            self.Model = SlideModel.instance(Position_X = 0, Position_Y = 0, Position_Z = 0, ObjectiveLevel = ObjectiveLevel.ObjectiveNone)

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

    def initLayouts(self):
        super(MotionControlView, self).initLayouts()
        if not self.hasControl or self.layout() is not None:
            return
        box: Qt.QGroupBox = Qt.QGroupBox(self)
        box_layout: Qt.QVBoxLayout = Qt.QVBoxLayout()
        box_layout.setSpacing(5)  # 设置布局间距
        box_layout.setContentsMargins(5, 20, 5, 5)
        box.setTitle('托盘位置')
        # 创建主布局
        main_layout = Qt.QVBoxLayout()
        main_layout.setSpacing(5)  # 设置布局间距
        # 创建三个十字布局的按钮组（横向排列）
        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)

        zr_widget.setStyleSheet(UiUtils.getControlWidgetStyle())
        xy_widget.setStyleSheet(UiUtils.getControlWidgetStyle())

        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())

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

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

        self.x_move_step_label          = Qt.QLabel('Ｘ移动步长', self)
        self.x_move_step_button         = Qt.QComboBox(self)
        self.y_move_step_label          = Qt.QLabel('Ｙ移动步长', self)
        self.y_move_step_button         = Qt.QComboBox(self)
        self.z_move_step_label          = Qt.QLabel('Ｚ移动步长', self)
        self.z_move_step_button         = Qt.QComboBox(self)
        self.z_move_range_label         = Qt.QLabel(self)
        self.camera_view_button         = Qt.QPushButton('相机画面切换', self)       # 相机画面
        self.z_move_range_Button        = Qt.QPushButton('清轴Ｚ轴限位', self)
        self.motion_init_button         = Qt.QPushButton('载玻台已初始', self)
        self.oil_switch_button          = Qt.QPushButton('打开油泵　　', self)        # 油泵开关
        self.camera_image_button        = Qt.QPushButton('多曝光图像　', self)
        self.x_move_step_button.addItems(['0.01mm','0.02mm','0.05mm','0.1mm','0.2mm','0.5mm','0.71mm','1.00mm', '1.12mm','1.21mm','2.00mm', '5.00mm'])
        self.y_move_step_button.addItems(['0.01mm','0.02mm','0.05mm','0.1mm','0.2mm','0.5mm','0.83mm','1.00mm', '1.12mm','1.21mm','2.00mm', '5.00mm'])
        self.z_move_step_button.addItems(['50','100','500','1000','2000','5000','10000','20000','50000','100000','200000','500000', '1000000','2000000','5000000',])
        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_4: 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_4.setSpacing(1)
        row_4.setContentsMargins(5, 5, 5, 5)

        row_1.addWidget(self.x_move_step_label          )
        row_1.addWidget(self.x_move_step_button         )
        row_1.addWidget(self.y_move_step_label          )
        row_1.addWidget(self.y_move_step_button         )
        row_2.addWidget(self.z_move_step_label          )
        row_2.addWidget(self.z_move_step_button         )
        row_2.addWidget(self.z_move_range_label         )
        row_2.addWidget(self.camera_view_button         )
        row_3.addWidget(self.z_move_range_Button        )
        row_3.addWidget(self.motion_init_button         )
        row_4.addWidget(self.oil_switch_button          )
        row_4.addWidget(self.camera_image_button        )


        self.camera_view_button     .setStyleSheet(UiUtils.getButtonStyle())
        self.x_move_step_label      .setStyleSheet(UiUtils.getButtonStyle())
        self.x_move_step_button     .setStyleSheet(UiUtils.getButtonStyle())
        self.y_move_step_label      .setStyleSheet(UiUtils.getButtonStyle())
        self.y_move_step_button     .setStyleSheet(UiUtils.getButtonStyle())
        self.z_move_step_label      .setStyleSheet(UiUtils.getButtonStyle())
        self.z_move_step_button     .setStyleSheet(UiUtils.getButtonStyle())
        self.z_move_range_label     .setStyleSheet(UiUtils.getButtonStyle())
        self.z_move_range_Button    .setStyleSheet(UiUtils.getButtonStyle())
        self.motion_init_button     .setStyleSheet(UiUtils.getButtonStyle())
        self.camera_image_button    .setStyleSheet(UiUtils.getButtonStyle())
        self.z_move_range_Button    .setStyleSheet(UiUtils.getButtonStyle())
        self.motion_init_button     .setStyleSheet(UiUtils.getButtonStyle())
        self.oil_switch_button      .setStyleSheet(UiUtils.getButtonStyle())
        self.camera_image_button    .setStyleSheet(UiUtils.getButtonStyle())
        self.x_move_step_label    .setFixedWidth(100)
        self.x_move_step_button   .setFixedWidth(200)
        self.y_move_step_label    .setFixedWidth(100)
        self.y_move_step_button   .setFixedWidth(200)
        self.z_move_step_label    .setFixedWidth(100)
        self.z_move_step_button   .setFixedWidth(200)
        self.z_move_range_label   .setFixedWidth(100)

        control_panel_layout.addLayout(row_1)
        control_panel_layout.addLayout(row_2)
        control_panel_layout.addLayout(row_3)
        control_panel_layout.addLayout(row_4)
        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.setLayout(main_layout)

    def initConnect(self):
        super(MotionControlView, self).initConnect()
        TYPE: Qt.Qt.ConnectionType = Qt.Qt.ConnectionType(Qt.Qt.AutoConnection | Qt.Qt.UniqueConnection)
        self.valueUpdated.connect(slot=self.slot_valueUpdated, type=TYPE)
        self.currentDataUpdated.connect(slot=self.currentDataUpdatedSlot, 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)


    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.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()

        x_step: float = self.get_x_move_step_value()
        y_step: float = self.get_y_move_step_value()
        if not isinstance(x_step, (float, int)):
            return
        if x > 0:
            self.Model.Position_X += x_step
        elif x < 0:
            self.Model.Position_X -= x_step
        if not isinstance(y_step, (float, int)):
            return
        if y > 0:
            self.Model.Position_Y += y_step
        elif y < 0:
            self.Model.Position_Y -= y_step
        self._update_robot_position()

    def _on_zr_button_pressed(self, z, r):
        self.initModel()
        z_step: float = self.get_z_move_step_value()
        if not isinstance(z_step, (float, int)):
            return
        if z > 0:
            self.Model.Position_Z += z_step  # Z轴使用步长控件值
        elif z < 0:
            self.Model.Position_Z -= z_step  # Z轴使用步长控件值

        self._update_robot_position()


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

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

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


    def slot_valueUpdated(self, model: SlideModelInterface):
        if isinstance(model, SlideModelInterface):
            self.initModel()
            self.Model.as_field(model.to_field())

    def currentDataUpdatedSlot(self, model: SlideModelInterface):
        if isinstance(model, SlideModelInterface):
            self.initModel()
            self.Model.as_field(model.to_field())

    def get_robot_position(self) -> SlideModelInterface:
        self.initModel()
        return SlideModel.copyInstance(slide=self.Model, box=None)

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

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