import sys
import os
import subprocess
import threading
import glob
import random
import math
import time
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QLabel, QLineEdit, QPushButton, QRadioButton, QButtonGroup,
                            QCheckBox, QComboBox, QTextEdit, QProgressBar, QFileDialog,
                            QMessageBox, QFrame, QSizePolicy, QSpinBox)
from PyQt5.QtCore import Qt, QSize, QTimer, QPoint, QRectF, QPropertyAnimation, pyqtProperty, QPointF, QEasingCurve, pyqtSignal, QObject
from PyQt5.QtGui import QPainter, QColor, QPen, QLinearGradient, QFont, QFontDatabase, QPixmap, QPainterPath
from PyQt5.QtSvg import QSvgRenderer

class BuildWorker(QObject):
    """打包工作线程"""
    progress_updated = pyqtSignal(int, str)
    log_message = pyqtSignal(str)
    finished = pyqtSignal(bool, str, bool)  # success, message, cancelled
    
    def __init__(self, cmd, working_dir):
        super().__init__()
        self.cmd = cmd
        self.working_dir = working_dir
        self.process = None
        self._is_cancelled = False
        self._lock = threading.Lock()
        
    def cancel(self):
        """取消打包"""
        with self._lock:
            self._is_cancelled = True
            if self.process:
                try:
                    self.process.terminate()
                except:
                    pass
    
    def is_cancelled(self):
        """检查是否已取消"""
        with self._lock:
            return self._is_cancelled
    
    def run(self):
        """运行打包过程"""
        success = False
        cancelled = False
        message = ""
        
        try:
            self.log_message.emit("\n开始打包...")
            self.log_message.emit(f"工作目录: {self.working_dir}")
            
            # 创建进程
            self.process = subprocess.Popen(
                self.cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                encoding="utf-8",
                errors="replace",
                shell=True,
                cwd=self.working_dir,
                creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 'nt' else 0
            )
            
            # 设置初始进度
            self.progress_updated.emit(5, "启动中...")
            
            # 读取输出并更新进度
            total_lines = 0
            stages = [
                ("分析模块", 0, 20),
                ("收集文件", 20, 40),
                ("打包程序", 40, 80),
                ("写入文件", 80, 95),
                ("完成", 95, 100)
            ]
            current_stage_idx = 0
            
            # 读取进程输出
            while True:
                # 检查是否被取消
                if self.is_cancelled():
                    cancelled = True
                    if self.process:
                        self.process.terminate()
                    self.log_message.emit("打包已取消")
                    break
                
                # 读取一行输出
                line = self.process.stdout.readline()
                if not line and self.process.poll() is not None:
                    break
                
                if line:
                    line = line.strip()
                    self.log_message.emit(line)
                    total_lines += 1
                    
                    # 简单的进度模拟 - 基于行数和关键词
                    if total_lines > 0:
                        # 根据输出内容判断阶段
                        if "Analyzing" in line or "分析" in line:
                            current_stage_idx = 0
                        elif "Collecting" in line or "收集" in line or "collecting" in line.lower():
                            current_stage_idx = 1
                        elif "Packaging" in line or "打包" in line or "building" in line.lower():
                            current_stage_idx = 2
                        elif "Writing" in line or "写入" in line or "writing" in line.lower():
                            current_stage_idx = 3
                        elif "completed successfully" in line or "成功完成" in line or "Building" in line:
                            current_stage_idx = 4
                        
                        # 在当前阶段内模拟进度
                        stage_name, stage_start, stage_end = stages[current_stage_idx]
                        stage_progress = min(100, (total_lines % 30) * 3)  # 每30行一个周期
                        progress = stage_start + (stage_end - stage_start) * stage_progress / 100
                        
                        self.progress_updated.emit(int(progress), f"{stage_name}... {int(progress)}%")
            
            # 等待进程结束
            return_code = self.process.wait()
            
            if cancelled:
                message = "打包已取消"
                self.progress_updated.emit(70, "正在取消...")
            elif return_code == 0:
                success = True
                message = "打包完成!"
                self.progress_updated.emit(100, "✓ 打包完成 100%")
            else:
                message = f"打包失败，返回码: {return_code}"
                self.progress_updated.emit(90, "✗ 打包失败")
                
        except Exception as e:
            success = False
            message = f"发生异常: {str(e)}"
            self.log_message.emit(f"\n✗ {message}")
            self.progress_updated.emit(50, "✗ 发生异常")
            
        finally:
            # 发送完成信号
            self.finished.emit(success, message, cancelled)

class ECGLogWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMinimumHeight(180)
        self.setStyleSheet("background-color: #0a0a1a; border: 1px solid #00aaff; border-radius: 5px;")
        
        # ECG波形数据
        self.ecg_data = []
        self.max_points = 300
        self.x_spacing = 3
        self.amplitude = 50  # 增大幅度
        self.heartbeat_counter = 0
        self.is_active = False  # 是否处于活动状态（打包中）
        self.is_finished = False  # 是否完成
        
        # ECG波形参数（模拟真实心电图）
        self.heart_rate = 75  # 心率（次/分钟）
        
        # 定时器更新波形
        self.update_timer = QTimer(self)
        self.update_timer.timeout.connect(self.update_ecg)
        self.update_timer.start(30)  # 约33 FPS
        
        # 日志消息
        self.log_messages = []
        self.current_message = ""
        self.message_index = 0
        self.char_index = 0
        self.text_timer = QTimer(self)
        self.text_timer.timeout.connect(self.update_text)
        self.text_timer.start(100)
        
        # 样式设置
        self.font = QFont("Consolas", 10)
        self.font.setBold(True)
        self.text_color = QColor(0, 255, 255)
        self.ecg_color = QColor(0, 255, 0, 220)  # 更亮的绿色
        self.grid_color = QColor(0, 170, 255, 40)  # 更明显的网格
        self.pulse_color = QColor(255, 255, 255, 150)
        self.baseline_color = QColor(100, 100, 100, 100)
        
        # 初始化ECG数据
        for i in range(self.max_points):
            self.ecg_data.append(self.generate_ecg_point(i))
    
    def generate_ecg_point(self, index):
        """生成逼真的ECG波形点"""
        if not self.is_active:
            # 非活动状态显示平线
            return 0.0
        
        if self.is_finished:
            # 完成状态显示平线
            return 0.0
        
        # 计算基于时间的x坐标
        x = index * 0.05 + self.heartbeat_counter * 0.5
        
        # 计算心跳周期（基于心率）
        heartbeat_interval = 60.0 / self.heart_rate  # 每个心跳的秒数
        t_cycle = x / heartbeat_interval
        cycle_position = t_cycle - math.floor(t_cycle)
        
        # 模拟真实心电图波形
        value = 0.0
        
        # P波（心房除极） - 位置0.0-0.2
        if 0.0 <= cycle_position < 0.2:
            # 使用正弦波模拟P波
            p_position = cycle_position / 0.2
            value = 0.15 * math.sin(p_position * math.pi)
        
        # QRS复合波（心室除极） - 位置0.2-0.28
        elif 0.2 <= cycle_position < 0.28:
            qrs_position = (cycle_position - 0.2) / 0.08
            
            # 模拟Q波（负向）
            if qrs_position < 0.2:
                value = -0.2 * (qrs_position / 0.2)
            # 模拟R波（正向尖峰）
            elif qrs_position < 0.5:
                r_pos = (qrs_position - 0.2) / 0.3
                # 使用高斯函数模拟R波尖峰
                value = 1.0 * math.exp(-((r_pos - 0.5) ** 2) * 10)
            # 模拟S波（负向）
            else:
                s_pos = (qrs_position - 0.5) / 0.5
                value = -0.3 * (1 - s_pos)
        
        # T波（心室复极） - 位置0.4-0.6
        elif 0.4 <= cycle_position < 0.6:
            t_position = (cycle_position - 0.4) / 0.2
            # T波通常比P波宽且圆润
            value = 0.3 * math.sin(t_position * math.pi) * 0.7
        
        # 添加一些随机噪声（模拟真实ECG信号）
        if self.is_active and not self.is_finished:
            noise = random.uniform(-0.02, 0.02)
            value += noise
        
        # 添加呼吸引起的基线漂移
        if self.is_active and not self.is_finished:
            breathing = 0.05 * math.sin(x * 0.3)
            value += breathing
        
        return value
    
    def update_ecg(self):
        """更新ECG波形"""
        if self.is_active and not self.is_finished:
            self.heartbeat_counter += 0.02  # 减慢速度
        
        # 移动数据
        self.ecg_data.pop(0)
        new_index = len(self.ecg_data)
        self.ecg_data.append(self.generate_ecg_point(new_index))
        
        self.update()
    
    def start_activity(self):
        """开始活动（打包开始）"""
        self.is_active = True
        self.is_finished = False
        self.heartbeat_counter = 0
        # 打包时心率稍微加快
        self.heart_rate = 85
        self.log_messages.clear()
        self.current_message = ""
        self.message_index = 0
        self.char_index = 0
    
    def stop_activity(self, success=True):
        """停止活动（打包结束）"""
        self.is_active = False
        self.is_finished = True
        # 完成后心率恢复正常
        self.heart_rate = 65
        if success:
            self.add_log("✓ 打包完成！")
        else:
            self.add_log("✗ 打包失败！")
    
    def add_log(self, message):
        """添加日志消息"""
        self.log_messages.append(message)
        if len(self.log_messages) > 100:
            self.log_messages.pop(0)
    
    def update_text(self):
        """更新文本显示"""
        if not self.log_messages:
            return
        
        if self.message_index >= len(self.log_messages):
            self.message_index = 0
            self.char_index = 0
            return
        
        current_message = self.log_messages[self.message_index]
        if self.char_index < len(current_message):
            self.current_message = current_message[:self.char_index+1]
            self.char_index += 1
        else:
            self.message_index += 1
            self.char_index = 0
            if self.message_index < len(self.log_messages):
                self.current_message = ""
        
        self.update()
    
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        width = self.width()
        height = self.height()
        
        # 绘制更密集的网格（模拟真实心电图仪）
        painter.setPen(QPen(self.grid_color, 0.5, Qt.SolidLine))
        small_grid = 10
        large_grid = 50
        
        # 小网格
        for x in range(0, width, small_grid):
            painter.drawLine(x, 0, x, height)
        for y in range(0, height, small_grid):
            painter.drawLine(0, y, width, y)
        
        # 大网格（更明显的线）
        painter.setPen(QPen(self.grid_color, 1, Qt.SolidLine))
        for x in range(0, width, large_grid):
            painter.drawLine(x, 0, x, height)
        for y in range(0, height, large_grid):
            painter.drawLine(0, y, width, y)
        
        # 绘制ECG波形
        if self.ecg_data:
            path = QPainterPath()
            
            # 计算垂直位置（稍微偏上，给文本留空间）
            center_y = height // 2 + 20
            
            # 绘制基线（更明显）
            painter.setPen(QPen(self.baseline_color, 1.5, Qt.DashLine))
            painter.drawLine(0, center_y, width, center_y)
            
            # 创建ECG路径 - 修复：确保路径在可见范围内
            visible_points = min(len(self.ecg_data), width // self.x_spacing + 1)
            
            for i in range(visible_points):
                x = i * self.x_spacing
                if x > width:  # 确保不超出边界
                    break
                    
                value = self.ecg_data[i]
                y = center_y - value * self.amplitude
                
                # 确保y在合理范围内
                y = max(10, min(height - 10, y))
                
                if i == 0:
                    path.moveTo(x, y)
                else:
                    path.lineTo(x, y)
            
            # 绘制ECG波形（更粗的线）
            ecg_pen = QPen(self.ecg_color, 2.5, Qt.SolidLine)
            ecg_pen.setCapStyle(Qt.RoundCap)
            ecg_pen.setJoinStyle(Qt.RoundJoin)
            painter.setPen(ecg_pen)
            painter.drawPath(path)
            
            # 绘制脉冲点（只在活动状态下）
            if self.is_active and not self.is_finished and len(self.ecg_data) > 10:
                try:
                    # 找到R波的位置（最大值）
                    max_index = max(range(len(self.ecg_data)), key=lambda i: self.ecg_data[i])
                    if max_index < len(self.ecg_data) - 10 and max_index * self.x_spacing < width:  # 确保有足够的空间绘制
                        pulse_x = max_index * self.x_spacing
                        pulse_y = center_y - self.ecg_data[max_index] * self.amplitude
                        
                        # 确保y在合理范围内
                        pulse_y = max(10, min(height - 10, pulse_y))
                        
                        # 绘制R波标记
                        painter.setPen(Qt.NoPen)
                        
                        # 外圈光晕
                        painter.setBrush(QColor(255, 255, 255, 50))
                        painter.drawEllipse(QPointF(pulse_x, pulse_y), 8, 8)
                        
                        # 内圈
                        painter.setBrush(self.pulse_color)
                        painter.drawEllipse(QPointF(pulse_x, pulse_y), 4, 4)
                except (ValueError, IndexError):
                    pass  # 忽略可能的错误
        
        # 绘制状态文本
        status_text = ""
        status_color = QColor(0, 255, 0)
        if self.is_active and not self.is_finished:
            status_text = "打包中..."
            status_color = QColor(255, 255, 0)
            
            # 显示模拟心率
            hr_text = f"HR: {self.heart_rate} bpm"
            painter.setFont(QFont("Arial", 9, QFont.Bold))
            painter.setPen(QColor(255, 100, 100))
            painter.drawText(width - 80, 20, hr_text)
            
        elif self.is_finished:
            status_text = "准备就绪"
            status_color = QColor(0, 255, 0)
        else:
            status_text = "等待开始"
            status_color = QColor(100, 100, 255)
        
        painter.setFont(QFont("Arial", 11, QFont.Bold))
        painter.setPen(status_color)
        painter.drawText(10, 20, status_text)
        
        # 绘制日志文本区域背景
        text_bg = QRectF(5, height - 40, width - 10, 35)
        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(0, 0, 0, 150))
        painter.drawRoundedRect(text_bg, 3, 3)
        
        # 绘制日志文本
        if self.current_message:
            painter.setFont(self.font)
            painter.setPen(self.text_color)
            text_rect = QRectF(10, height - 35, width - 20, 30)
            painter.drawText(text_rect, Qt.AlignLeft | Qt.AlignVCenter, self.current_message)

