import sys
import ctypes
import platform
from PySide6.QtCore import Qt, QPoint, QTimer
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from pynput.mouse import Controller as MouseController

# Windows特定常量和函数
if platform.system() == "Windows":
    GWL_EXSTYLE = -20
    WS_EX_NOACTIVATE = 0x08000000
    WS_EX_TOOLWINDOW = 0x00000080

    def set_window_noactivate(widget):
        hwnd = widget.winId().__int__()
        ex_style = ctypes.windll.user32.GetWindowLongW(hwnd, GWL_EXSTYLE)
        ex_style |= WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW
        ctypes.windll.user32.SetWindowLongW(hwnd, GWL_EXSTYLE, ex_style)

class ScrollButton(QPushButton):
    def __init__(self, label, direction, parent=None):
        super().__init__(label, parent)
        self.direction = direction  # 'up' 或 'down'
        self.mouse = MouseController()

        # 设置按钮不接受焦点
        self.setFocusPolicy(Qt.NoFocus)

        # 使用 QTimer 实现持续滚动
        self.timer = QTimer()
        self.timer.timeout.connect(self.scroll_step)

    def scroll_step(self):
        if self.direction == 'up':
            self.mouse.scroll(0, 1)  # 向上滚动
        elif self.direction == 'down':
            self.mouse.scroll(0, -1)  # 向下滚动

    def mousePressEvent(self, event):
        if event.button() == Qt.RightButton:  # 修改为右键
            self.timer.start(50)  # 每50毫秒滚动一次，调整此值以控制滚动速度
        super().mousePressEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.RightButton:  # 修改为右键
            self.timer.stop()
        super().mouseReleaseEvent(event)

class DraggableWindow(QWidget):
    def __init__(self):
        super().__init__()
        # 设置窗口标志，使其始终在最前且无边框，并且不获取焦点
        self.setWindowFlags(
            Qt.WindowStaysOnTopHint |
            Qt.FramelessWindowHint |
            Qt.Tool
        )
        self.setAttribute(Qt.WA_ShowWithoutActivating)  # 显示时不激活窗口
        self.setAttribute(Qt.WA_TranslucentBackground, True)  # 可选，设置透明背景
        self.setFocusPolicy(Qt.NoFocus)

        self.init_ui()
        self.dragging = False
        self.drag_position = QPoint()

        # 平台特定的设置
        if platform.system() == "Windows":
            set_window_noactivate(self)
        elif platform.system() == "Linux":
            # Linux上可能需要额外的设置，取决于窗口管理器
            pass
        elif platform.system() == "Darwin":
            # macOS上可能需要额外的设置
            pass

    def init_ui(self):
        layout = QVBoxLayout()
        layout.setSpacing(5)
        layout.setContentsMargins(5, 5, 5, 5)

        # 创建上滚和下滚按钮
        self.up_button = ScrollButton("⬆️ 上滚", 'up', self)
        self.down_button = ScrollButton("⬇️ 下滚", 'down', self)

        # 设置按钮样式（可根据需要调整）
        button_style = """
            QPushButton {
                background-color: rgba(52, 152, 219, 0.8);
                color: white;
                border: none;
                border-radius: 5px;
                height: 40px;
                font-size: 14px;
            }
            QPushButton:pressed {
                background-color: rgba(41, 128, 185, 0.8);
            }
            QPushButton:hover {
                background-color: rgba(52, 152, 219, 1);
            }
        """
        self.up_button.setStyleSheet(button_style)
        self.down_button.setStyleSheet(button_style)

        layout.addWidget(self.up_button)
        layout.addWidget(self.down_button)

        self.setLayout(layout)
        self.setFixedSize(100, 100)  # 根据需要调整窗口大小

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = True
            # 获取鼠标点击位置与窗口左上角的偏移量
            if hasattr(event, 'globalPosition'):
                self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
            else:
                self.drag_position = event.globalPos() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.LeftButton and self.dragging:
            # 计算新的窗口位置
            if hasattr(event, 'globalPosition'):
                new_pos = event.globalPosition().toPoint() - self.drag_position
            else:
                new_pos = event.globalPos() - self.drag_position
            self.move(new_pos)
            event.accept()

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.dragging = False
            event.accept()

    # 重写 event 方法，确保窗口不被激活
    def event(self, e):
        if platform.system() == "Windows" and e.type() == 10:  # QEvent.WindowActivate = 10
            return False
        return super().event(e)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = DraggableWindow()
    window.show()
    sys.exit(app.exec())添加两个迷你按钮“+”和“-”用来调节悬浮按钮透明度