"""
时间工具合集 - 整合时钟、定时器、计时器
"""
import tkinter as tk
from tkinter import ttk, messagebox
import time
import math
import threading

class TimeToolsApp:
    def __init__(self, root):
        self.root = root
        self.root.title("时间工具合集 v1.0")
        self.root.geometry("650x600")
        self.root.resizable(False, False)
        
        # 定时器变量
        self.timer_remaining = 0
        self.timer_running = False
        self.timer_paused = False
        
        # 计时器变量
        self.stopwatch_running = False
        self.stopwatch_start = 0
        self.stopwatch_elapsed = 0
        self.lap_count = 0
        
        self.setup_ui()
        self.update_clock()
    
    def setup_ui(self):
        """设置界面"""
        # 标题栏
        title_frame = tk.Frame(self.root, bg='#1a237e', height=60)
        title_frame.pack(fill=tk.X)
        title_frame.pack_propagate(False)
        
        tk.Label(title_frame, text="⏰ 时间工具合集", font=('Microsoft YaHei', 20, 'bold'),
                bg='#1a237e', fg='white').pack(pady=12)
        
        # 创建选项卡
        tab_control = ttk.Notebook(self.root)
        
        # 时钟选项卡
        self.clock_tab = ttk.Frame(tab_control)
        tab_control.add(self.clock_tab, text="🕐 时钟")
        self.setup_clock_tab()
        
        # 定时器选项卡
        self.timer_tab = ttk.Frame(tab_control)
        tab_control.add(self.timer_tab, text="⏳ 定时器")
        self.setup_timer_tab()
        
        # 计时器选项卡
        self.stopwatch_tab = ttk.Frame(tab_control)
        tab_control.add(self.stopwatch_tab, text="⏱ 计时器")
        self.setup_stopwatch_tab()
        
        tab_control.pack(expand=True, fill='both', padx=10, pady=10)
        
        # 状态栏
        self.status_bar = tk.Label(self.root, text="就绪", bd=1, relief=tk.SUNKEN,
                                  anchor=tk.W, font=('Microsoft YaHei', 9), bg='#e8eaf6')
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
    
    # ========== 时钟模块 ==========
    def setup_clock_tab(self):
        """设置时钟界面"""
        frame = tk.Frame(self.clock_tab, bg='white')
        frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 时钟画布
        self.clock_canvas = tk.Canvas(frame, width=400, height=420, bg='white', highlightthickness=0)
        self.clock_canvas.pack()
        
        # 数字时间显示
        self.digital_label = tk.Label(frame, text="", font=('Courier New', 24, 'bold'), fg='#333')
        self.digital_label.pack(pady=5)
        
        # 日期显示
        self.date_label = tk.Label(frame, text="", font=('Microsoft YaHei', 14), fg='#666')
        self.date_label.pack()
    
    def update_clock(self):
        """更新时钟"""
        self.clock_canvas.delete("all")
        
        cx, cy, r = 200, 200, 160
        
        # 表盘
        self.clock_canvas.create_oval(cx-r, cy-r, cx+r, cy+r, outline='#333', width=3)
        self.clock_canvas.create_oval(cx-r+8, cy-r+8, cx+r-8, cy+r-8, outline='#ddd', width=1)
        
        # 刻度
        for i in range(12):
            angle = math.radians(i * 30 - 90)
            inner = r - 18 if i % 3 == 0 else r - 10
            outer = r - 5
            width = 3 if i % 3 == 0 else 1
            x1 = cx + inner * math.cos(angle)
            y1 = cy + inner * math.sin(angle)
            x2 = cx + outer * math.cos(angle)
            y2 = cy + outer * math.sin(angle)
            self.clock_canvas.create_line(x1, y1, x2, y2, width=width, fill='#333')
        
        # 数字
        for i in range(12):
            angle = math.radians(i * 30 - 90)
            x = cx + (r-32) * math.cos(angle)
            y = cy + (r-32) * math.sin(angle)
            text = '12' if i == 0 else str(i)
            self.clock_canvas.create_text(x, y, text=text, font=('Arial', 14, 'bold'), fill='#333')
        
        # 获取时间
        now = time.localtime()
        hour, minute, second = now.tm_hour % 12, now.tm_min, now.tm_sec
        
        # 时针
        ha = math.radians((hour + minute/60) * 30 - 90)
        hl = r * 0.45
        self.clock_canvas.create_line(cx, cy, cx + hl*math.cos(ha), cy + hl*math.sin(ha),
                                     width=6, fill='#1a237e', capstyle=tk.ROUND)
        
        # 分针
        ma = math.radians((minute + second/60) * 6 - 90)
        ml = r * 0.65
        self.clock_canvas.create_line(cx, cy, cx + ml*math.cos(ma), cy + ml*math.sin(ma),
                                     width=4, fill='#1565c0', capstyle=tk.ROUND)
        
        # 秒针
        sa = math.radians(second * 6 - 90)
        sl = r * 0.75
        self.clock_canvas.create_line(cx, cy, cx + sl*math.cos(sa), cy + sl*math.sin(sa),
                                     width=2, fill='#c62828', capstyle=tk.ROUND)
        
        # 中心点
        self.clock_canvas.create_oval(cx-5, cy-5, cx+5, cy+5, fill='#c62828', outline='')
        
        # 数字时间
        time_str = time.strftime("%H:%M:%S")
        self.digital_label.config(text=time_str)
        
        # 日期
        date_str = time.strftime("%Y年%m月%d日 %A")
        weekdays = {'Monday': '星期一', 'Tuesday': '星期二', 'Wednesday': '星期三',
                   'Thursday': '星期四', 'Friday': '星期五', 'Saturday': '星期六', 'Sunday': '星期日'}
        for en, cn in weekdays.items():
            date_str = date_str.replace(en, cn)
        self.date_label.config(text=date_str)
        
        self.root.after(1000, self.update_clock)
    
    # ========== 定时器模块 ==========
    def setup_timer_tab(self):
        """设置定时器界面"""
        frame = tk.Frame(self.timer_tab, bg='#f5f5f5')
        frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 时间显示
        self.timer_label = tk.Label(frame, text="00:00:00", font=('Courier New', 48, 'bold'), fg='#e65100')
        self.timer_label.pack(pady=20)
        
        # 设置时间
        set_frame = tk.Frame(frame, bg='#f5f5f5')
        set_frame.pack(pady=10)
        
        tk.Label(set_frame, text="设置：", font=('Microsoft YaHei', 12), bg='#f5f5f5').pack(side=tk.LEFT)
        
        self.timer_hours = tk.Spinbox(set_frame, from_=0, to=23, width=3, font=('Arial', 14))
        self.timer_hours.pack(side=tk.LEFT, padx=2)
        tk.Label(set_frame, text="时", font=('Microsoft YaHei', 10), bg='#f5f5f5').pack(side=tk.LEFT)
        
        self.timer_minutes = tk.Spinbox(set_frame, from_=0, to=59, width=3, font=('Arial', 14))
        self.timer_minutes.pack(side=tk.LEFT, padx=2)
        tk.Label(set_frame, text="分", font=('Microsoft YaHei', 10), bg='#f5f5f5').pack(side=tk.LEFT)
        
        self.timer_seconds = tk.Spinbox(set_frame, from_=0, to=59, width=3, font=('Arial', 14))
        self.timer_seconds.pack(side=tk.LEFT, padx=2)
        tk.Label(set_frame, text="秒", font=('Microsoft YaHei', 10), bg='#f5f5f5').pack(side=tk.LEFT)
        
        # 控制按钮
        btn_frame = tk.Frame(frame, bg='#f5f5f5')
        btn_frame.pack(pady=15)
        
        self.timer_start_btn = tk.Button(btn_frame, text="▶ 开始", command=self.timer_start,
                                        bg='#4caf50', fg='white', font=('Microsoft YaHei', 11),
                                        padx=15, pady=5, cursor='hand2')
        self.timer_start_btn.pack(side=tk.LEFT, padx=5)
        
        self.timer_pause_btn = tk.Button(btn_frame, text="⏸ 暂停", command=self.timer_pause,
                                        bg='#ff9800', fg='white', font=('Microsoft YaHei', 11),
                                        padx=15, pady=5, cursor='hand2', state='disabled')
        self.timer_pause_btn.pack(side=tk.LEFT, padx=5)
        
        self.timer_reset_btn = tk.Button(btn_frame, text="🔄 重置", command=self.timer_reset,
                                        bg='#f44336', fg='white', font=('Microsoft YaHei', 11),
                                        padx=15, pady=5, cursor='hand2')
        self.timer_reset_btn.pack(side=tk.LEFT, padx=5)
        
        # 预设时间
        preset_frame = tk.LabelFrame(frame, text="快速设置", font=('Microsoft YaHei', 10), bg='#f5f5f5')
        preset_frame.pack(pady=10, padx=20, fill=tk.X)
        
        presets = [('1分钟', 0, 1, 0), ('5分钟', 0, 5, 0), ('10分钟', 0, 10, 0),
                  ('30分钟', 0, 30, 0), ('1小时', 1, 0, 0)]
        
        for text, h, m, s in presets:
            tk.Button(preset_frame, text=text,
                     command=lambda h=h, m=m, s=s: self.timer_set_preset(h, m, s),
                     bg='#e0e0e0', font=('Microsoft YaHei', 10), padx=10).pack(side=tk.LEFT, padx=5, pady=5)
        
        # 进度条
        self.timer_progress = ttk.Progressbar(frame, length=400, mode='determinate')
        self.timer_progress.pack(pady=10)
        
        # 状态
        self.timer_status = tk.Label(frame, text="就绪", font=('Microsoft YaHei', 10), fg='gray', bg='#f5f5f5')
        self.timer_status.pack()
    
    def timer_set_preset(self, h, m, s):
        """设置预设时间"""
        self.timer_hours.delete(0, tk.END)
        self.timer_hours.insert(0, str(h))
        self.timer_minutes.delete(0, tk.END)
        self.timer_minutes.insert(0, str(m))
        self.timer_seconds.delete(0, tk.END)
        self.timer_seconds.insert(0, str(s))
    
    def timer_start(self):
        """启动定时器"""
        if self.timer_running:
            return
        
        if not self.timer_paused:
            h = int(self.timer_hours.get())
            m = int(self.timer_minutes.get())
            s = int(self.timer_seconds.get())
            self.timer_remaining = h * 3600 + m * 60 + s
            
            if self.timer_remaining <= 0:
                messagebox.showwarning("提示", "请设置有效的时间")
                return
        
        self.timer_total = self.timer_remaining
        self.timer_running = True
        self.timer_paused = False
        self.timer_start_btn.config(state='disabled')
        self.timer_pause_btn.config(state='normal')
        self.timer_status.config(text="⏳ 倒计时中...")
        
        self.timer_countdown()
    
    def timer_pause(self):
        """暂停定时器"""
        if self.timer_running and not self.timer_paused:
            self.timer_paused = True
            self.timer_pause_btn.config(text="▶ 继续")
            self.timer_status.config(text="⏸ 已暂停")
    
    def timer_reset(self):
        """重置定时器"""
        self.timer_running = False
        self.timer_paused = False
        self.timer_remaining = 0
        self.timer_label.config(text="00:00:00")
        self.timer_progress['value'] = 0
        self.timer_start_btn.config(state='normal')
        self.timer_pause_btn.config(text="⏸ 暂停", state='disabled')
        self.timer_status.config(text="已重置")
    
    def timer_countdown(self):
        """定时器倒计时"""
        if not self.timer_running or self.timer_paused:
            return
        
        if self.timer_remaining > 0:
            h = self.timer_remaining // 3600
            m = (self.timer_remaining % 3600) // 60
            s = self.timer_remaining % 60
            self.timer_label.config(text=f"{h:02d}:{m:02d}:{s:02d}")
            
            # 更新进度条
            if hasattr(self, 'timer_total') and self.timer_total > 0:
                progress = ((self.timer_total - self.timer_remaining) / self.timer_total) * 100
                self.timer_progress['value'] = progress
            
            self.timer_remaining -= 1
            self.root.after(1000, self.timer_countdown)
        else:
            self.timer_label.config(text="00:00:00")
            self.timer_progress['value'] = 100
            self.timer_running = False
            self.timer_start_btn.config(state='normal')
            self.timer_pause_btn.config(state='disabled')
            self.timer_status.config(text="⏰ 时间到！")
            messagebox.showinfo("时间到", "⏰ 定时器已结束！")
    
    # ========== 计时器模块 ==========
    def setup_stopwatch_tab(self):
        """设置计时器界面"""
        frame = tk.Frame(self.stopwatch_tab, bg='#f5f5f5')
        frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 时间显示
        self.stopwatch_label = tk.Label(frame, text="00:00:00.00", 
                                       font=('Courier New', 48, 'bold'), fg='#1565c0')
        self.stopwatch_label.pack(pady=20)
        
        # 控制按钮
        btn_frame = tk.Frame(frame, bg='#f5f5f5')
        btn_frame.pack(pady=15)
        
        self.sw_start_btn = tk.Button(btn_frame, text="▶ 开始", command=self.stopwatch_start,
                                     bg='#4caf50', fg='white', font=('Microsoft YaHei', 11),
                                     padx=15, pady=5, cursor='hand2')
        self.sw_start_btn.pack(side=tk.LEFT, padx=5)
        
        self.sw_lap_btn = tk.Button(btn_frame, text="🏁 计次", command=self.stopwatch_lap,
                                   bg='#2196f3', fg='white', font=('Microsoft YaHei', 11),
                                   padx=15, pady=5, cursor='hand2', state='disabled')
        self.sw_lap_btn.pack(side=tk.LEFT, padx=5)
        
        self.sw_reset_btn = tk.Button(btn_frame, text="🔄 重置", command=self.stopwatch_reset,
                                     bg='#f44336', fg='white', font=('Microsoft YaHei', 11),
                                     padx=15, pady=5, cursor='hand2')
        self.sw_reset_btn.pack(side=tk.LEFT, padx=5)
        
        # 计次记录
        lap_frame = tk.LabelFrame(frame, text="计次记录", font=('Microsoft YaHei', 10), bg='#f5f5f5')
        lap_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        scrollbar = tk.Scrollbar(lap_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        self.lap_listbox = tk.Listbox(lap_frame, height=6, font=('Courier New', 11),
                                     yscrollcommand=scrollbar.set)
        self.lap_listbox.pack(fill=tk.BOTH, expand=True)
        scrollbar.config(command=self.lap_listbox.yview)
        
        # 状态
        self.sw_status = tk.Label(frame, text="就绪", font=('Microsoft YaHei', 10), fg='gray', bg='#f5f5f5')
        self.sw_status.pack()
    
    def stopwatch_format(self, seconds):
        """格式化计时器时间"""
        hours = int(seconds // 3600)
        minutes = int((seconds % 3600) // 60)
        secs = int(seconds % 60)
        centisecs = int((seconds - int(seconds)) * 100)
        return f"{hours:02d}:{minutes:02d}:{secs:02d}.{centisecs:02d}"
    
    def stopwatch_start(self):
        """启动/停止计时器"""
        if not self.stopwatch_running:
            self.stopwatch_running = True
            self.stopwatch_start = time.time() - self.stopwatch_elapsed
            self.sw_start_btn.config(text="⏹ 停止", bg='#f44336')
            self.sw_lap_btn.config(state='normal')
            self.sw_status.config(text="⏱ 计时中...")
            self.stopwatch_update()
        else:
            self.stopwatch_running = False
            self.sw_start_btn.config(text="▶ 继续", bg='#4caf50')
            self.sw_lap_btn.config(state='disabled')
            self.sw_status.config(text="⏸ 已停止")
    
    def stopwatch_update(self):
        """更新计时器显示"""
        if self.stopwatch_running:
            self.stopwatch_elapsed = time.time() - self.stopwatch_start
            self.stopwatch_label.config(text=self.stopwatch_format(self.stopwatch_elapsed))
            self.root.after(10, self.stopwatch_update)
    
    def stopwatch_lap(self):
        """记录计次"""
        if self.stopwatch_running:
            self.lap_count += 1
            lap_time = self.stopwatch_format(self.stopwatch_elapsed)
            self.lap_listbox.insert(0, f"计次 {self.lap_count:2d}: {lap_time}")
            self.sw_status.config(text=f"🏁 已记录计次 {self.lap_count}")
    
    def stopwatch_reset(self):
        """重置计时器"""
        self.stopwatch_running = False
        self.stopwatch_elapsed = 0
        self.lap_count = 0
        self.stopwatch_label.config(text="00:00:00.00")
        self.sw_start_btn.config(text="▶ 开始", bg='#4caf50')
        self.sw_lap_btn.config(state='disabled')
        self.lap_listbox.delete(0, tk.END)
        self.sw_status.config(text="已重置")


def main():
    root = tk.Tk()
    app = TimeToolsApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()