class TechProgressBar(QProgressBar):
    def __init__(self, parent=None):
        super().__init__(parent)
        self._glow = 0  # 初始化 _glow 属性
        self._success = True  # 标记是否成功
        self._cancelled = False  # 标记是否取消
        
        # 基础样式
        self.setStyleSheet("""
            QProgressBar {
                border: 2px solid #00aaff;
                border-radius: 5px;
                text-align: center;
                background: #0a0a2a;
                color: white;
                font-weight: bold;
            }
            QProgressBar::chunk {
                background: qlineargradient(
                    x1:0, y1:0, x2:1, y2:0,
                    stop:0 #00aaff, stop:0.5 #aa00ff, stop:1 #ff00aa
                );
                border-radius: 3px;
            }
        """)
        self.setTextVisible(True)
        self.setValue(0)
        
        # 发光动画
        self.glow_animation = QPropertyAnimation(self, b"glow")
        self.glow_animation.setDuration(1000)
        self.glow_animation.setLoopCount(-1)
        self.glow_animation.setStartValue(0)
        self.glow_animation.setEndValue(100)
        self.glow_animation.start()
        
        # 进度还原动画
        self.reset_animation = QPropertyAnimation(self, b"value")
        self.reset_animation.setDuration(800)
        self.reset_animation.setEasingCurve(QEasingCurve.OutCubic)
        
    def get_glow(self):
        return self._glow
        
    def set_glow(self, value):
        self._glow = value
        self.update()
        
    glow = pyqtProperty(int, get_glow, set_glow)
    
    def set_status(self, success=True, cancelled=False):
        """设置状态"""
        self._success = success
        self._cancelled = cancelled
        
        if cancelled:
            style = """
                QProgressBar {
                    border: 2px solid #ffaa00;
                    border-radius: 5px;
                    text-align: center;
                    background: #0a0a2a;
                    color: white;
                    font-weight: bold;
                }
                QProgressBar::chunk {
                    background: qlineargradient(
                        x1:0, y1:0, x2:1, y2:0,
                        stop:0 #ffaa00, stop:0.5 #ff5500, stop:1 #ff0000
                    );
                    border-radius: 3px;
                }
            """
        elif success:
            style = """
                QProgressBar {
                    border: 2px solid #00ffaa;
                    border-radius: 5px;
                    text-align: center;
                    background: #0a0a2a;
                    color: white;
                    font-weight: bold;
                }
                QProgressBar::chunk {
                    background: qlineargradient(
                        x1:0, y1:0, x2:1, y2:0,
                        stop:0 #00ffaa, stop:0.5 #00aaff, stop:1 #00aaff
                    );
                    border-radius: 3px;
                }
            """
        else:
            style = """
                QProgressBar {
                    border: 2px solid #ff5555;
                    border-radius: 5px;
                    text-align: center;
                    background: #0a0a2a;
                    color: white;
                    font-weight: bold;
                }
                QProgressBar::chunk {
                    background: qlineargradient(
                        x1:0, y1:0, x2:1, y2:0,
                        stop:0 #ff5555, stop:0.5 #ff0000, stop:1 #aa0000
                    );
                    border-radius: 3px;
                }
            """
        
        self.setStyleSheet(style)
        self.update()
    
    def reset_to_zero(self, success=True, cancelled=False):
        """重置进度条到0"""
        self.set_status(success, cancelled)
        
        # 设置进度还原动画
        current_value = self.value()
        self.reset_animation.setStartValue(current_value)
        self.reset_animation.setEndValue(0)
        
        # 动画结束后显示状态文本
        self.reset_animation.finished.connect(lambda: self._on_reset_finished(success, cancelled))
        self.reset_animation.start()
    
    def _on_reset_finished(self, success, cancelled):
        """重置动画完成后的处理"""
        if cancelled:
            self.setFormat("⚠ 已取消")
        elif success:
            self.setFormat("✓ 打包完成")
        else:
            self.setFormat("✗ 打包失败")
        self.update()
    
    def paintEvent(self, event):
        super().paintEvent(event)
        
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        # 只在活动状态下绘制发光效果
        if self.value() > 0 and self.value() < 100:
            glow_width = int(self.width() * (self.value() / 100))
            glow_rect = QRectF(0, 0, glow_width, self.height())
            
            # 根据状态选择颜色
            if self._cancelled:
                gradient = QLinearGradient(0, 0, glow_width, 0)
                gradient.setColorAt(0, QColor(255, 170, 0, 30 + self._glow))
                gradient.setColorAt(0.5, QColor(255, 85, 0, 30 + self._glow))
                gradient.setColorAt(1, QColor(255, 0, 0, 30 + self._glow))
            elif self._success:
                gradient = QLinearGradient(0, 0, glow_width, 0)
                gradient.setColorAt(0, QColor(0, 255, 170, 30 + self._glow))
                gradient.setColorAt(0.5, QColor(0, 170, 255, 30 + self._glow))
                gradient.setColorAt(1, QColor(0, 170, 255, 30 + self._glow))
            else:
                gradient = QLinearGradient(0, 0, glow_width, 0)
                gradient.setColorAt(0, QColor(255, 85, 85, 30 + self._glow))
                gradient.setColorAt(0.5, QColor(255, 0, 0, 30 + self._glow))
                gradient.setColorAt(1, QColor(170, 0, 0, 30 + self._glow))
            
            painter.setPen(Qt.NoPen)
            painter.setBrush(gradient)
            painter.drawRoundedRect(glow_rect, 3, 3)
            
            # 绘制脉冲效果
            pulse_pos = int(glow_width * (self._glow / 100))
            pulse_width = 20
            pulse_rect = QRectF(pulse_pos - pulse_width//2, 0, pulse_width, self.height())
            
            pulse_gradient = QLinearGradient(pulse_rect.left(), 0, pulse_rect.right(), 0)
            if self._cancelled:
                pulse_gradient.setColorAt(0, QColor(255, 220, 170, 0))
                pulse_gradient.setColorAt(0.5, QColor(255, 200, 100, 150))
                pulse_gradient.setColorAt(1, QColor(255, 220, 170, 0))
            elif self._success:
                pulse_gradient.setColorAt(0, QColor(255, 255, 255, 0))
                pulse_gradient.setColorAt(0.5, QColor(255, 255, 255, 150))
                pulse_gradient.setColorAt(1, QColor(255, 255, 255, 0))
            else:
                pulse_gradient.setColorAt(0, QColor(255, 200, 200, 0))
                pulse_gradient.setColorAt(0.5, QColor(255, 150, 150, 150))
                pulse_gradient.setColorAt(1, QColor(255, 200, 200, 0))
            
            painter.setBrush(pulse_gradient)
            painter.drawRoundedRect(pulse_rect, 3, 3)

class PyInstallerGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Python转exe一键打包工具 v3.0")
        self.setGeometry(100, 100, 800, 700)
        
        # 统一的样式表
        self.setStyleSheet("""
            QMainWindow {
                background-color: #0a0a1a;
            }
            QLabel {
                color: #00aaff;
                font-size: 12px;
                font-weight: bold;
            }
            QLineEdit, QComboBox {
                background-color: #0a0a2a;
                border: 1px solid #00aaff;
                color: #ffffff;
                padding: 5px;
                selection-background-color: #aa00ff;
                border-radius: 3px;
            }
            QPushButton {
                background-color: #0a0a2a;
                border: 1px solid #00aaff;
                color: #00aaff;
                padding: 5px 10px;
                min-width: 80px;
                border-radius: 3px;
            }
            QPushButton:hover {
                background-color: #00aaff;
                color: #0a0a1a;
            }
            QPushButton:pressed {
                background-color: #aa00ff;
                border-color: #aa00ff;
            }
            QRadioButton {
                color: #00aaff;
                spacing: 5px;
                font-weight: bold;
            }
            QRadioButton::indicator {
                width: 18px;
                height: 18px;
                border: 2px solid #00aaff;
                border-radius: 9px;
                background-color: #0a0a2a;
            }
            QRadioButton::indicator:checked {
                background-color: #00aaff;
                border: 2px solid #00aaff;
            }
            QRadioButton::indicator:hover {
                border: 2px solid #00ffff;
            }
            QCheckBox {
                color: #00aaff;
                spacing: 5px;
                font-weight: bold;
            }
            QCheckBox::indicator {
                width: 18px;
                height: 18px;
                border: 2px solid #00aaff;
                background-color: #0a0a2a;
                border-radius: 3px;
            }
            QCheckBox::indicator:checked {
                background-color: #00aaff;
                border: 2px solid #00aaff;
            }
            QCheckBox::indicator:checked:hover {
                background-color: #00ffff;
                border: 2px solid #00ffff;
            }
            QCheckBox::indicator:hover {
                border: 2px solid #00ffff;
            }
            QGroupBox {
                border: 1px solid #00aaff;
                border-radius: 5px;
                margin-top: 10px;
                padding-top: 15px;
                color: #00aaff;
                font-weight: bold;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 3px;
            }
            QFrame {
                border-radius: 5px;
            }
        """)
        
        # 打包工作线程
        self.worker = None
        self.worker_thread = None
        
        self.init_ui()
        
    def init_ui(self):
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(15)
        
        # 模式选择
        mode_group = QButtonGroup(self)
        
        mode_layout = QHBoxLayout()
        mode_label = QLabel("打包模式:")
        self.file_mode = QRadioButton("单文件模式")
        self.folder_mode = QRadioButton("项目文件夹模式")
        self.file_mode.setChecked(True)
        
        mode_group.addButton(self.file_mode)
        mode_group.addButton(self.folder_mode)
        
        mode_layout.addWidget(mode_label)
        mode_layout.addWidget(self.file_mode)
        mode_layout.addWidget(self.folder_mode)
        mode_layout.addStretch()
        
        main_layout.addLayout(mode_layout)
        
        # 文件选择框架
        file_frame = QFrame()
        file_frame.setFrameShape(QFrame.StyledPanel)
        file_frame.setStyleSheet("border: 1px solid #00aaff;")
        file_layout = QVBoxLayout(file_frame)
        file_layout.setContentsMargins(10, 20, 10, 10)
        
        # 单文件模式组件
        self.script_layout = QHBoxLayout()
        self.script_label = QLabel("Python 脚本:")
        self.script_entry = QLineEdit()
        self.script_button = QPushButton("浏览...")
        self.script_button.clicked.connect(self.browse_script)
        
        self.script_layout.addWidget(self.script_label)
        self.script_layout.addWidget(self.script_entry)
        self.script_layout.addWidget(self.script_button)
        
        # 文件夹模式组件
        self.folder_layout = QHBoxLayout()
        self.folder_label = QLabel("项目文件夹:")
        self.folder_entry = QLineEdit()
        self.folder_button = QPushButton("浏览...")
        self.folder_button.clicked.connect(self.browse_folder)
        
        self.folder_layout.addWidget(self.folder_label)
        self.folder_layout.addWidget(self.folder_entry)
        self.folder_layout.addWidget(self.folder_button)
        
        # 入口文件选择
        self.entry_layout = QHBoxLayout()
        self.entry_label = QLabel("入口文件:")
        self.entry_combobox = QComboBox()
        self.entry_combobox.setEditable(False)
        self.detect_button = QPushButton("自动检测")
        self.detect_button.clicked.connect(self.detect_entry_points)
        
        self.entry_layout.addWidget(self.entry_label)
        self.entry_layout.addWidget(self.entry_combobox)
        self.entry_layout.addWidget(self.detect_button)
        
        # 应用名称
        self.name_layout = QHBoxLayout()
        self.name_label = QLabel("应用名称:")
        self.name_entry = QLineEdit()
        
        self.name_layout.addWidget(self.name_label)
        self.name_layout.addWidget(self.name_entry)
        
        file_layout.addLayout(self.script_layout)
        file_layout.addLayout(self.folder_layout)
        file_layout.addLayout(self.entry_layout)
        file_layout.addLayout(self.name_layout)
        
        main_layout.addWidget(file_frame)
        
        # 图标文件选择
        icon_layout = QHBoxLayout()
        self.icon_label = QLabel("图标文件 (.ico):")
        self.icon_entry = QLineEdit()
        self.icon_button = QPushButton("浏览...")
        self.icon_button.clicked.connect(self.browse_icon)
        
        icon_layout.addWidget(self.icon_label)
        icon_layout.addWidget(self.icon_entry)
        icon_layout.addWidget(self.icon_button)
        icon_layout.addStretch()
        
        main_layout.addLayout(icon_layout)
        
        # 打包选项框架
        options_frame = QFrame()
        options_frame.setFrameShape(QFrame.StyledPanel)
        options_frame.setStyleSheet("border: 1px solid #00aaff;")
        options_layout = QVBoxLayout(options_frame)
        options_layout.setContentsMargins(10, 20, 10, 10)
        options_layout.setSpacing(10)
        
        # 修复复选框显示 - 只在框中显示✔
        self.onefile_check = QCheckBox("打包为单个文件 (--onefile)")
        self.onefile_check.setChecked(True)
        
        self.windowed_check = QCheckBox("无控制台窗口 (--windowed)")
        self.windowed_check.setChecked(True)
        
        self.upx_check = QCheckBox("使用 UPX 压缩 (需安装 UPX)")
        
        options_layout.addWidget(self.onefile_check)
        options_layout.addWidget(self.windowed_check)
        options_layout.addWidget(self.upx_check)
        
        main_layout.addWidget(options_frame)
        
        # 输出目录
        output_layout = QHBoxLayout()
        
        self.output_label = QLabel("输出目录:")
        self.output_entry = QLineEdit()
        self.output_entry.setText(os.path.join(os.getcwd(), "dist"))
        self.output_button = QPushButton("浏览...")
        self.output_button.clicked.connect(self.browse_output)
        
        output_layout.addWidget(self.output_label)
        output_layout.addWidget(self.output_entry)
        output_layout.addWidget(self.output_button)
        
        main_layout.addLayout(output_layout)
        
        # 日志区域
        log_label = QLabel("打包状态：")
        main_layout.addWidget(log_label)
        
        self.ecg_log = ECGLogWidget()
        main_layout.addWidget(self.ecg_log)
        
        # 进度条
        self.progress = TechProgressBar()
        main_layout.addWidget(self.progress)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        # 打包按钮
        self.build_button = QPushButton("开始打包")
        self.build_button.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                          stop:0 #00aaff, stop:0.5 #aa00ff, stop:1 #ff00aa);
                color: #0a0a1a;
                font-weight: bold;
                font-size: 14px;
                padding: 12px;
                border: 2px solid #00aaff;
                border-radius: 5px;
                min-width: 120px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                          stop:0 #00ffff, stop:0.5 #ff00ff, stop:1 #ff55aa);
                border-color: #00ffff;
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                          stop:0 #0088cc, stop:0.5 #8800cc, stop:1 #cc0088);
                border-color: #aa00ff;
            }
            QPushButton:disabled {
                background: #0a0a2a;
                color: #666666;
                border-color: #666666;
            }
        """)
        self.build_button.clicked.connect(self.start_build)
        
        # 取消按钮
        self.cancel_button = QPushButton("取消打包")
        self.cancel_button.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                          stop:0 #ffaa00, stop:0.5 #ff5500, stop:1 #ff0000);
                color: #0a0a1a;
                font-weight: bold;
                font-size: 14px;
                padding: 12px;
                border: 2px solid #ffaa00;
                border-radius: 5px;
                min-width: 120px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                          stop:0 #ffcc00, stop:0.5 #ff7700, stop:1 #ff3333);
                border-color: #ffcc00;
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                                          stop:0 #cc8800, stop:0.5 #cc4400, stop:1 #cc0000);
                border-color: #ff5500;
            }
            QPushButton:disabled {
                background: #0a0a2a;
                color: #666666;
                border-color: #666666;
            }
        """)
        self.cancel_button.clicked.connect(self.cancel_build)
        self.cancel_button.setEnabled(False)
        
        button_layout.addStretch()
        button_layout.addWidget(self.build_button)
        button_layout.addWidget(self.cancel_button)
        button_layout.addStretch()
        
        main_layout.addLayout(button_layout)
        
        # 初始化UI状态
        self.update_mode()
        
        # 连接信号
        self.file_mode.toggled.connect(self.update_mode)
        
    def update_mode(self):
        """更新UI模式状态"""
        is_file_mode = self.file_mode.isChecked()
        
        self.script_label.setVisible(is_file_mode)
        self.script_entry.setVisible(is_file_mode)
        self.script_button.setVisible(is_file_mode)
        
        self.folder_label.setVisible(not is_file_mode)
        self.folder_entry.setVisible(not is_file_mode)
        self.folder_button.setVisible(not is_file_mode)
        
        self.entry_label.setVisible(not is_file_mode)
        self.entry_combobox.setVisible(not is_file_mode)
        self.detect_button.setVisible(not is_file_mode)
        
        self.name_label.setVisible(not is_file_mode)
        self.name_entry.setVisible(not is_file_mode)
        
    def browse_script(self):
        filepath, _ = QFileDialog.getOpenFileName(
            self, "选择 Python 脚本", "", "Python 文件 (*.py);;所有文件 (*.*)"
        )
        if filepath:
            self.script_entry.setText(filepath)
            script_dir = os.path.dirname(filepath)
            self.output_entry.setText(os.path.join(script_dir, "dist"))
            
    def browse_folder(self):
        dirpath = QFileDialog.getExistingDirectory(self, "选择项目文件夹")
        if dirpath:
            self.folder_entry.setText(dirpath)
            self.detect_entry_points()
            folder_name = os.path.basename(dirpath)
            self.name_entry.setText(folder_name)
            self.output_entry.setText(os.path.join(dirpath, "dist"))
            
    def detect_entry_points(self):
        """自动检测项目中的入口文件"""
        folder_path = self.folder_entry.text()
        if not folder_path or not os.path.isdir(folder_path):
            return
            
        patterns = [
            "main.py",
            "app.py",
            "run.py",
            "start.py",
            "*main*.py",
            "*app*.py"
        ]
        
        entry_files = []
        for pattern in patterns:
            entry_files.extend(glob.glob(os.path.join(folder_path, pattern)))
        
        entry_files = sorted(list(set(entry_files)))
        
        if entry_files:
            relative_paths = [os.path.relpath(f, folder_path) for f in entry_files]
            self.entry_combobox.clear()
            self.entry_combobox.addItems(relative_paths)
            self.entry_combobox.setCurrentIndex(0)
        else:
            self.entry_combobox.clear()
            QMessageBox.warning(self, "警告", "未检测到可能的入口文件")
            
    def browse_icon(self):
        filepath, _ = QFileDialog.getOpenFileName(
            self, "选择图标文件", "", "图标文件 (*.ico);;所有文件 (*.*)"
        )
        if filepath:
            self.icon_entry.setText(filepath)
            
    def browse_output(self):
        dirpath = QFileDialog.getExistingDirectory(self, "选择输出目录")
        if dirpath:
            self.output_entry.setText(dirpath)
            
    def log(self, message):
        self.ecg_log.add_log(message)
        
    def start_build(self):
        # 开始ECG动画
        self.ecg_log.start_activity()
        
        if self.file_mode.isChecked():
            script_path = self.script_entry.text()
            if not script_path:
                QMessageBox.critical(self, "错误", "请选择 Python 脚本文件")
                self.ecg_log.stop_activity(False)
                return
                
            if not os.path.exists(script_path):
                QMessageBox.critical(self, "错误", "Python 脚本文件不存在")
                self.ecg_log.stop_activity(False)
                return
                
            working_dir = os.path.dirname(script_path)
            script_file = os.path.basename(script_path)
        else:
            folder_path = self.folder_entry.text()
            if not folder_path:
                QMessageBox.critical(self, "错误", "请选择项目文件夹")
                self.ecg_log.stop_activity(False)
                return
                
            if not os.path.isdir(folder_path):
                QMessageBox.critical(self, "错误", "项目文件夹不存在")
                self.ecg_log.stop_activity(False)
                return
                
            entry_file = self.entry_combobox.currentText()
            if not entry_file:
                QMessageBox.critical(self, "错误", "请选择或检测入口文件")
                self.ecg_log.stop_activity(False)
                return
                
            working_dir = folder_path
            script_file = entry_file
            
        # 构建 PyInstaller 命令
        cmd = ["pyinstaller"]
        
        if self.onefile_check.isChecked():
            cmd.append("--onefile")
            
        if self.windowed_check.isChecked():
            cmd.append("--windowed")
            
        icon_path = self.icon_entry.text()
        if icon_path and os.path.exists(icon_path):
            cmd.extend(["--icon", icon_path])
            
        if self.upx_check.isChecked():
            cmd.append("--upx-dir=upx")
            
        output_dir = self.output_entry.text()
        if output_dir:
            cmd.extend(["--distpath", output_dir])
            
        # 文件夹模式下的额外选项
        if not self.file_mode.isChecked():
            cmd.extend(["--workpath", os.path.join(working_dir, "build")])
            cmd.extend(["--specpath", working_dir])
            
            app_name = self.name_entry.text()
            if app_name:
                cmd.extend(["--name", app_name])
                
        cmd.append(script_file)
        
        self.log("准备执行命令:")
        self.log(" ".join(cmd))
        
        # 更新按钮状态
        self.build_button.setEnabled(False)
        self.cancel_button.setEnabled(True)
        
        # 重置进度条
        self.progress.setValue(0)
        self.progress.setFormat("启动中... 0%")
        
        # 创建并启动工作线程
        self.worker = BuildWorker(cmd, working_dir)
        self.worker_thread = threading.Thread(target=self.worker.run, daemon=True)
        
        # 连接信号
        self.worker.progress_updated.connect(self.update_progress)
        self.worker.log_message.connect(self.log)
        self.worker.finished.connect(self.on_build_finished)
        
        # 启动线程
        self.worker_thread.start()
        
    def cancel_build(self):
        """取消打包"""
        if self.worker:
            reply = QMessageBox.question(
                self, "确认取消", 
                "确定要取消打包吗？",
                QMessageBox.Yes | QMessageBox.No,
                QMessageBox.No
            )
            
            if reply == QMessageBox.Yes:
                self.worker.cancel()
                self.log("用户请求取消打包...")
                self.progress.setFormat("正在取消...")
    
    def update_progress(self, value, text):
        """更新进度"""
        self.progress.setValue(value)
        self.progress.setFormat(text)
        
        # 如果进度增加，更新心电图
        if value > 0 and value < 100:
            self.ecg_log.is_active = True
            self.ecg_log.is_finished = False
    
    def on_build_finished(self, success, message, cancelled):
        """打包完成处理"""
        # 更新心电图
        self.ecg_log.stop_activity(success and not cancelled)
        
        # 重置进度条
        self.progress.reset_to_zero(success, cancelled)
        
        # 显示消息
        if cancelled:
            QMessageBox.warning(self, "已取消", message)
        elif success:
            QMessageBox.information(self, "成功", message)
        else:
            QMessageBox.critical(self, "错误", message)
        
        # 更新按钮状态
        self.build_button.setEnabled(True)
        self.cancel_button.setEnabled(False)
        
        # 清理工作线程
        self.worker = None
        self.worker_thread = None

if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置应用程序样式
    app.setStyle("Fusion")
    
    # 创建并显示主窗口
    window = PyInstallerGUI()
    window.show()
    
    sys.exit(app.exec_())