import sys
import os
import numpy as np
import pandas as pd
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                               QHBoxLayout, QGroupBox, QLabel, QComboBox, 
                               QLineEdit, QPushButton, QSlider, QCheckBox,
                               QRadioButton, QButtonGroup, QTableWidget,
                               QTabWidget, QFileDialog, QMessageBox, QSplitter,
                               QSpinBox, QDoubleSpinBox, QTextEdit, QListWidget)
from PySide6.QtCore import Qt, Signal, Slot
from PySide6.QtGui import QColor, QPalette
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.colors as mcolors

class MplCanvas(FigureCanvas):
    """Matplotlib画布类"""
    def __init__(self, parent=None, width=5, height=4, dpi=100):
        self.fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = self.fig.add_subplot(111)
        super().__init__(self.fig)
        self.setParent(parent)

class PlotPro2DLineGUI(QMainWindow):
    """主窗口类"""
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Acycle: Plot Pro 2D Line")
        self.setGeometry(100, 100, 1200, 800)
        
        # 初始化变量
        self.current_data = None
        self.dat_name = ""
        self.unit = ""
        self.unit_type = 0
        self.plot_list = []
        self.plot_list_ext = []
        self.plot_no_dir = ""
        self.nplot = 0
        self.plot_s = []
        self.lang_choice = 0  # 0=English, 1=其他语言
        self.lang_var = {}
        self.lang_id = []
        
        # 初始化UI
        self.init_ui()
        
        # 初始化颜色映射
        self.init_color_maps()
        
        # 加载默认设置
        self.load_default_settings()
    
    def init_ui(self):
        """初始化用户界面"""
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QHBoxLayout(central_widget)
        
        # 左侧控制面板
        control_panel = QTabWidget()
        control_panel.setMaximumWidth(400)
        
        # 添加标签页
        control_panel.addTab(self.create_data_panel(), "Data Panel")
        control_panel.addTab(self.create_font_panel(), "Font")
        control_panel.addTab(self.create_xyaxis_panel(), "X-Y Axis")
        control_panel.addTab(self.create_line_spec_panel(), "Line Spec")
        control_panel.addTab(self.create_marker_spec_panel(), "Marker Spec")
        
        # 右侧绘图区域
        plot_widget = QWidget()
        plot_layout = QVBoxLayout(plot_widget)
        
        #  matplotlib画布
        self.canvas = MplCanvas(self, width=10, height=8, dpi=100)
        plot_layout.addWidget(self.canvas)
        
        # 添加控制按钮
        button_layout = QHBoxLayout()
        self.update_btn = QPushButton("Update Plot")
        self.update_btn.clicked.connect(self.update_plot)
        self.save_btn = QPushButton("Save Plot")
        self.save_btn.clicked.connect(self.save_plot)
        button_layout.addWidget(self.update_btn)
        button_layout.addWidget(self.save_btn)
        plot_layout.addLayout(button_layout)
        
        # 分割左右面板
        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(control_panel)
        splitter.addWidget(plot_widget)
        splitter.setSizes([300, 900])
        
        main_layout.addWidget(splitter)
    
    def create_data_panel(self):
        """创建数据面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 所有面板设置
        full_group = QGroupBox("All Panel")
        full_layout = QHBoxLayout(full_group)
        full_layout.addWidget(QLabel("Format: row,col"))
        self.full_input = QLineEdit("1,1")
        full_layout.addWidget(self.full_input)
        layout.addWidget(full_group)
        
        # 设置面板
        set_group = QGroupBox("Set Panel")
        set_layout = QHBoxLayout(set_group)
        set_layout.addWidget(QLabel("Panel"))
        self.set_input = QComboBox()
        self.set_input.addItems(["1"])
        set_layout.addWidget(self.set_input)
        layout.addWidget(set_group)
        
        # 数据文件
        data_group = QGroupBox("Data File")
        data_layout = QHBoxLayout(data_group)
        data_layout.addWidget(QLabel("Data"))
        self.data_input = QComboBox()
        data_layout.addWidget(self.data_input)
        layout.addWidget(data_group)
        
        # X轴设置
        x_group = QGroupBox("X Axis")
        x_layout = QHBoxLayout(x_group)
        x_layout.addWidget(QLabel("X Column"))
        self.x_input = QLineEdit("1")
        x_layout.addWidget(self.x_input)
        layout.addWidget(x_group)
        
        # Y轴设置
        y_group = QGroupBox("Y Axis")
        y_layout = QHBoxLayout(y_group)
        y_layout.addWidget(QLabel("Y Columns"))
        self.y_input = QLineEdit("2")
        y_layout.addWidget(self.y_input)
        layout.addWidget(y_group)
        
        # Y轴数据ID列表
        y_i_group = QGroupBox("Y Data List")
        y_i_layout = QHBoxLayout(y_i_group)
        y_i_layout.addWidget(QLabel("Data ID"))
        self.y_i_input = QComboBox()
        y_i_layout.addWidget(self.y_i_input)
        layout.addWidget(y_i_group)
        
        # 连接信号
        self.full_input.textChanged.connect(self.update_full_panel)
        self.set_input.currentIndexChanged.connect(self.update_set_panel)
        self.data_input.currentIndexChanged.connect(self.update_data_panel)
        self.x_input.textChanged.connect(self.update_x_data)
        self.y_input.textChanged.connect(self.update_y_data)
        self.y_i_input.currentIndexChanged.connect(self.update_y_i_data)
        
        return panel
    
    def create_font_panel(self):
        """创建字体面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 标题设置
        title_group = QGroupBox("Title")
        title_layout = QHBoxLayout(title_group)
        title_layout.addWidget(QLabel("Title"))
        self.title_input = QLineEdit()
        title_layout.addWidget(self.title_input)
        layout.addWidget(title_group)
        
        # 图例设置
        legend_group = QGroupBox("Legend")
        legend_layout = QHBoxLayout(legend_group)
        self.legend_check = QCheckBox("Show Legend")
        legend_layout.addWidget(self.legend_check)
        self.legend_text = QLineEdit("Legend Text")
        legend_layout.addWidget(self.legend_text)
        self.legend_box_check = QCheckBox("Legend Box")
        legend_layout.addWidget(self.legend_box_check)
        layout.addWidget(legend_group)
        
        # 字体名称
        fontname_group = QGroupBox("Font Name")
        fontname_layout = QHBoxLayout(fontname_group)
        fontname_layout.addWidget(QLabel("Font"))
        self.fontname_input = QComboBox()
        # 添加系统字体
        fontname_layout.addWidget(self.fontname_input)
        layout.addWidget(fontname_group)
        
        # 字体大小
        fontsize_group = QGroupBox("Font Size")
        fontsize_layout = QHBoxLayout(fontsize_group)
        fontsize_layout.addWidget(QLabel("Size"))
        self.fontsize_input = QSpinBox()
        self.fontsize_input.setRange(6, 72)
        self.fontsize_input.setValue(12)
        fontsize_layout.addWidget(self.fontsize_input)
        layout.addWidget(fontsize_group)
        
        # 字体粗细
        fontweight_group = QGroupBox("Font Weight")
        fontweight_layout = QHBoxLayout(fontweight_group)
        self.fontweight_normal = QRadioButton("Normal")
        self.fontweight_bold = QRadioButton("Bold")
        self.fontweight_normal.setChecked(True)
        fontweight_group = QButtonGroup()
        fontweight_group.addButton(self.fontweight_normal)
        fontweight_group.addButton(self.fontweight_bold)
        fontweight_layout.addWidget(self.fontweight_normal)
        fontweight_layout.addWidget(self.fontweight_bold)
        layout.addWidget(fontweight_group)
        
        # 字体角度
        fontangle_group = QGroupBox("Font Angle")
        fontangle_layout = QHBoxLayout(fontangle_group)
        self.fontangle_normal = QRadioButton("Normal")
        self.fontangle_italic = QRadioButton("Italic")
        self.fontangle_normal.setChecked(True)
        fontangle_group = QButtonGroup()
        fontangle_group.addButton(self.fontangle_normal)
        fontangle_group.addButton(self.fontangle_italic)
        fontangle_layout.addWidget(self.fontangle_normal)
        fontangle_layout.addWidget(self.fontangle_italic)
        layout.addWidget(fontangle_group)
        
        # 连接信号
        self.title_input.textChanged.connect(self.update_plot)
        self.legend_check.stateChanged.connect(self.update_plot)
        self.legend_text.textChanged.connect(self.update_plot)
        self.legend_box_check.stateChanged.connect(self.update_plot)
        self.fontname_input.currentIndexChanged.connect(self.update_plot)
        self.fontsize_input.valueChanged.connect(self.update_plot)
        self.fontweight_normal.toggled.connect(self.update_plot)
        self.fontangle_normal.toggled.connect(self.update_plot)
        
        return panel
    
    def create_xyaxis_panel(self):
        """创建XY轴面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # X标签
        xlabel_group = QGroupBox("X Label")
        xlabel_layout = QHBoxLayout(xlabel_group)
        xlabel_layout.addWidget(QLabel("X Label"))
        self.xlabel_input = QLineEdit("X Axis")
        xlabel_layout.addWidget(self.xlabel_input)
        layout.addWidget(xlabel_group)
        
        # Y标签
        ylabel_group = QGroupBox("Y Label")
        ylabel_layout = QHBoxLayout(ylabel_group)
        ylabel_layout.addWidget(QLabel("Y Label"))
        self.ylabel_input = QLineEdit("Y Axis")
        ylabel_layout.addWidget(self.ylabel_input)
        layout.addWidget(ylabel_group)
        
        # X限制
        xlim_group = QGroupBox("X Limits")
        xlim_layout = QHBoxLayout(xlim_group)
        xlim_layout.addWidget(QLabel("Min"))
        self.xlim_low_input = QDoubleSpinBox()
        self.xlim_low_input.setRange(-1e10, 1e10)
        xlim_layout.addWidget(self.xlim_low_input)
        xlim_layout.addWidget(QLabel("Max"))
        self.xlim_high_input = QDoubleSpinBox()
        self.xlim_high_input.setRange(-1e10, 1e10)
        xlim_layout.addWidget(self.xlim_high_input)
        layout.addWidget(xlim_group)
        
        # Y限制
        ylim_group = QGroupBox("Y Limits")
        ylim_layout = QHBoxLayout(ylim_group)
        ylim_layout.addWidget(QLabel("Min"))
        self.ylim_low_input = QDoubleSpinBox()
        self.ylim_low_input.setRange(-1e10, 1e10)
        ylim_layout.addWidget(self.ylim_low_input)
        ylim_layout.addWidget(QLabel("Max"))
        self.ylim_high_input = QDoubleSpinBox()
        self.ylim_high_input.setRange(-1e10, 1e10)
        ylim_layout.addWidget(self.ylim_high_input)
        layout.addWidget(ylim_group)
        
        # 其他设置...
        # 这里省略了其他XY轴设置的代码
        
        # 连接信号
        self.xlabel_input.textChanged.connect(self.update_plot)
        self.ylabel_input.textChanged.connect(self.update_plot)
        self.xlim_low_input.valueChanged.connect(self.update_plot)
        self.xlim_high_input.valueChanged.connect(self.update_plot)
        self.ylim_low_input.valueChanged.connect(self.update_plot)
        self.ylim_high_input.valueChanged.connect(self.update_plot)
        
        return panel
    
    def create_line_spec_panel(self):
        """创建线型面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 线图类型
        lineplot_group = QGroupBox("Line Plot Type")
        lineplot_layout = QHBoxLayout(lineplot_group)
        lineplot_layout.addWidget(QLabel("Type"))
        self.lineplot_input = QComboBox()
        self.lineplot_input.addItems(["line", "stairs", "errorbar", "area"])
        lineplot_layout.addWidget(self.lineplot_input)
        layout.addWidget(lineplot_group)
        
        # 线型
        linestyle_group = QGroupBox("Line Style")
        linestyle_layout = QHBoxLayout(linestyle_group)
        linestyle_layout.addWidget(QLabel("Style"))
        self.linestyle_input = QComboBox()
        self.linestyle_input.addItems(["-", "--", ":", "-.", "none"])
        linestyle_layout.addWidget(self.linestyle_input)
        layout.addWidget(linestyle_group)
        
        # 线宽
        linewidth_group = QGroupBox("Line Width")
        linewidth_layout = QHBoxLayout(linewidth_group)
        linewidth_layout.addWidget(QLabel("Width"))
        self.linewidth_input = QComboBox()
        self.linewidth_input.addItems(["0.1", "0.2", "0.3", "0.4", "0.5", "0.7", "1", "1.5", "2", "3", "4", "5", "6", "7", "8", "9", "10", "12", "15", "20", "25", "30", "40", "50", "60", "70", "80", "100", "120"])
        self.linewidth_input.setCurrentIndex(8)  # 默认选择2
        linewidth_layout.addWidget(self.linewidth_input)
        layout.addWidget(linewidth_group)
        
        # 线颜色
        linecolor_group = QGroupBox("Line Color")
        linecolor_layout = QHBoxLayout(linecolor_group)
        self.linecolor_btn = QPushButton("Select Color")
        self.linecolor_btn.clicked.connect(self.select_line_color)
        linecolor_layout.addWidget(self.linecolor_btn)
        layout.addWidget(linecolor_group)
        
        # 连接信号
        self.lineplot_input.currentIndexChanged.connect(self.update_plot)
        self.linestyle_input.currentIndexChanged.connect(self.update_plot)
        self.linewidth_input.currentIndexChanged.connect(self.update_plot)
        
        return panel
    
    def create_marker_spec_panel(self):
        """创建标记面板"""
        panel = QWidget()
        layout = QVBoxLayout(panel)
        
        # 标记显示
        markershow_group = QGroupBox("Marker Show")
        markershow_layout = QHBoxLayout(markershow_group)
        self.markershow_yes = QRadioButton("Yes")
        self.markershow_no = QRadioButton("No")
        self.markershow_yes.setChecked(True)
        markershow_group = QButtonGroup()
        markershow_group.addButton(self.markershow_yes)
        markershow_group.addButton(self.markershow_no)
        markershow_layout.addWidget(self.markershow_yes)
        markershow_layout.addWidget(self.markershow_no)
        layout.addWidget(markershow_group)
        
        # 标记边缘显示
        markeredgeshow_group = QGroupBox("Marker Edge Show")
        markeredgeshow_layout = QHBoxLayout(markeredgeshow_group)
        self.markeredgeshow_yes = QRadioButton("Yes")
        self.markeredgeshow_no = QRadioButton("No")
        self.markeredgeshow_yes.setChecked(True)
        markeredgeshow_group = QButtonGroup()
        markeredgeshow_group.addButton(self.markeredgeshow_yes)
        markeredgeshow_group.addButton(self.markeredgeshow_no)
        markeredgeshow_layout.addWidget(self.markeredgeshow_yes)
        markeredgeshow_layout.addWidget(self.markeredgeshow_no)
        layout.addWidget(markeredgeshow_group)
        
        # 标记样式
        markerstyle_group = QGroupBox("Marker Style")
        markerstyle_layout = QHBoxLayout(markerstyle_group)
        markerstyle_layout.addWidget(QLabel("Style"))
        self.markerstyle_input = QComboBox()
        self.markerstyle_input.addItems(["none", "o", "+", "*", "x", "-", "|", "square", "diamond", "^", "v", ">", "<", "pentagram", "hexagram"])
        markerstyle_layout.addWidget(self.markerstyle_input)
        layout.addWidget(markerstyle_group)
        
        # 标记大小
        markersize_group = QGroupBox("Marker Size")
        markersize_layout = QHBoxLayout(markersize_group)
        markersize_layout.addWidget(QLabel("Size"))
        self.markersize_input = QLineEdit("50")
        markersize_layout.addWidget(self.markersize_input)
        layout.addWidget(markersize_group)
        
        # 标记透明度
        markeralpha_group = QGroupBox("Marker Alpha")
        markeralpha_layout = QHBoxLayout(markeralpha_group)
        self.markeralpha_slider = QSlider(Qt.Horizontal)
        self.markeralpha_slider.setRange(0, 100)
        self.markeralpha_slider.setValue(50)
        markeralpha_layout.addWidget(self.markeralpha_slider)
        layout.addWidget(markeralpha_group)
        
        # 标记颜色
        markerfacecolor_group = QGroupBox("Marker Face Color")
        markerfacecolor_layout = QHBoxLayout(markerfacecolor_group)
        self.markerfacecolor_btn = QPushButton("Select Color")
        self.markerfacecolor_btn.clicked.connect(self.select_marker_face_color)
        markerfacecolor_layout.addWidget(self.markerfacecolor_btn)
        layout.addWidget(markerfacecolor_group)
        
        # 标记边缘颜色
        markeredgecolor_group = QGroupBox("Marker Edge Color")
        markeredgecolor_layout = QHBoxLayout(markeredgecolor_group)
        self.markeredgecolor_btn = QPushButton("Select Color")
        self.markeredgecolor_btn.clicked.connect(self.select_marker_edge_color)
        markeredgecolor_layout.addWidget(self.markeredgecolor_btn)
        layout.addWidget(markeredgecolor_group)
        
        # 连接信号
        self.markershow_yes.toggled.connect(self.update_plot)
        self.markeredgeshow_yes.toggled.connect(self.update_plot)
        self.markerstyle_input.currentIndexChanged.connect(self.update_plot)
        self.markersize_input.textChanged.connect(self.update_plot)
        self.markeralpha_slider.valueChanged.connect(self.update_plot)
        
        return panel
    
    def init_color_maps(self):
        """初始化颜色映射"""
        self.c_map0 = [
            [0, 0.4470, 0.7410],
            [0.8500, 0.3250, 0.0980],
            [0.9290, 0.6940, 0.1250],
            [0.4940, 0.1840, 0.5560],
            [0.4660, 0.6740, 0.1880],
            [0.3010, 0.7450, 0.9330],
            [0.6350, 0.0780, 0.1840],
            [0.5700, 0.6900, 0.3000],
            [0.89, 0.88, 0.57],
            [0.76, 0.49, 0.58],
            [0.47, 0.76, 0.81],
            [0.21, 0.21, 0.35],
            [0.28, 0.57, 0.54],
            [0.07, 0.35, 0.40],
            [0.41, 0.20, 0.42],
            [0.60, 0.24, 0.18],
            [0.76, 0.84, 0.65],
            [0.77, 0.18, 0.78],
            [0.21, 0.33, 0.64],
            [0.88, 0.17, 0.56],
            [0.20, 0.69, 0.28],
            [0.26, 0.15, 0.47],
            [0.83, 0.27, 0.44],
            [0.87, 0.85, 0.42],
            [0.85, 0.51, 0.87],
            [0.99, 0.62, 0.76],
            [0.52, 0.43, 0.87],
            [0.00, 0.68, 0.92],
            [0.26, 0.45, 0.77],
            [0.98, 0.75, 0.00],
            [0.72, 0.81, 0.76],
            [0.77, 0.18, 0.78],
            [0.28, 0.39, 0.44],
            [0.22, 0.26, 0.24],
            [0.64, 0.52, 0.64],
            [0.87, 0.73, 0.78],
            [0.94, 0.89, 0.85],
            [0.85, 0.84, 0.86]
        ]
        
        self.c_map1 = [
            [0.57, 0.69, 0.30],
            [0.89, 0.88, 0.57],
            [0.76, 0.49, 0.58],
            [0.47, 0.76, 0.81],
            [0.21, 0.21, 0.35],
            [0.28, 0.57, 0.54],
            [0.07, 0.35, 0.40],
            [0.41, 0.20, 0.42],
            [0.60, 0.24, 0.18],
            [0.76, 0.84, 0.65]
        ]
        
        self.c_map2 = [
            [0.77, 0.18, 0.78],
            [0.21, 0.33, 0.64],
            [0.88, 0.17, 0.56],
            [0.20, 0.69, 0.28],
            [0.26, 0.15, 0.47],
            [0.83, 0.27, 0.44],
            [0.87, 0.85, 0.42],
            [0.85, 0.51, 0.87],
            [0.99, 0.62, 0.76],
            [0.52, 0.43, 0.87],
            [0.00, 0.68, 0.92],
            [0.26, 0.45, 0.77],
            [0.98, 0.75, 0.00],
            [0.72, 0.81, 0.76],
            [0.77, 0.18, 0.78],
            [0.28, 0.39, 0.44],
            [0.22, 0.26, 0.24],
            [0.64, 0.52, 0.64],
            [0.87, 0.73, 0.78],
            [0.94, 0.89, 0.85],
            [0.85, 0.84, 0.86]
        ]
    
    def load_default_settings(self):
        """加载默认设置"""
        # 这里应该从Excel文件加载设置，但为了简化，我们使用默认值
        self.plot_adv_setting = {
            'panel_nrow': 1,
            'panel_ncol': 1,
            'panel_i': 1,
            'x_axis_file': '',
            'x_axis_col': 1,
            'y_axis_file': '',
            'y_axis_col': 2,
            'title': 'Plot',
            'legend': 0,
            'legend_box': 0,
            'legend_text': 'Legend',
            'fontname': 'Arial',
            'fontsize': 12,
            'fontweight': 0,
            'fontangle': 0,
            'xlabel': 'X Axis',
            'ylabel': 'Y Axis',
            'xlim_low': 0,
            'xlim_high': 1,
            'ylim_low': 0,
            'ylim_high': 1,
            'xminortick': 0,
            'yminortick': 0,
            'grid': 0,
            'xdir': 1,
            'ydir': 1,
            'xscale': 1,
            'yscale': 1,
            'swap_xy': 0,
            'line_plot': 'line',
            'line_style': '-',
            'line_width': 2,
            'line_color': [0, 0.4470, 0.7410],
            'marker_face_show': 1,
            'marker_edge_show': 1,
            'marker_style': 'o',
            'marker_size': 50,
            'marker_alpha': 0.5,
            'marker_face_color': [0, 0.4470, 0.7410],
            'marker_edge_color': [0, 0.4470, 0.7410]
        }
    
    def load_data(self, file_paths):
        """加载数据文件"""
        self.plot_s = file_paths
        self.nplot = len(file_paths)
        
        # 更新数据文件列表
        self.data_input.clear()
        for path in file_paths:
            self.data_input.addItem(os.path.basename(path))
        
        # 加载第一个文件的数据
        if self.nplot > 0:
            self.dat_name = file_paths[0]
            try:
                self.current_data = np.loadtxt(file_paths[0])
                self.update_data_display()
            except Exception as e:
                QMessageBox.warning(self, "Error", f"Failed to load data: {str(e)}")
    
    def update_data_display(self):
        """更新数据显示"""
        if self.current_data is not None:
            # 设置X和Y轴的默认值
            self.x_input.setText("1")
            
            if self.current_data.shape[1] > 1:
                self.y_input.setText("2")
            else:
                self.y_input.setText("1")
            
            # 设置X和Y轴的范围
            x_col = int(self.x_input.text()) - 1  # 转换为0-based索引
            y_col = int(self.y_input.text()) - 1  # 转换为0-based索引
            
            if 0 <= x_col < self.current_data.shape[1]:
                x_data = self.current_data[:, x_col]
                self.xlim_low_input.setValue(np.min(x_data))
                self.xlim_high_input.setValue(np.max(x_data))
            
            if 0 <= y_col < self.current_data.shape[1]:
                y_data = self.current_data[:, y_col]
                self.ylim_low_input.setValue(np.min(y_data))
                self.ylim_high_input.setValue(np.max(y_data))
    
    def update_full_panel(self):
        """更新所有面板设置"""
        text = self.full_input.text()
        if ',' in text:
            try:
                rows, cols = map(int, text.split(','))
                # 更新面板数量
                self.set_input.clear()
                for i in range(1, rows * cols + 1):
                    self.set_input.addItem(str(i))
                
                # 更新设置
                self.plot_adv_setting['panel_nrow'] = rows
                self.plot_adv_setting['panel_ncol'] = cols
                
                self.update_plot()
            except ValueError:
                QMessageBox.warning(self, "Error", "Invalid format. Please use 'row,col' format.")
    
    def update_set_panel(self):
        """更新设置面板"""
        panel_i = int(self.set_input.currentText())
        self.plot_adv_setting['panel_i'] = panel_i
        self.update_plot()
    
    def update_data_panel(self):
        """更新数据面板"""
        if self.data_input.currentIndex() >= 0 and self.nplot > 0:
            file_name = self.data_input.currentText()
            self.plot_adv_setting['x_axis_file'] = file_name
            self.plot_adv_setting['y_axis_file'] = file_name
            
            # 加载选中的数据文件
            try:
                self.current_data = np.loadtxt(self.plot_s[self.data_input.currentIndex()])
                self.update_data_display()
            except Exception as e:
                QMessageBox.warning(self, "Error", f"Failed to load data: {str(e)}")
            
            self.update_plot()
    
    def update_x_data(self):
        """更新X轴数据"""
        try:
            x_col = int(self.x_input.text())
            self.plot_adv_setting['x_axis_col'] = x_col
            
            # 更新X轴范围
            if self.current_data is not None and 0 < x_col <= self.current_data.shape[1]:
                x_data = self.current_data[:, x_col - 1]  # 转换为0-based索引
                self.xlim_low_input.setValue(np.min(x_data))
                self.xlim_high_input.setValue(np.max(x_data))
            
            self.update_plot()
        except ValueError:
            QMessageBox.warning(self, "Error", "Invalid X column value.")
    
    def update_y_data(self):
        """更新Y轴数据"""
        try:
            y_cols = [int(col) for col in self.y_input.text().split(',')]
            # 这里简化处理，只使用第一个Y列
            if y_cols:
                self.plot_adv_setting['y_axis_col'] = y_cols[0]
                
                # 更新Y轴范围
                if self.current_data is not None and 0 < y_cols[0] <= self.current_data.shape[1]:
                    y_data = self.current_data[:, y_cols[0] - 1]  # 转换为0-based索引
                    self.ylim_low_input.setValue(np.min(y_data))
                    self.ylim_high_input.setValue(np.max(y_data))
            
            self.update_plot()
        except ValueError:
            QMessageBox.warning(self, "Error", "Invalid Y column value.")
    
    def update_y_i_data(self):
        """更新Y轴数据ID"""
        # 这个功能在简化版本中暂时不实现
        pass
    
    def select_line_color(self):
        """选择线条颜色"""
        color = QColorDialog.getColor()
        if color.isValid():
            self.plot_adv_setting['line_color'] = [color.redF(), color.greenF(), color.blueF()]
            self.update_plot()
    
    def select_marker_face_color(self):
        """选择标记面颜色"""
        color = QColorDialog.getColor()
        if color.isValid():
            self.plot_adv_setting['marker_face_color'] = [color.redF(), color.greenF(), color.blueF()]
            self.update_plot()
    
    def select_marker_edge_color(self):
        """选择标记边缘颜色"""
        color = QColorDialog.getColor()
        if color.isValid():
            self.plot_adv_setting['marker_edge_color'] = [color.redF(), color.greenF(), color.blueF()]
            self.update_plot()
    
    def update_plot(self):
        """更新绘图"""
        if self.current_data is None:
            return
        
        # 清除当前图形
        self.canvas.axes.clear()
        
        # 获取数据
        x_col = self.plot_adv_setting['x_axis_col'] - 1  # 转换为0-based索引
        y_col = self.plot_adv_setting['y_axis_col'] - 1  # 转换为0-based索引
        
        if x_col < 0 or x_col >= self.current_data.shape[1] or y_col < 0 or y_col >= self.current_data.shape[1]:
            QMessageBox.warning(self, "Error", "Invalid column index.")
            return
        
        x_data = self.current_data[:, x_col]
        y_data = self.current_data[:, y_col]
        
        # 绘制图形
        line_plot = self.plot_adv_setting['line_plot']
        
        if line_plot == 'line':
            self.canvas.axes.plot(x_data, y_data, 
                                 linestyle=self.plot_adv_setting['line_style'],
                                 linewidth=float(self.plot_adv_setting['line_width']),
                                 color=self.plot_adv_setting['line_color'])
        elif line_plot == 'stairs':
            self.canvas.axes.stairs(y_data, x_data, 
                                   color=self.plot_adv_setting['line_color'])
        # 其他绘图类型可以在这里添加
        
        # 添加标记
        if self.plot_adv_setting['marker_face_show'] or self.plot_adv_setting['marker_edge_show']:
            marker_style = self.plot_adv_setting['marker_style']
            if marker_style != 'none':
                face_color = self.plot_adv_setting['marker_face_color'] if self.plot_adv_setting['marker_face_show'] else 'none'
                edge_color = self.plot_adv_setting['marker_edge_color'] if self.plot_adv_setting['marker_edge_show'] else 'none'
                
                self.canvas.axes.scatter(x_data, y_data, 
                                        marker=marker_style,
                                        s=float(self.plot_adv_setting['marker_size']),
                                        facecolors=face_color,
                                        edgecolors=edge_color,
                                        alpha=self.plot_adv_setting['marker_alpha'])
        
        # 设置标题和标签
        self.canvas.axes.set_title(self.plot_adv_setting['title'])
        self.canvas.axes.set_xlabel(self.plot_adv_setting['xlabel'])
        self.canvas.axes.set_ylabel(self.plot_adv_setting['ylabel'])
        
        # 设置范围
        self.canvas.axes.set_xlim([self.plot_adv_setting['xlim_low'], self.plot_adv_setting['xlim_high']])
        self.canvas.axes.set_ylim([self.plot_adv_setting['ylim_low'], self.plot_adv_setting['ylim_high']])
        
        # 设置网格
        self.canvas.axes.grid(self.plot_adv_setting['grid'])
        
        # 刷新画布
        self.canvas.draw()
    
    def save_plot(self):
        """保存绘图"""
        file_path, _ = QFileDialog.getSaveFileName(self, "Save Plot", "", "PNG Files (*.png);;PDF Files (*.pdf);;SVG Files (*.svg)")
        if file_path:
            self.canvas.fig.savefig(file_path)
            QMessageBox.information(self, "Success", "Plot saved successfully.")


