import tkinter as tk
from tkinter import messagebox
import time
import threading
import os

# --- 声音播放逻辑 (兼容 Windows/Mac/Linux) ---
def play_alarm_sound():
    """播放提示音"""
    try:
        # Windows 系统使用 winsound
        import winsound
        winsound.Beep(1000, 1000) # 频率1000Hz，持续1000ms
    except ImportError:
        # Mac/Linux 系统使用系统命令播放提示音
        try:
            os.system('afplay /System/Library/Sounds/Glass.aiff') # Mac
        except:
            os.system('paplay /usr/share/sounds/freedesktop/stereo/bell.oga') # Linux

# --- 主程序类 ---
class MultiTimerApp:
    def __init__(self, root):
        self.root = root
        self.root.title("Python 多功能定时器")
        self.root.geometry("450x350")
        self.root.resizable(False, False)

        # 变量定义
        self.is_running = False
        self.time_left = 0
        self.timer_thread = None
        
        # --- 界面布局 ---
        
        # 1. 顶部：实时时钟
        self.clock_label = tk.Label(root, text="00:00:00", font=("Arial", 16), fg="#555")
        self.clock_label.pack(pady=10)
        self.update_clock()

        # 2. 中间：主计时器显示
        self.timer_label = tk.Label(root, text="25:00", font=("Consolas", 60, "bold"), fg="#0078D7")
        self.timer_label.pack(pady=20)

        # 3. 底部：控制按钮区
        btn_frame = tk.Frame(root)
        btn_frame.pack(pady=10)

        # 模式选择
        self.mode_var = tk.StringVar(value="pomodoro")
        tk.Radiobutton(btn_frame, text="🍅 番茄钟 (25分)", variable=self.mode_var, value="pomodoro", command=self.reset_timer).grid(row=0, column=0, padx=10)
        tk.Radiobutton(btn_frame, text="⏳ 短休息 (5分)", variable=self.mode_var, value="short_break", command=self.reset_timer).grid(row=0, column=1, padx=10)

        # 自定义时间输入
        custom_frame = tk.Frame(root)
        custom_frame.pack()
        tk.Label(custom_frame, text="自定义(分):").pack(side=tk.LEFT)
        self.custom_min = tk.Spinbox(custom_frame, from_=1, to=120, width=5, command=self.reset_timer)
        self.custom_min.pack(side=tk.LEFT, padx=5)
        tk.Button(custom_frame, text="设置", command=self.set_custom_time).pack(side=tk.LEFT, padx=5)

        # 操作按钮
        control_frame = tk.Frame(root)
        control_frame.pack(pady=20)
        
        self.start_btn = tk.Button(control_frame, text="开始", font=("Arial", 12), width=8, command=self.start_timer)
        self.start_btn.grid(row=0, column=0, padx=10)
        
        self.pause_btn = tk.Button(control_frame, text="暂停", font=("Arial", 12), width=8, command=self.pause_timer, state="disabled")
        self.pause_btn.grid(row=0, column=1, padx=10)
        
        self.reset_btn = tk.Button(control_frame, text="重置", font=("Arial", 12), width=8, command=self.reset_timer)
        self.reset_btn.grid(row=0, column=2, padx=10)

    # --- 核心逻辑函数 ---

    def update_clock(self):
        """更新顶部实时时钟"""
        current_time = time.strftime("%H:%M:%S")
        self.clock_label.config(text=current_time)
        self.root.after(1000, self.update_clock)

    def set_custom_time(self):
        """设置自定义时间"""
        try:
            mins = int(self.custom_min.get())
            self.time_left = mins * 60
            self.update_display()
            self.is_running = False
            self.start_btn.config(text="开始")
            self.pause_btn.config(state="disabled")
        except:
            pass

    def reset_timer(self):
        """重置定时器"""
        self.is_running = False
        if self.timer_thread and self.timer_thread.is_alive():
            # 这里简单处理，实际多线程停止需要更复杂的标志位控制
            pass 
        
        mode = self.mode_var.get()
        if mode == "pomodoro":
            self.time_left = 25 * 60
        elif mode == "short_break":
            self.time_left = 5 * 60
        
        self.update_display()
        self.start_btn.config(text="开始")
        self.pause_btn.config(state="disabled")
        self.timer_label.config(fg="#0078D7") # 恢复蓝色

    def start_timer(self):
        """开始倒计时"""
        if not self.is_running:
            if self.time_left <= 0:
                # 如果是0，根据模式重新加载时间
                self.reset_timer()
            
            self.is_running = True
            self.start_btn.config(text="运行中...")
            self.start_btn.config(state="disabled") # 防止重复点击
            self.pause_btn.config(state="normal")
            self.timer_label.config(fg="#D70040") # 变为红色警示
            
            # 使用线程运行，防止界面卡死
            threading.Thread(target=self.run_timer, daemon=True).start()

    def pause_timer(self):
        """暂停倒计时"""
        self.is_running = False
        self.start_btn.config(text="继续")
        self.start_btn.config(state="normal")
        self.pause_btn.config(state="disabled")

    def run_timer(self):
        """后台计时线程"""
        while self.is_running and self.time_left > 0:
            time.sleep(1)
            self.time_left -= 1
            self.update_display()
        
        # 计时结束
        if self.time_left == 0:
            self.is_running = False
            play_alarm_sound()
            messagebox.showinfo("时间到", "⏰ 时间到了！该休息一下了。")
            self.reset_timer()

    def update_display(self):
        """更新数字显示"""
        minutes = self.time_left // 60
        seconds = self.time_left % 60
        self.timer_label.config(text=f"{minutes:02d}:{seconds:02d}")

# --- 程序入口 ---
if __name__ == "__main__":
    root = tk.Tk()
    app = MultiTimerApp(root)
    root.mainloop()