from PySide6.QtWidgets import (QWidget,QMainWindow, QMessageBox,QLabel, QTextEdit, QPushButton)
from PySide6.QtUiTools import QUiLoader
from PySide6.QtCore import QFile, Qt, Signal, QRect
from PySide6.QtGui import QStandardItemModel, QStandardItem
from qt_material import apply_stylesheet, list_themes
import os
class PlotCfg(QWidget):
    content_saved = Signal(str, str)  # 窗口标题, 内容
    
    def __init__(self, **kwargs):
        super().__init__()
        self.theme = kwargs.get('theme', 'dark_cyan.xml')  # 默认主题
        self.title = kwargs.get('title', '数据配置')  # 默认标题
        self.files = kwargs.get('files', [])  # 默认文件列表
        self.parent_win = kwargs.get('parent_win', None)  # 默认父窗口
        self.load_ui()
        self.init_ui()
        self.init_combo_with_model()
    
    def load_ui(self):
        """加载UI文件"""
        ui_file = QFile("./ui/plot/cfg.ui")
        if not ui_file.open(QFile.ReadOnly):
            raise Exception(f"无法打开UI文件: {ui_file.errorString()}")
        
        loader = QUiLoader()
        self.ui = loader.load(ui_file, self)  # 将self作为父对象
        ui_file.close()
        
        # 设置主布局
        self.setLayout(self.ui.layout())
        
    
    def init_ui(self):
        """初始化UI元素"""
        self.setWindowTitle(self.title)
        apply_stylesheet(self, theme='dark_cyan.xml')  # 应用相同的主题
        # 查找UI中的组件
        # self.titleLabel = self.ui.findChild(QLabel, "titleLabel")
        # self.textEdit = self.ui.findChild(QTextEdit, "textEdit")
        # self.btnSave = self.ui.findChild(QPushButton, "btnSave")
        # self.btnClear = self.ui.findChild(QPushButton, "btnClear")
        
        # 设置初始内容
        # self.titleLabel.setText(f"<h2>{self.title}</h2>")
        # self.textEdit.setPlaceholderText(f"在此输入{self.title}的内容...")
        # self.btnSave.setText(f"保存{self.title}内容")
        # self.btnClear.setText(f"清空{self.title}内容")
    
    def connect_signals(self):
        """连接信号与槽"""
        # self.ui.btnSave.clicked.connect(self.save_content)
        # self.ui.btnClear.clicked.connect(self.clear_content)
    
    def save_content(self):
        """保存内容"""
        content = self.ui.textEdit.toPlainText()
        if content:
            self.content_saved.emit(self.title, content)
            QMessageBox.information(self, "保存成功", f"{self.title}内容已保存")
        else:
            QMessageBox.warning(self, "保存失败", "没有内容可保存")
    
    def init_combo_with_model(self):
        """使用模型初始化ComboBox"""
        combo = self.ui.file_comboBox
        model = QStandardItemModel()
        
        for path in self.files:
            item = QStandardItem(os.path.basename(path))
            item.setData(path, Qt.UserRole)  # 将完整路径存储在UserRoles中
            model.appendRow(item)
        
        combo.setModel(model)
        combo.setCurrentIndex(0)  # 初始时选中第一项
        
        # 连接信号时使用lambda保持对combo的引用
        combo.currentIndexChanged.connect(
            lambda index: self.on_combo_selection_changed(combo, index)
        )
    
    def on_combo_selection_changed(self, combo, index):
        """处理选择变化"""
        if index >= 0:
            selected_path = combo.model().item(index).data(Qt.UserRole)
            print(f"选中的文件: {selected_path}")
            # 处理选中的文件
            self.parent_win.set_file_path(selected_path)

    def clear_content(self):
        """清空内容"""
        self.ui.textEdit.clear()
    
    def closeEvent(self, event):
        """关闭窗口时确认"""
        reply = QMessageBox.question(
            self, '确认关闭',
            f'确定要关闭{self.title}吗?',
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            event.accept()
        else:
            event.ignore()