import sys
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, 
                              QVBoxLayout, QPushButton, QLineEdit, QLabel, 
                              QHBoxLayout, )
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtCore import QUrl, QTimer, Qt
from PySide6.QtGui import QIcon
from qt_material import apply_stylesheet
AI_URL = "http://118.31.5.143:9039/ui/chat/46c09402bdb51d23"
class WebBrowserWindow(QMainWindow):
    def __init__(self, url = AI_URL, parent=None):
        super().__init__(parent)
        self.setWindowTitle("Acycle-小助手")
        self.resize(1000, 700)
                # 设置窗口图标
        self.setWindowIcon(QIcon("resources/icons/logo.svg"))
        # 主窗口设置
        self.setWindowFlags(self.windowFlags() | Qt.Window)  # 确保作为独立窗口
        
        # 中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        layout = QVBoxLayout(central_widget)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        
        # 创建网页视图
        self.web_view = QWebEngineView()
        self.web_view.setUrl(QUrl(url))
        
        # 控制按钮区域
        # control_layout = QHBoxLayout()
        # self.close_btn = QPushButton("关闭窗口")
        # self.zoom_in_btn = QPushButton("放大(+)")
        # self.zoom_out_btn = QPushButton("缩小(-)")
        # self.zoom_reset_btn = QPushButton("重置缩放")
        
        # 按钮连接信号
        # self.close_btn.clicked.connect(self.close)
        # self.zoom_in_btn.clicked.connect(self.zoom_in)
        # self.zoom_out_btn.clicked.connect(self.zoom_out)
        # self.zoom_reset_btn.clicked.connect(self.zoom_reset)
        
        # 添加控制按钮
        # control_layout.addWidget(self.zoom_out_btn)
        # control_layout.addWidget(self.zoom_reset_btn)
        # control_layout.addWidget(self.zoom_in_btn)
        # control_layout.addStretch()
        # control_layout.addWidget(self.close_btn)
        
        # 添加控件到布局
        # layout.addLayout(control_layout)
        layout.addWidget(self.web_view)
        
        # 初始化缩放相关变量
        self.current_zoom = 1.0
        self.auto_zoom_enabled = True
        
        # 连接信号
        self.web_view.loadFinished.connect(self.initial_zoom_adjustment)
        
        # 设置定时器定期检查并调整缩放
        self.zoom_timer = QTimer(self)
        self.zoom_timer.timeout.connect(self.check_and_adjust_zoom)
        self.zoom_timer.start(300)  # 每300毫秒检查一次
    
    def initial_zoom_adjustment(self, ok):
        """初始加载完成后调整缩放"""
        if ok and self.auto_zoom_enabled:
            self.adjust_zoom_to_fit()
    
    def check_and_adjust_zoom(self):
        """定期检查并调整缩放"""
        # if (self.web_view.url().isValid() and 
        #     self.auto_zoom_enabled and 
        #     # not self.web_view.isLoading()):
        #     self.adjust_zoom_to_fit()
    
    def adjust_zoom_to_fit(self):
        """根据窗口大小自动调整缩放"""
        view_width = self.web_view.width()
        
        self.web_view.page().runJavaScript(
            "document.documentElement.scrollWidth", 
            lambda content_width: self.calculate_zoom(view_width, content_width)
        )
    
    def calculate_zoom(self, view_width, content_width):
        """计算合适的缩放比例"""
        if content_width > 0 and view_width > 0:
            # 计算基础缩放比例
            base_zoom = view_width / content_width
            
            # 限制缩放范围
            new_zoom = min(max(base_zoom, 0.3), 2.0)
            
            # 只有当变化较大时才更新，避免频繁微调
            if abs(new_zoom - self.current_zoom) > 0.05:
                self.current_zoom = new_zoom
                self.web_view.setZoomFactor(self.current_zoom)
    
    def zoom_in(self):
        """手动放大"""
        self.auto_zoom_enabled = False
        self.current_zoom = min(self.current_zoom + 0.1, 3.0)
        self.web_view.setZoomFactor(self.current_zoom)
    
    def zoom_out(self):
        """手动缩小"""
        self.auto_zoom_enabled = False
        self.current_zoom = max(self.current_zoom - 0.1, 0.3)
        self.web_view.setZoomFactor(self.current_zoom)
    
    def zoom_reset(self):
        """重置为自动缩放"""
        self.auto_zoom_enabled = True
        self.adjust_zoom_to_fit()
    
    def resizeEvent(self, event):
        """窗口大小改变时重新调整缩放"""
        if self.auto_zoom_enabled:
            self.adjust_zoom_to_fit()
        super().resizeEvent(event)

class MainAppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("网页浏览器控制器")
        self.resize(600, 400)
        
        # 中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        layout = QVBoxLayout(central_widget)
        layout.setSpacing(15)
        
        # URL 输入框
        self.url_label = QLabel("输入网页URL:")
        self.url_input = QLineEdit()
        self.url_input.setPlaceholderText("https://www.example.com")
        self.url_input.setText("https://www.example.com")
        
        # 打开网页按钮
        self.open_btn = QPushButton("打开独立浏览器窗口")
        self.open_btn.clicked.connect(self.open_web_browser)
        
        # 添加到布局
        layout.addWidget(self.url_label)
        layout.addWidget(self.url_input)
        layout.addWidget(self.open_btn)
        layout.addStretch()
        
        # 存储浏览器窗口引用
        self.browser_window = None
    
    def open_web_browser(self):
        url = self.url_input.text().strip()
        if not url:
            return
            
        # 确保URL有协议前缀
        if not url.startswith(('http://', 'https://')):
            url = 'https://' + url
            
        # 创建并显示独立浏览器窗口
        self.browser_window = WebBrowserWindow(url)
        self.browser_window.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 应用qt-material主题
    apply_stylesheet(app, theme='dark_teal.xml')
    
    window = MainAppWindow()
    window.show()
    sys.exit(app.exec())