def strrep2(filename, pre, post):
    """
    移除HTML样式
    示例: foldername = strrep2(filename,'<HTML><FONT color="blue">','</FONT></HTML>')
    """
    try:
        # 如果文件名是HTML名称
        filename = filename.replace(pre, '')
        filename = filename.replace(post, '')
        return filename
    except:
        # 如果文件名是纯名称
        return filename


def menu_plotpro_2d_callback(plot_selected, listbox_contents, lang_choice=0, lang_var=None, lang_id=None):
    """
    MATLAB menu_plotpro_2d_Callback 的Python实现
    """
    if lang_var is None:
        lang_var = {}
    if lang_id is None:
        lang_id = []
    
    nplot = len(plot_selected)
    
    # 检查文件类型
    supported_extensions = ['.txt', '.csv', '.dat', '.xlsx', '.xls']
    image_extensions = ['.bmp', '.BMP', '.gif', '.GIF', '.jpg', '.jpeg', '.JPG', '.JPEG', '.png', '.PNG', '.tif', '.tiff', '.TIF', '.TIFF']
    
    plot_paths = []
    
    for i in range(nplot):
        plot_no = plot_selected[i]
        plot_filter_s = str(listbox_contents[plot_no])
        plot_filter_s = strrep2(plot_filter_s, '<HTML><FONT color="blue">', '</FONT></HTML>')
        
        if os.path.isdir(plot_filter_s):
            continue
        else:
            _, dat_name, ext = os.path.splitext(plot_filter_s)
            if ext in supported_extensions:
                plot_paths.append(plot_filter_s)
            elif ext in image_extensions:
                # 处理图像文件 - 这里简化处理
                try:
                    from PIL import Image
                    img = Image.open(plot_filter_s)
                    # 可以在这里添加图像显示逻辑
                    print(f"Image file: {dat_name}{ext}")
                except Exception as e:
                    print(f"Error opening image: {e}")
    
    if plot_paths:
        # 创建并显示绘图窗口
        app = QApplication.instance()
        if app is None:
            app = QApplication(sys.argv)
        
        plot_window = PlotPro2DLineGUI()
        plot_window.load_data(plot_paths)
        plot_window.show()
        
        return plot_window
    else:
        print("No valid data files selected.")
        return None


if __name__ == "__main__":
    # 示例用法
    app = QApplication(sys.argv)
    
    # 模拟MATLAB回调函数的参数
    plot_selected = [0]  # 假设选择了第一个文件
    listbox_contents = ["Example-La2004-1E.5T-1P-0-2000.txt"]  # 假设列表框中有一个文件
    
    window = menu_plotpro_2d_callback(plot_selected, listbox_contents)
    
    if window is not None:
        sys.exit(app.exec())