import sys
import time
import threading
from datetime import datetime
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class StopwatchApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        
        # 计时器变量
        self.is_running = False
        self.start_time = None
        self.elapsed_time = 0
        self.lap_count = 0
        self.lap_times = []
        
        # 计时线程
        self.timer_thread = None
        self.running = False
        
    def initUI(self):
        self.setWindowTitle('专业计时器')
        self.setFixedSize(900, 1000)
        
        # 设置全局样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #1a1a2e;
            }
            QLabel {
                color: #ffffff;
            }
            QPushButton {
                border: none;
                border-radius: 35px;
                font-size: 16px;
                font-weight: bold;
                color: white;
                padding: 12px;
            }
            QPushButton:hover {
                opacity: 150;
            }
            QPushButton:pressed {
                padding: 13px;
            }
            QListWidget {
                background-color: #16213e;
                border: 2px solid #0f3460;
                border-radius: 10px;
                color: #ffffff;
                font-size: 14px;
                padding: 10px;
            }
            QListWidget::item {
                padding: 8px;
                border-bottom: 1px solid #0f3460;
            }
            QListWidget::item:last {
                border-bottom: none;
            }
        """)
        
        # 主布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setSpacing(20)
        main_layout.setContentsMargins(30, 30, 30, 30)
        
        # 顶部标题
        title_label = QLabel("⏱️ 计时器")
        title_label.setAlignment(Qt.AlignCenter)
        title_label.setStyleSheet("""
            font-size: 38px;
            font-weight: bold;
            color: #e94560;
            margin-bottom: 10px;
        """)
        main_layout.addWidget(title_label)
        
        # 时间显示区域
        time_frame = QFrame()
        time_frame.setStyleSheet("""
            QFrame {
                background-color: #16213e;
                border-radius: 80px;
                border: 3px solid #0f3460;
                padding: 20px;
            }
        """)
        time_layout = QVBoxLayout(time_frame)
        
        # 主时间显示
        self.time_display = QLabel("00:00:00.00")
        self.time_display.setAlignment(Qt.AlignCenter)
        self.time_display.setStyleSheet("""
            font-size: 64px;
            font-weight: bold;
            color: #e94560;
            font-family: 'Courier New', monospace;
            letter-spacing: 3px;
        """)
        time_layout.addWidget(self.time_display)
        
        # 状态标签
        self.status_label = QLabel("点击开始按钮开始计时")
        self.status_label.setAlignment(Qt.AlignCenter)
        self.status_label.setStyleSheet("""
            font-size: 16px;
            color: #8899aa;
            margin-top: 5px;
        """)
        time_layout.addWidget(self.status_label)
        
        main_layout.addWidget(time_frame)
        
        # 控制按钮区域
        button_frame = QFrame()
        button_layout = QHBoxLayout(button_frame)
        button_layout.setSpacing(20)
        
        # 左侧按钮组
        left_button_layout = QVBoxLayout()
        left_button_layout.setSpacing(10)
        
        # 开始/停止按钮
        self.start_stop_btn = QPushButton("▶ 开始")
        self.start_stop_btn.setMinimumSize(160, 70)
        self.start_stop_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #e94560, stop:1 #c23152);
                font-size: 22px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff5a7a, stop:1 #d64555);
            }
        """)
        self.start_stop_btn.clicked.connect(self.toggleStartStop)
        left_button_layout.addWidget(self.start_stop_btn)
        
        # 重置按钮
        self.reset_btn = QPushButton("🔄 重置")
        self.reset_btn.setMinimumSize(160, 70)
        self.reset_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #533483, stop:1 #3b2563);
                font-size: 22px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #6b44a3, stop:1 #4b3073);
            }
        """)
        self.reset_btn.clicked.connect(self.resetTimer)
        left_button_layout.addWidget(self.reset_btn)
        
        button_layout.addLayout(left_button_layout)
        
        # 右侧按钮组
        right_button_layout = QVBoxLayout()
        right_button_layout.setSpacing(10)
        
        # 计圈按钮
        self.lap_btn = QPushButton("🏁 计圈")
        self.lap_btn.setMinimumSize(140, 70)
        self.lap_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #0f3460, stop:1 #0a2540);
                font-size: 22px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #1a4a80, stop:1 #0f3460);
            }
            QPushButton:disabled {
                background: #333333;
                color: #666666;
            }
        """)
        self.lap_btn.clicked.connect(self.recordLap)
        self.lap_btn.setEnabled(False)
        right_button_layout.addWidget(self.lap_btn)
        
        # 导出按钮
        self.export_btn = QPushButton("📥 导出")
        self.export_btn.setMinimumSize(140, 70)
        self.export_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #2d6a4f, stop:1 #1b4332);
                font-size: 22px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #40916c, stop:1 #2d6a4f);
            }
            QPushButton:disabled {
                background: #333333;
                color: #666666;
            }
        """)
        self.export_btn.clicked.connect(self.exportData)
        self.export_btn.setEnabled(False)
        right_button_layout.addWidget(self.export_btn)
        
        button_layout.addLayout(right_button_layout)
        
        main_layout.addWidget(button_frame)
        
        # 计圈记录区域
        lap_frame = QFrame()
        lap_frame.setStyleSheet("""
            QFrame {
                background-color: #16213e;
                border-radius: 15px;
                border: 2px solid #0f3460;
                padding: 10px;
            }
        """)
        lap_layout = QVBoxLayout(lap_frame)
        
        # 计圈标题
        lap_header = QHBoxLayout()
        lap_title = QLabel("🏁 计圈记录")
        lap_title.setStyleSheet("""
            font-size: 20px;
            font-weight: bold;
            color: #e94560;
        """)
        lap_header.addWidget(lap_title)
        
        self.lap_count_label = QLabel("0 圈")
        self.lap_count_label.setStyleSheet("""
            font-size: 16px;
            color: #8899aa;
        """)
        lap_header.addWidget(self.lap_count_label)
        lap_header.addStretch()
        
        lap_layout.addLayout(lap_header)
        
        # 计圈列表
        self.lap_list = QListWidget()
        self.lap_list.setMinimumHeight(180)
        self.lap_list.setAlternatingRowColors(True)
        self.lap_list.setStyleSheet("""
            QListWidget {
                background-color: #0f3460;
                border: none;
                border-radius: 10px;
                font-size: 14px;
                padding: 5px;
            }
            QListWidget::item {
                padding: 8px 15px;
                margin: 2px 0px;
                border-radius: 5px;
            }
            QListWidget::item:alternate {
                background-color: #16213e;
            }
            QListWidget::item:selected {
                background-color: #e94560;
            }
        """)
        lap_layout.addWidget(self.lap_list)
        
        # 清空计圈按钮
        clear_lap_btn = QPushButton("🗑️ 清空记录")
        clear_lap_btn.setStyleSheet("""
            QPushButton {
                background-color: #533483;
                border-radius: 8px;
                padding: 8px;
                font-size: 14px;
                color: white;
            }
            QPushButton:hover {
                background-color: #6b44a3;
            }
        """)
        clear_lap_btn.clicked.connect(self.clearLaps)
        lap_layout.addWidget(clear_lap_btn)
        
        main_layout.addWidget(lap_frame)
        
        # 底部信息栏
        info_frame = QFrame()
        info_frame.setStyleSheet("""
            QFrame {
                background-color: #16213e;
                border-radius: 10px;
                border: 1px solid #0f3460;
                padding: 10px;
            }
        """)
        info_layout = QHBoxLayout(info_frame)
        
        # 平均时间
        self.avg_time_label = QLabel("平均: --")
        self.avg_time_label.setStyleSheet("font-size: 14px; color: #8899aa;")
        info_layout.addWidget(self.avg_time_label)
        
        info_layout.addStretch()
        
        # 最快时间
        self.best_time_label = QLabel("最快: --")
        self.best_time_label.setStyleSheet("font-size: 14px; color: #4CAF50;")
        info_layout.addWidget(self.best_time_label)
        
        info_layout.addStretch()
        
        # 最慢时间
        self.worst_time_label = QLabel("最慢: --")
        self.worst_time_label.setStyleSheet("font-size: 14px; color: #f44336;")
        info_layout.addWidget(self.worst_time_label)
        
        main_layout.addWidget(info_frame)
        
        # 键盘快捷键
        self.shortcut_start = QShortcut(QKeySequence("Space"), self)
        self.shortcut_start.activated.connect(self.toggleStartStop)
        
        self.shortcut_lap = QShortcut(QKeySequence("L"), self)
        self.shortcut_lap.activated.connect(self.recordLap)
        
        self.shortcut_reset = QShortcut(QKeySequence("R"), self)
        self.shortcut_reset.activated.connect(self.resetTimer)
        
    def toggleStartStop(self):
        """开始/停止计时"""
        if not self.is_running:
            self.startTimer()
        else:
            self.stopTimer()
    
    def startTimer(self):
        """开始计时"""
        self.is_running = True
        self.running = True
        self.start_time = time.time() - self.elapsed_time
        
        # 更新按钮状态
        self.start_stop_btn.setText("⏹ 停止")
        self.start_stop_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #f44336, stop:1 #d32f2f);
                font-size: 22px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff5252, stop:1 #e53935);
            }
        """)
        
        self.lap_btn.setEnabled(True)
        self.export_btn.setEnabled(False)
        
        self.status_label.setText("⏱️ 计时中...")
        self.status_label.setStyleSheet("""
            font-size: 16px;
            color: #4CAF50;
            margin-top: 5px;
        """)
        
        # 启动计时线程
        self.timer_thread = threading.Thread(target=self.updateTime)
        self.timer_thread.daemon = True
        self.timer_thread.start()
    
    def stopTimer(self):
        """停止计时"""
        self.is_running = False
        self.running = False
        
        # 更新按钮状态
        self.start_stop_btn.setText("▶ 继续")
        self.start_stop_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #e94560, stop:1 #c23152);
                font-size: 22px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff5a7a, stop:1 #d64555);
            }
        """)
        
        self.lap_btn.setEnabled(False)
        self.export_btn.setEnabled(True)
        
        self.status_label.setText("⏹ 已停止")
        self.status_label.setStyleSheet("""
            font-size: 16px;
            color: #f44336;
            margin-top: 5px;
        """)
    
    def updateTime(self):
        """更新时间显示"""
        while self.running:
            current_time = time.time()
            self.elapsed_time = current_time - self.start_time
            
            # 格式化时间
            hours = int(self.elapsed_time // 3600)
            minutes = int((self.elapsed_time % 3600) // 60)
            seconds = int(self.elapsed_time % 60)
            milliseconds = int((self.elapsed_time * 100) % 100)
            
            # 更新显示
            display_text = f"{hours:02d}:{minutes:02d}:{seconds:02d}.{milliseconds:02d}"
            self.time_display.setText(display_text)
            
            time.sleep(0.01)  # 100Hz刷新率
    
    def recordLap(self):
        """记录计圈"""
        if not self.is_running:
            return
        
        self.lap_count += 1
        current_time = self.time_display.text()
        self.lap_times.append(self.elapsed_time)
        
        # 计算圈间时间差
        if len(self.lap_times) > 1:
            lap_diff = self.lap_times[-1] - self.lap_times[-2]
            diff_text = self.formatTime(lap_diff)
            lap_info = f"🏁 第 {self.lap_count:2d} 圈 | {current_time} (+{diff_text})"
        else:
            lap_info = f"🏁 第 {self.lap_count:2d} 圈 | {current_time}"
        
        # 添加到列表
        list_item = QListWidgetItem(lap_info)
        
        # 根据圈速设置颜色
        if self.lap_count > 1:
            if lap_diff == min(self.getLapDiffs()):
                list_item.setForeground(QColor("#4CAF50"))  # 最快绿色
                list_item.setText(f"⚡ {lap_info}")
            elif lap_diff == max(self.getLapDiffs()):
                list_item.setForeground(QColor("#f44336"))  # 最慢红色
                list_item.setText(f"🐢 {lap_info}")
            else:
                list_item.setForeground(QColor("#ffffff"))
        
        self.lap_list.insertItem(0, list_item)
        
        # 更新计圈数和统计信息
        self.lap_count_label.setText(f"{self.lap_count} 圈")
        self.updateStats()
    
    def getLapDiffs(self):
        """获取所有圈间时间差"""
        diffs = []
        for i in range(1, len(self.lap_times)):
            diffs.append(self.lap_times[i] - self.lap_times[i-1])
        return diffs
    
    def updateStats(self):
        """更新统计信息"""
        if self.lap_count < 2:
            return
        
        diffs = self.getLapDiffs()
        
        # 平均时间
        avg_time = sum(diffs) / len(diffs)
        self.avg_time_label.setText(f"平均: {self.formatTime(avg_time)}")
        
        # 最快时间
        best_time = min(diffs)
        self.best_time_label.setText(f"最快: {self.formatTime(best_time)}")
        
        # 最慢时间
        worst_time = max(diffs)
        self.worst_time_label.setText(f"最慢: {self.formatTime(worst_time)}")
    
    def formatTime(self, seconds):
        """格式化时间"""
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        millisecs = int((seconds * 100) % 100)
        
        if hours > 0:
            return f"{hours:02d}:{minutes:02d}:{secs:02d}.{millisecs:02d}"
        else:
            return f"{minutes:02d}:{secs:02d}.{millisecs:02d}"
    
    def resetTimer(self):
        """重置计时器"""
        self.is_running = False
        self.running = False
        self.elapsed_time = 0
        self.lap_count = 0
        self.lap_times = []
        
        # 重置显示
        self.time_display.setText("00:00:00.00")
        self.lap_list.clear()
        self.lap_count_label.setText("0 圈")
        
        # 重置按钮状态
        self.start_stop_btn.setText("▶ 开始")
        self.start_stop_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #e94560, stop:1 #c23152);
                font-size: 22px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
                    stop:0 #ff5a7a, stop:1 #d64555);
            }
        """)
        
        self.lap_btn.setEnabled(False)
        self.export_btn.setEnabled(False)
        
        # 重置状态
        self.status_label.setText("已重置")
        self.status_label.setStyleSheet("""
            font-size: 16px;
            color: #8899aa;
            margin-top: 5px;
        """)
        
        # 重置统计信息
        self.avg_time_label.setText("平均: --")
        self.best_time_label.setText("最快: --")
        self.worst_time_label.setText("最慢: --")
    
    def clearLaps(self):
        """清空计圈记录"""
        self.lap_list.clear()
        self.lap_count = 0
        self.lap_times = []
        self.lap_count_label.setText("0 圈")
        
        self.avg_time_label.setText("平均: --")
        self.best_time_label.setText("最快: --")
        self.worst_time_label.setText("最慢: --")
    
    def exportData(self):
        """导出计时数据"""
        if self.lap_count == 0:
            QMessageBox.information(self, "提示", "没有数据可以导出")
            return
        
        # 创建导出对话框
        text, ok = QInputDialog.getItem(
            self, 
            "导出格式",
            "选择导出格式:",
            ["文本文件 (.txt)", "CSV文件 (.csv)"],
            0, 
            False
        )
        
        if ok and text:
            file_path, _ = QFileDialog.getSaveFileName(
                self,
                "保存文件",
                f"计时数据_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
                f"{text.split('.')[-1].replace(')', '')} files (*.{text.split('.')[-1].replace(')', '')})"
            )
            
            if file_path:
                if ".txt" in text:
                    self.exportToTxt(file_path)
                else:
                    self.exportToCsv(file_path)
                
                QMessageBox.information(self, "成功", f"数据已导出到:\n{file_path}")
    
    def exportToTxt(self, file_path):
        """导出为文本文件"""
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write("=" * 50 + "\n")
            f.write("         计时器数据报告\n")
            f.write(f"          导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write("=" * 50 + "\n\n")
            
            f.write(f"总用时: {self.time_display.text()}\n")
            f.write(f"总圈数: {self.lap_count}\n\n")
            
            f.write("-" * 50 + "\n")
            f.write("详细记录:\n")
            f.write("-" * 50 + "\n")
            
            for i, time_str in enumerate(self.lap_times, 1):
                f.write(f"第 {i:2d} 圈: {self.formatTime(time_str)}\n")
            
            f.write("\n" + "-" * 50 + "\n")
            f.write("统计信息:\n")
            f.write("-" * 50 + "\n")
            
            if self.lap_count > 1:
                diffs = self.getLapDiffs()
                f.write(f"平均圈速: {self.formatTime(sum(diffs)/len(diffs))}\n")
                f.write(f"最快圈速: {self.formatTime(min(diffs))}\n")
                f.write(f"最慢圈速: {self.formatTime(max(diffs))}\n")
    
    def exportToCsv(self, file_path):
        """导出为CSV文件"""
        with open(file_path, 'w', encoding='utf-8-sig') as f:
            f.write("圈数,用时(秒),格式化时间\n")
            
            for i, time_sec in enumerate(self.lap_times, 1):
                formatted = self.formatTime(time_sec)
                f.write(f"{i},{time_sec:.2f},{formatted}\n")
            
            f.write("\n")
            f.write(f"总用时,{self.elapsed_time:.2f},{self.time_display.text()}\n")
            f.write(f"总圈数,{self.lap_count},\n")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle('Fusion')
    
    # 设置全局字体
    font = QFont("Microsoft YaHei", 10)
    app.setFont(font)
    
    window = StopwatchApp()
    window.show()
    sys.exit(app.exec_())