from PySide6.QtWidgets import (QWidget, QMainWindow, QMessageBox, QLabel, QTextEdit, 
                              QPushButton, QComboBox, QSlider, QColorDialog, QVBoxLayout, 
                              QHBoxLayout, QGroupBox, QFormLayout, QLineEdit, QSpinBox,
                              QCheckBox, QRadioButton, QTabWidget, QFileDialog, QFontComboBox,
                              QScrollArea, QGridLayout)
from PySide6.QtCore import QFile, Qt, Signal, QRect
from PySide6.QtGui import QStandardItemModel, QStandardItem, QColor
from qt_material import apply_stylesheet, list_themes
import os
from util import utiltool
@utiltool.window_shortcut
class plotConfig(QWidget):
    content_saved = Signal(str, str)  # Window title, content
    plot_config_changed = Signal(dict)  # Plot configuration change signal
    
    def __init__(self, **kwargs):
        super().__init__()
        self.theme = kwargs.get('theme', 'dark_cyan.xml')  # Default theme
        self.title = kwargs.get('title', 'Plot Configuration')  # Default title
        self.files = kwargs.get('files', [])  # Default file list
        self.parent_win = kwargs.get('parent_win', None)  # Default parent window
        
        # Plot configuration
        self.plot_config = {
            'data': {
                'all_panels': '1,1',
                'set_panels': '1',
                'data_file': '',
                'x_column': 1,
                'y_column': 2,
                'set_data': ''
            },
            'title': {
                'title': '1D line plot',
                'legend': 'data1',
                'font_family': 'Arial',
                'font_weight': 'normal'
            },
            'axis': {
            'x_label': 'Depth (m)',
            'y_label': 'Value',  # 添加y_label配置
            'x_min': 0,
            'x_max': 2000,
            'y_min': 0,  # 添加y_min配置
            'y_max': 2000,  # 添加y_max配置
            'x_tick_label': False,
            'x_minor_tick': False,
            'y_minor_tick': True,
            'x_direction': 'normal',
            'y_direction': 'normal',  # 添加y_direction配置
            'x_log_scale': False,  # 改为x_log_scale
            'y_log_scale': False   # 添加y_log_scale
        },
            'legend': {
                'font_size': 12,
                'font_style': 'normal'
            },
            'line': {
                'plot_type': 'line',
                'line_style': '-',
                'line_width': 1,
                'line_color': '#1f77b4'
            },
            'marker': {
                'show_face': False,
                'show_edge': False,
                'style': 'o',
                'size': 1,
                'alpha': 0.5,
                'face_color': '#1f77b4',
                'edge_color': '#000000'
            }
        }
        
        self.init_ui()
        self.init_combo_with_model()
        self.connect_signals()
    
    def init_ui(self):
        """Initialize UI elements"""
        self.setWindowTitle(self.title)
        apply_stylesheet(self, theme='dark_cyan.xml')
        
        # Create main layout
        main_layout = QVBoxLayout(self)
        
        # Create scroll area to accommodate all controls
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_content = QWidget()
        scroll_layout = QVBoxLayout(scroll_content)
        
        # Data configuration group
        data_group = QGroupBox("Data Configuration")
        data_layout = QFormLayout(data_group)
        
        # All panels
        self.all_panels_edit = QLineEdit(self.plot_config['data']['all_panels'])
        data_layout.addRow("All panels:", self.all_panels_edit)
        
        # Set panels - changed to QComboBox
        self.set_panels_combo = QComboBox()
        data_layout.addRow("Set panel:", self.set_panels_combo)
        
        # File selection combo box
        self.file_combo = QComboBox()
        data_layout.addRow("Select file:", self.file_combo)
        
        # X and Y columns
        xy_layout = QHBoxLayout()
        self.x_column_spin = QSpinBox()
        self.x_column_spin.setValue(self.plot_config['data']['x_column'])
        self.y_column_spin = QSpinBox()
        self.y_column_spin.setValue(self.plot_config['data']['y_column'])
        xy_layout.addWidget(QLabel("X column:"))
        xy_layout.addWidget(self.x_column_spin)
        xy_layout.addWidget(QLabel("Y column:"))
        xy_layout.addWidget(self.y_column_spin)
        data_layout.addRow(xy_layout)
        
        # Set data - changed to QComboBox
        self.set_data_combo = QComboBox()
        data_layout.addRow("Set data:", self.set_data_combo)
        
        scroll_layout.addWidget(data_group)
        
        # Title and legend configuration group
        title_group = QGroupBox("Title/Legend/Font")
        title_layout = QFormLayout(title_group)
        
        # Title
        self.title_edit = QLineEdit(self.plot_config['title']['title'])
        title_layout.addRow("Title:", self.title_edit)
        
        # Legend
        self.legend_edit = QLineEdit(self.plot_config['title']['legend'])
        title_layout.addRow("Legend:", self.legend_edit)
        
        # Font name
        self.font_combo = QFontComboBox()
        index = self.font_combo.findText(self.plot_config['title']['font_family'])
        if index >= 0:
            self.font_combo.setCurrentIndex(index)
        title_layout.addRow("Font name:", self.font_combo)
        
        # Font weight
        font_weight_layout = QHBoxLayout()
        self.normal_radio = QRadioButton("normal")
        self.normal_radio.setChecked(self.plot_config['title']['font_weight'] == 'normal')
        self.bold_radio = QRadioButton("bold")
        self.bold_radio.setChecked(self.plot_config['title']['font_weight'] == 'bold')
        font_weight_layout.addWidget(self.normal_radio)
        font_weight_layout.addWidget(self.bold_radio)
        title_layout.addRow("Font weight:", font_weight_layout)
        
        scroll_layout.addWidget(title_group)
        
        # Axis configuration group
        axis_group = QGroupBox("X&Y Axis/Limit/Scale")
        axis_layout = QFormLayout(axis_group)
        
        # X label
        self.x_label_edit = QLineEdit(self.plot_config['axis']['x_label'])
        axis_layout.addRow("X label:", self.x_label_edit)
        
        # X limit
        x_limit_layout = QHBoxLayout()
        self.x_min_edit = QLineEdit(str(self.plot_config['axis']['x_min']))
        self.x_max_edit = QLineEdit(str(self.plot_config['axis']['x_max']))
        x_limit_layout.addWidget(self.x_min_edit)
        x_limit_layout.addWidget(QLabel("-"))
        x_limit_layout.addWidget(self.x_max_edit)
        axis_layout.addRow("X limit:", x_limit_layout)
        
        # Minor tick configuration
        minor_tick_layout = QHBoxLayout()
        x_minor_layout = QHBoxLayout()
        self.x_minor_off_radio = QRadioButton("X off")
        self.x_minor_off_radio.setChecked(not self.plot_config['axis']['x_minor_tick'])
        self.x_minor_on_radio = QRadioButton("X on")
        self.x_minor_on_radio.setChecked(self.plot_config['axis']['x_minor_tick'])
        x_minor_layout.addWidget(self.x_minor_off_radio)
        x_minor_layout.addWidget(self.x_minor_on_radio)
        
        y_minor_layout = QHBoxLayout()
        self.y_minor_off_radio = QRadioButton("Y off")
        self.y_minor_off_radio.setChecked(not self.plot_config['axis']['y_minor_tick'])
        self.y_minor_on_radio = QRadioButton("Y on")
        self.y_minor_on_radio.setChecked(self.plot_config['axis']['y_minor_tick'])
        y_minor_layout.addWidget(self.y_minor_off_radio)
        y_minor_layout.addWidget(self.y_minor_on_radio)
        
        minor_tick_layout.addLayout(x_minor_layout)
        minor_tick_layout.addLayout(y_minor_layout)
        axis_layout.addRow("Minor tick:", minor_tick_layout)
        
        # X direction
        x_direction_layout = QHBoxLayout()
        self.x_normal_radio = QRadioButton("Normal")
        self.x_normal_radio.setChecked(self.plot_config['axis']['x_direction'] == 'normal')
        self.x_reverse_radio = QRadioButton("Reverse")
        self.x_reverse_radio.setChecked(self.plot_config['axis']['x_direction'] == 'reverse')
        x_direction_layout.addWidget(self.x_normal_radio)
        x_direction_layout.addWidget(self.x_reverse_radio)
        axis_layout.addRow("X direction:", x_direction_layout)
        
        # Y label
        self.y_label_edit = QLineEdit(self.plot_config['axis'].get('y_label', 'Value'))
        axis_layout.addRow("Y label:", self.y_label_edit)

        # Y limit
        y_limit_layout = QHBoxLayout()
        self.y_min_edit = QLineEdit(str(self.plot_config['axis'].get('y_min', '')))
        self.y_max_edit = QLineEdit(str(self.plot_config['axis'].get('y_max', '')))
        y_limit_layout.addWidget(self.y_min_edit)
        y_limit_layout.addWidget(QLabel("-"))
        y_limit_layout.addWidget(self.y_max_edit)
        axis_layout.addRow("Y limit:", y_limit_layout)

        # Y direction
        y_direction_layout = QHBoxLayout()
        self.y_normal_radio = QRadioButton("Normal")
        self.y_normal_radio.setChecked(self.plot_config['axis'].get('y_direction', 'normal') == 'normal')
        self.y_reverse_radio = QRadioButton("Reverse")
        self.y_reverse_radio.setChecked(self.plot_config['axis'].get('y_direction', 'normal') == 'reverse')
        y_direction_layout.addWidget(self.y_normal_radio)
        y_direction_layout.addWidget(self.y_reverse_radio)
        axis_layout.addRow("Y direction:", y_direction_layout)


        # Log scale
        log_scale_layout = QHBoxLayout()
        self.x_log_scale_check = QCheckBox("X Log")
        self.x_log_scale_check.setChecked(self.plot_config['axis'].get('x_log_scale', False))
        self.y_log_scale_check = QCheckBox("Y Log")
        self.y_log_scale_check.setChecked(self.plot_config['axis'].get('y_log_scale', False))
        log_scale_layout.addWidget(self.x_log_scale_check)
        log_scale_layout.addWidget(self.y_log_scale_check)
        axis_layout.addRow("Log scale:", log_scale_layout)
        
        scroll_layout.addWidget(axis_group)
        
        # Legend box configuration group
        legend_group = QGroupBox("Legend Box")
        legend_layout = QFormLayout(legend_group)
        
        # Font size
        self.legend_font_size_spin = QSpinBox()
        self.legend_font_size_spin.setValue(self.plot_config['legend']['font_size'])
        legend_layout.addRow("Font size:", self.legend_font_size_spin)
        
        # Font style
        font_style_layout = QHBoxLayout()
        self.legend_normal_radio = QRadioButton("normal")
        self.legend_normal_radio.setChecked(self.plot_config['legend']['font_style'] == 'normal')
        self.legend_italic_radio = QRadioButton("italic")
        self.legend_italic_radio.setChecked(self.plot_config['legend']['font_style'] == 'italic')
        font_style_layout.addWidget(self.legend_normal_radio)
        font_style_layout.addWidget(self.legend_italic_radio)
        legend_layout.addRow("Font style:", font_style_layout)
        
        scroll_layout.addWidget(legend_group)
        
        # Line specification configuration group
        line_group = QGroupBox("Line Specification")
        line_layout = QFormLayout(line_group)
        
        # Line plot
        self.line_plot_combo = QComboBox()
        self.line_plot_combo.addItems(["line", "scatter", "bar"])
        self.line_plot_combo.setCurrentText(self.plot_config['line']['plot_type'])
        line_layout.addRow("Line plot:", self.line_plot_combo)
        
        # Line style
        self.line_style_combo = QComboBox()
        self.line_style_combo.addItems(["-", "--", ":", "-."])
        self.line_style_combo.setCurrentText(self.plot_config['line']['line_style'])
        line_layout.addRow("Line style:", self.line_style_combo)
        
        # Line width
        self.line_width_spin = QSpinBox()
        self.line_width_spin.setValue(self.plot_config['line']['line_width'])
        line_layout.addRow("Line width:", self.line_width_spin)
        
        # Line color
        self.line_color_btn = QPushButton("Select")
        line_layout.addRow("Line color:", self.line_color_btn)
        
        scroll_layout.addWidget(line_group)
        
        # Marker specification configuration group
        marker_group = QGroupBox("Marker Specification")
        marker_layout = QFormLayout(marker_group)
        
        # Show marker face and edge
        marker_face_edge_layout = QHBoxLayout()
        
        marker_face_layout = QHBoxLayout()
        self.marker_face_yes_radio = QRadioButton("Show face")
        self.marker_face_yes_radio.setChecked(self.plot_config['marker']['show_face'])
        self.marker_face_no_radio = QRadioButton("Hide face")
        self.marker_face_no_radio.setChecked(not self.plot_config['marker']['show_face'])
        marker_face_layout.addWidget(self.marker_face_yes_radio)
        marker_face_layout.addWidget(self.marker_face_no_radio)
        
        marker_edge_layout = QHBoxLayout()
        self.marker_edge_yes_radio = QRadioButton("Show edge")
        self.marker_edge_yes_radio.setChecked(self.plot_config['marker']['show_edge'])
        self.marker_edge_no_radio = QRadioButton("Hide edge")
        self.marker_edge_no_radio.setChecked(not self.plot_config['marker']['show_edge'])
        marker_edge_layout.addWidget(self.marker_edge_yes_radio)
        marker_edge_layout.addWidget(self.marker_edge_no_radio)
        
        marker_face_edge_layout.addLayout(marker_face_layout)
        marker_face_edge_layout.addLayout(marker_edge_layout)
        marker_layout.addRow("Marker display:", marker_face_edge_layout)
        
        # Style and size
        style_size_layout = QHBoxLayout()
        
        self.marker_style_combo = QComboBox()
        self.marker_style_combo.addItems(["o", "s", "^", "D", "*"])
        self.marker_style_combo.setCurrentText(self.plot_config['marker']['style'])
        
        self.marker_size_spin = QSpinBox()
        self.marker_size_spin.setValue(self.plot_config['marker']['size'])
        
        style_size_layout.addWidget(QLabel("Style:"))
        style_size_layout.addWidget(self.marker_style_combo)
        style_size_layout.addWidget(QLabel("Size:"))
        style_size_layout.addWidget(self.marker_size_spin)
        
        marker_layout.addRow(style_size_layout)
        
        # Alpha
        self.marker_alpha_slider = QSlider(Qt.Horizontal)
        self.marker_alpha_slider.setRange(0, 100)
        self.marker_alpha_slider.setValue(int(self.plot_config['marker']['alpha'] * 100))
        marker_layout.addRow("Alpha:", self.marker_alpha_slider)
        
        # Face color and edge color
        color_layout = QHBoxLayout()
        self.marker_face_color_btn = QPushButton("Face color")
        self.marker_edge_color_btn = QPushButton("Edge color")
        color_layout.addWidget(self.marker_face_color_btn)
        color_layout.addWidget(self.marker_edge_color_btn)
        marker_layout.addRow("Color:", color_layout)
        
        scroll_layout.addWidget(marker_group)
        
        # Add stretch factor to make layout more reasonable
        scroll_layout.addStretch()
        
        # Set scroll area content
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)
        
        # Add buttons
        button_layout = QHBoxLayout()
        self.apply_btn = QPushButton("Apply")
        self.cancel_btn = QPushButton("Cancel")
        self.ok_btn = QPushButton("OK")
        
        button_layout.addWidget(self.apply_btn)
        button_layout.addWidget(self.cancel_btn)
        button_layout.addStretch()
        button_layout.addWidget(self.ok_btn)
        
        main_layout.addLayout(button_layout)
        
        # Initialize panel options
        self.update_panel_options()

    def connect_signals(self):
        """Connect signals and slots"""
        # File selection combo box
        self.file_combo.currentIndexChanged.connect(
            lambda index: self.on_combo_selection_changed(self.file_combo, index)
        )
        
        # All panels edit box text change updates panel options
        self.all_panels_edit.textChanged.connect(self.update_panel_options)
        
        # Color selection buttons
        self.line_color_btn.clicked.connect(self.choose_line_color)
        self.marker_face_color_btn.clicked.connect(self.choose_marker_face_color)
        self.marker_edge_color_btn.clicked.connect(self.choose_marker_edge_color)
        
        # Apply button
        self.apply_btn.clicked.connect(self.apply_config)
        
        # Cancel button
        self.cancel_btn.clicked.connect(self.close)
        
        # OK button
        self.ok_btn.clicked.connect(self.apply_and_close)

        self.file_combo.currentIndexChanged.connect(self.update_axis_range_from_data)
        self.x_column_spin.valueChanged.connect(self.update_axis_range_from_data)
        self.y_column_spin.valueChanged.connect(self.update_axis_range_from_data)
        
        # Add automatic apply configuration signal connections
        self.connect_auto_apply_signals()

    def connect_auto_apply_signals(self):
        """Connect all control signals to implement automatic apply configuration"""
        # Data configuration group
        self.all_panels_edit.textChanged.connect(self.auto_apply_config)
        self.set_panels_combo.currentIndexChanged.connect(self.auto_apply_config)
        self.file_combo.currentIndexChanged.connect(self.auto_apply_config)
        self.x_column_spin.valueChanged.connect(self.auto_apply_config)
        self.y_column_spin.valueChanged.connect(self.auto_apply_config)
        self.set_data_combo.currentIndexChanged.connect(self.auto_apply_config)
        
        # Title and legend configuration group
        self.title_edit.textChanged.connect(self.auto_apply_config)
        self.legend_edit.textChanged.connect(self.auto_apply_config)
        self.font_combo.currentIndexChanged.connect(self.auto_apply_config)
        self.normal_radio.toggled.connect(self.auto_apply_config)
        self.bold_radio.toggled.connect(self.auto_apply_config)
        
        # Axis configuration group
        self.x_label_edit.textChanged.connect(self.auto_apply_config)
        self.x_min_edit.textChanged.connect(self.auto_apply_config)
        self.x_max_edit.textChanged.connect(self.auto_apply_config)
        self.x_minor_off_radio.toggled.connect(self.auto_apply_config)
        self.x_minor_on_radio.toggled.connect(self.auto_apply_config)
        self.y_minor_off_radio.toggled.connect(self.auto_apply_config)
        self.y_minor_on_radio.toggled.connect(self.auto_apply_config)
        self.x_normal_radio.toggled.connect(self.auto_apply_config)
        self.x_reverse_radio.toggled.connect(self.auto_apply_config)
        self.x_log_scale_check.stateChanged.connect(self.auto_apply_config)
        self.y_log_scale_check.stateChanged.connect(self.auto_apply_config)
        
        # Legend box configuration group
        self.legend_font_size_spin.valueChanged.connect(self.auto_apply_config)
        self.legend_normal_radio.toggled.connect(self.auto_apply_config)
        self.legend_italic_radio.toggled.connect(self.auto_apply_config)
        
        # Line specification configuration group
        self.line_plot_combo.currentIndexChanged.connect(self.auto_apply_config)
        self.line_style_combo.currentIndexChanged.connect(self.auto_apply_config)
        self.line_width_spin.valueChanged.connect(self.auto_apply_config)
        
        # Marker specification configuration group
        self.marker_face_yes_radio.toggled.connect(self.auto_apply_config)
        self.marker_face_no_radio.toggled.connect(self.auto_apply_config)
        self.marker_edge_yes_radio.toggled.connect(self.auto_apply_config)
        self.marker_edge_no_radio.toggled.connect(self.auto_apply_config)
        self.marker_style_combo.currentIndexChanged.connect(self.auto_apply_config)
        self.marker_size_spin.valueChanged.connect(self.auto_apply_config)
        self.marker_alpha_slider.valueChanged.connect(self.auto_apply_config)

    def auto_apply_config(self):
        """Automatically apply configuration"""
        self.update_config_from_ui()
        self.plot_config_changed.emit(self.plot_config.copy())

    def update_panel_options(self):
        """Update panel selection combo box based on all panels setting"""
        try:
            # Parse all panels setting
            panels_text = self.all_panels_edit.text()
            rows, cols = map(int, panels_text.split(','))
            total_panels = rows * cols
            
            # Clear existing options
            self.set_panels_combo.clear()
            
            # Add new options
            for i in range(1, total_panels + 1):
                self.set_panels_combo.addItem(str(i))
                
        except ValueError:
            # If parsing fails, keep at least one option
            if self.set_panels_combo.count() == 0:
                self.set_panels_combo.addItem("1")

    def init_combo_with_model(self):
        """Initialize ComboBox with model"""
        model = QStandardItemModel()
        
        for path in self.files:
            item = QStandardItem(os.path.basename(path))
            item.setData(path, Qt.UserRole)  # Store full path in UserRoles
            model.appendRow(item)
        
        self.file_combo.setModel(model)
        self.set_data_combo.setModel(model)  # Also set for set_data_combo
        if self.file_combo.count() > 0:
            self.file_combo.setCurrentIndex(0)
            self.set_data_combo.setCurrentIndex(0)
            self.update_axis_range_from_data()
    
    def on_combo_selection_changed(self, combo, index):
        """Handle selection change"""
        if index >= 0:
            selected_path = combo.model().item(index).data(Qt.UserRole)
            print(f"Selected file: {selected_path}")
            # Process selected file
            if self.parent_win:
                self.parent_win.set_file_path(selected_path)
    
    def choose_line_color(self):
        """Choose line color"""
        color = QColorDialog.getColor(QColor(self.plot_config['line']['line_color']))
        if color.isValid():
            self.plot_config['line']['line_color'] = color.name()
            self.auto_apply_config()
    
    # 在plotConfig类中添加update_axis_range_from_data方法
    def update_axis_range_from_data(self):
        """根据当前选择的数据文件更新坐标轴范围"""
        if not self.files:
            return
        
        # 获取当前选中的文件
        current_index = self.file_combo.currentIndex()
        if current_index < 0:
            return
        
        file_path = self.files[current_index]
        
        try:
            # 读取数据文件
            # 这里需要根据实际情况实现数据读取逻辑
            # 假设使用pandas读取
            import pandas as pd
            # 尝试使用空格分隔符
            try:
                data = pd.read_csv(file_path, delim_whitespace=True, header=None, engine='python')
                # 检查是否成功读取了多列数据
                if data.shape[1] < 2:
                    data = None
                    raise ValueError("Not enough columns with space delimiter")
            except Exception:
                data = None
            
            # 如果空格分隔失败，尝试逗号分隔符
            if data is None:
                try:
                    data = pd.read_csv(file_path, delimiter=',', header=None, engine='python')
                    # 检查是否成功读取了多列数据
                    if data.shape[1] < 2:
                        data = None
                        raise ValueError("Not enough columns with comma delimiter")
                except Exception:
                    data = None
            
            # 如果两种分隔符都失败，尝试自动检测
            if data is None:
                try:
                    data = pd.read_csv(file_path, sep=None, header=None, engine='python')
                except Exception as e:
                    print(f"Failed to read file with any delimiter: {e}")
                    return
            
            # 获取当前选择的列
            x_col = self.x_column_spin.value() - 1  # 转换为0-based索引
            y_col = self.y_column_spin.value() - 1  # 转换为0-based索引
            
            # 计算范围
            x_min = data.iloc[:, x_col].min()
            x_max = data.iloc[:, x_col].max()
            y_min = data.iloc[:, y_col].min()
            y_max = data.iloc[:, y_col].max()
            
            # 更新UI
            self.x_min_edit.setText(str(x_min))
            self.x_max_edit.setText(str(x_max))
            self.y_min_edit.setText(str(y_min))
            self.y_max_edit.setText(str(y_max))
            
        except Exception as e:
            print(f"Error updating axis range: {e}")



    def choose_marker_face_color(self):
        """Choose marker face color"""
        color = QColorDialog.getColor(QColor(self.plot_config['marker']['face_color']))
        if color.isValid():
            self.plot_config['marker']['face_color'] = color.name()
            self.auto_apply_config()
    
    def choose_marker_edge_color(self):
        """Choose marker edge color"""
        color = QColorDialog.getColor(QColor(self.plot_config['marker']['edge_color']))
        if color.isValid():
            self.plot_config['marker']['edge_color'] = color.name()
            self.auto_apply_config()
    
    def update_config_from_ui(self):
        """Update configuration from UI"""
        # 数据选项卡
        self.plot_config['data']['all_panels'] = self.all_panels_edit.text()
        # 使用ComboBox的当前文本
        self.plot_config['data']['set_panels'] = self.set_panels_combo.currentText()
        self.plot_config['data']['x_column'] = self.x_column_spin.value()
        self.plot_config['data']['y_column'] = self.y_column_spin.value()
        self.plot_config['data']['set_data'] = self.set_data_combo.currentText()
        
        # 标题选项卡
        self.plot_config['title']['title'] = self.title_edit.text()
        self.plot_config['title']['legend'] = self.legend_edit.text()
        self.plot_config['title']['font_family'] = self.font_combo.currentText()
        self.plot_config['title']['font_weight'] = 'normal' if self.normal_radio.isChecked() else 'bold'
        
        # 坐标轴选项卡
        self.plot_config['axis']['x_label'] = self.x_label_edit.text()
        self.plot_config['axis']['y_label'] = self.y_label_edit.text()
        
        try:
            self.plot_config['axis']['x_min'] = float(self.x_min_edit.text()) if self.x_min_edit.text() else None
        except ValueError:
            self.plot_config['axis']['x_min'] = None
        
        try:
            self.plot_config['axis']['x_max'] = float(self.x_max_edit.text()) if self.x_max_edit.text() else None
        except ValueError:
            self.plot_config['axis']['x_max'] = None
        
        try:
            self.plot_config['axis']['y_min'] = float(self.y_min_edit.text()) if self.y_min_edit.text() else None
        except ValueError:
            self.plot_config['axis']['y_min'] = None
        
        try:
            self.plot_config['axis']['y_max'] = float(self.y_max_edit.text()) if self.y_max_edit.text() else None
        except ValueError:
            self.plot_config['axis']['y_max'] = None
        
        self.plot_config['axis']['x_minor_tick'] = self.x_minor_on_radio.isChecked()
        self.plot_config['axis']['y_minor_tick'] = self.y_minor_on_radio.isChecked()
        self.plot_config['axis']['x_direction'] = 'normal' if self.x_normal_radio.isChecked() else 'reverse'
        self.plot_config['axis']['y_direction'] = 'normal' if self.y_normal_radio.isChecked() else 'reverse'
        self.plot_config['axis']['x_log_scale'] = self.x_log_scale_check.isChecked()
        self.plot_config['axis']['y_log_scale'] = self.y_log_scale_check.isChecked()
        
        # 图例选项卡
        self.plot_config['legend']['font_size'] = self.legend_font_size_spin.value()
        self.plot_config['legend']['font_style'] = 'normal' if self.legend_normal_radio.isChecked() else 'italic'
        
        # 线条选项卡
        self.plot_config['line']['plot_type'] = self.line_plot_combo.currentText()
        self.plot_config['line']['line_style'] = self.line_style_combo.currentText()
        self.plot_config['line']['line_width'] = self.line_width_spin.value()
        
        # 标记选项卡
        self.plot_config['marker']['show_face'] = self.marker_face_yes_radio.isChecked()
        self.plot_config['marker']['show_edge'] = self.marker_edge_yes_radio.isChecked()
        self.plot_config['marker']['style'] = self.marker_style_combo.currentText()
        self.plot_config['marker']['size'] = self.marker_size_spin.value()
        self.plot_config['marker']['alpha'] = self.marker_alpha_slider.value() / 100.0


    def apply_config(self):
        """Apply configuration"""
        self.update_config_from_ui()
        self.plot_config_changed.emit(self.plot_config.copy())
        QMessageBox.information(self, "Success", "Configuration applied")
    
    def apply_and_close(self):
        """Apply configuration and close window"""
        self.apply_config()
        self.close()
    
    def save_content(self):
        """Save content"""
        content = ""  # Content saving function can be implemented here as needed
        if content:
            self.content_saved.emit(self.title, content)
            QMessageBox.information(self, "Save successful", f"{self.title} content saved")
        else:
            QMessageBox.warning(self, "Save failed", "No content to save")
    
    def clear_content(self):
        """Clear content"""
        # Content clearing function can be implemented here as needed
        pass
    
    def closeEvent(self, event):
        """Confirm when closing window"""
        # reply = QMessageBox.question(
        #     self, 'Confirm close',
        #     f'Are you sure you want to close {self.title}?',
        #     QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
        #     QMessageBox.StandardButton.No
        # )
        
        # if reply == QMessageBox.StandardButton.Yes:
        event.accept()
        # else:
        #     event.ignore()