import tkinter as tk
from tkinter import ttk, font
import time
from datetime import datetime
import math
import calendar
from tkinter import colorchooser, messagebox
import json
import os

class DigitalClockApp:
    def __init__(self, root):
        self.root = root
        self.root.title("高级数字时钟")
        self.root.geometry("900x700")
        
        # 设置窗口图标
        try:
            self.root.iconbitmap(default="")
        except:
            pass
        
        # 时钟样式设置
        self.themes = {
            "深色主题": {
                "bg": "#1e1e1e",
                "fg": "#ffffff",
                "accent": "#3498db",
                "secondary": "#2c3e50"
            },
            "浅色主题": {
                "bg": "#f5f7fa",
                "fg": "#2c3e50",
                "accent": "#3498db",
                "secondary": "#bdc3c7"
            },
            "深蓝主题": {
                "bg": "#0d1b2a",
                "fg": "#e0e1dd",
                "accent": "#00b4d8",
                "secondary": "#1b263b"
            },
            "紫色主题": {
                "bg": "#2d1b69",
                "fg": "#ffffff",
                "accent": "#9d4edd",
                "secondary": "#3c096c"
            }
        }
        
        self.current_theme = "深色主题"
        self.clock_style = "digital"  # digital, analog, binary, flip
        self.show_date = True
        self.show_seconds = True
        self.show_milliseconds = False
        self.military_time = False
        self.alarm_enabled = False
        self.alarm_time = "07:00"
        
        # 创建UI
        self.setup_ui()
        
        # 加载设置
        self.load_settings()
        
        # 开始更新时间
        self.update_time()
        
        # 创建右键菜单
        self.create_context_menu()
        
    def setup_ui(self):
        """设置主界面"""
        # 主容器
        self.main_container = tk.Frame(self.root, bg=self.themes[self.current_theme]["bg"])
        self.main_container.pack(fill=tk.BOTH, expand=True)
        
        # 标题栏
        self.create_title_bar()
        
        # 时钟显示区域
        self.create_clock_display()
        
        # 控制面板
        self.create_control_panel()
        
        # 底部状态栏
        self.create_status_bar()
        
    def create_title_bar(self):
        """创建标题栏"""
        title_frame = tk.Frame(
            self.main_container,
            bg=self.themes[self.current_theme]["secondary"],
            height=50
        )
        title_frame.pack(fill=tk.X, side=tk.TOP)
        title_frame.pack_propagate(False)
        
        # 标题
        title_label = tk.Label(
            title_frame,
            text="⏰ 高级数字时钟",
            font=("Arial", 18, "bold"),
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"]
        )
        title_label.pack(side=tk.LEFT, padx=20)
        
        # 当前日期
        self.date_label = tk.Label(
            title_frame,
            font=("Arial", 12),
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["accent"]
        )
        self.date_label.pack(side=tk.RIGHT, padx=20)
        
    def create_clock_display(self):
        """创建时钟显示区域"""
        self.clock_frame = tk.Frame(
            self.main_container,
            bg=self.themes[self.current_theme]["bg"]
        )
        self.clock_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 数字时钟显示
        self.digital_clock = tk.Label(
            self.clock_frame,
            text="00:00:00",
            font=("Digital-7", 100, "bold"),
            bg=self.themes[self.current_theme]["bg"],
            fg=self.themes[self.current_theme]["accent"]
        )
        self.digital_clock.pack(expand=True)
        
        # 日期显示
        self.date_display = tk.Label(
            self.clock_frame,
            font=("Arial", 20),
            bg=self.themes[self.current_theme]["bg"],
            fg=self.themes[self.current_theme]["fg"]
        )
        self.date_display.pack()
        
        # 创建模拟时钟画布
        self.canvas_size = 300
        self.analog_canvas = tk.Canvas(
            self.clock_frame,
            width=self.canvas_size,
            height=self.canvas_size,
            bg=self.themes[self.current_theme]["bg"],
            highlightthickness=0
        )
        
        # 创建二进制时钟
        self.binary_frame = tk.Frame(
            self.clock_frame,
            bg=self.themes[self.current_theme]["bg"]
        )
        
        # 创建翻页时钟
        self.flip_hours = tk.Label(
            self.clock_frame,
            text="00",
            font=("Arial", 80, "bold"),
            bg="#2c3e50",
            fg="#ffffff",
            relief=tk.RAISED,
            bd=3
        )
        self.flip_minutes = tk.Label(
            self.clock_frame,
            text="00",
            font=("Arial", 80, "bold"),
            bg="#2c3e50",
            fg="#ffffff",
            relief=tk.RAISED,
            bd=3
        )
        self.flip_seconds = tk.Label(
            self.clock_frame,
            text="00",
            font=("Arial", 80, "bold"),
            bg="#2c3e50",
            fg="#ffffff",
            relief=tk.RAISED,
            bd=3
        )
        
    def create_control_panel(self):
        """创建控制面板"""
        control_frame = tk.Frame(
            self.main_container,
            bg=self.themes[self.current_theme]["secondary"]
        )
        control_frame.pack(fill=tk.X, side=tk.BOTTOM, padx=20, pady=20)
        
        # 样式选择
        style_frame = tk.LabelFrame(
            control_frame,
            text="时钟样式",
            font=("Arial", 10, "bold"),
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"]
        )
        style_frame.pack(side=tk.LEFT, padx=10, pady=10)
        
        styles = ["数字时钟", "模拟时钟", "二进制时钟", "翻页时钟"]
        self.style_var = tk.StringVar(value="数字时钟")
        
        for style in styles:
            rb = tk.Radiobutton(
                style_frame,
                text=style,
                variable=self.style_var,
                value=style,
                command=self.change_clock_style,
                bg=self.themes[self.current_theme]["secondary"],
                fg=self.themes[self.current_theme]["fg"],
                selectcolor=self.themes[self.current_theme]["bg"],
                font=("Arial", 9)
            )
            rb.pack(anchor=tk.W, padx=10, pady=2)
        
        # 主题选择
        theme_frame = tk.LabelFrame(
            control_frame,
            text="主题",
            font=("Arial", 10, "bold"),
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"]
        )
        theme_frame.pack(side=tk.LEFT, padx=10, pady=10)
        
        self.theme_var = tk.StringVar(value=self.current_theme)
        
        for theme in self.themes.keys():
            rb = tk.Radiobutton(
                theme_frame,
                text=theme,
                variable=self.theme_var,
                value=theme,
                command=self.change_theme,
                bg=self.themes[self.current_theme]["secondary"],
                fg=self.themes[self.current_theme]["fg"],
                selectcolor=self.themes[self.current_theme]["bg"],
                font=("Arial", 9)
            )
            rb.pack(anchor=tk.W, padx=10, pady=2)
        
        # 显示选项
        display_frame = tk.LabelFrame(
            control_frame,
            text="显示选项",
            font=("Arial", 10, "bold"),
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"]
        )
        display_frame.pack(side=tk.LEFT, padx=10, pady=10)
        
        # 秒显示开关
        self.seconds_var = tk.BooleanVar(value=self.show_seconds)
        seconds_cb = tk.Checkbutton(
            display_frame,
            text="显示秒数",
            variable=self.seconds_var,
            command=self.toggle_seconds,
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"],
            selectcolor=self.themes[self.current_theme]["bg"],
            font=("Arial", 9)
        )
        seconds_cb.pack(anchor=tk.W, padx=10, pady=2)
        
        # 日期显示开关
        self.date_var = tk.BooleanVar(value=self.show_date)
        date_cb = tk.Checkbutton(
            display_frame,
            text="显示日期",
            variable=self.date_var,
            command=self.toggle_date,
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"],
            selectcolor=self.themes[self.current_theme]["bg"],
            font=("Arial", 9)
        )
        date_cb.pack(anchor=tk.W, padx=10, pady=2)
        
        # 24小时制开关
        self.military_var = tk.BooleanVar(value=self.military_time)
        military_cb = tk.Checkbutton(
            display_frame,
            text="24小时制",
            variable=self.military_var,
            command=self.toggle_military_time,
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"],
            selectcolor=self.themes[self.current_theme]["bg"],
            font=("Arial", 9)
        )
        military_cb.pack(anchor=tk.W, padx=10, pady=2)
        
        # 闹钟设置
        alarm_frame = tk.LabelFrame(
            control_frame,
            text="闹钟设置",
            font=("Arial", 10, "bold"),
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"]
        )
        alarm_frame.pack(side=tk.LEFT, padx=10, pady=10)
        
        # 闹钟时间输入
        time_frame = tk.Frame(alarm_frame, bg=self.themes[self.current_theme]["secondary"])
        time_frame.pack(pady=5)
        
        tk.Label(
            time_frame,
            text="时间:",
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"],
            font=("Arial", 9)
        ).pack(side=tk.LEFT)
        
        self.alarm_hour = ttk.Combobox(
            time_frame,
            values=[f"{i:02d}" for i in range(24)],
            width=5,
            font=("Arial", 9)
        )
        self.alarm_hour.pack(side=tk.LEFT, padx=2)
        self.alarm_hour.set("07")
        
        tk.Label(
            time_frame,
            text=":",
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"],
            font=("Arial", 9)
        ).pack(side=tk.LEFT)
        
        self.alarm_minute = ttk.Combobox(
            time_frame,
            values=[f"{i:02d}" for i in range(60)],
            width=5,
            font=("Arial", 9)
        )
        self.alarm_minute.pack(side=tk.LEFT, padx=2)
        self.alarm_minute.set("00")
        
        # 闹钟开关
        self.alarm_var = tk.BooleanVar(value=self.alarm_enabled)
        alarm_cb = tk.Checkbutton(
            alarm_frame,
            text="启用闹钟",
            variable=self.alarm_var,
            command=self.toggle_alarm,
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"],
            selectcolor=self.themes[self.current_theme]["bg"],
            font=("Arial", 9)
        )
        alarm_cb.pack(pady=5)
        
        # 设置闹钟按钮
        tk.Button(
            alarm_frame,
            text="设置闹钟",
            command=self.set_alarm,
            bg=self.themes[self.current_theme]["accent"],
            fg="white",
            font=("Arial", 9),
            relief=tk.FLAT,
            padx=10,
            pady=2
        ).pack(pady=5)
        
    def create_status_bar(self):
        """创建状态栏"""
        self.status_bar = tk.Label(
            self.main_container,
            text="就绪 | 数字时钟模式",
            bd=1,
            relief=tk.SUNKEN,
            anchor=tk.W,
            bg=self.themes[self.current_theme]["secondary"],
            fg=self.themes[self.current_theme]["fg"],
            font=("Arial", 9)
        )
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
    def create_context_menu(self):
        """创建右键菜单"""
        self.context_menu = tk.Menu(self.root, tearoff=0)
        self.context_menu.add_command(label="全屏显示", command=self.toggle_fullscreen)
        self.context_menu.add_command(label="置顶窗口", command=self.toggle_always_on_top)
        self.context_menu.add_separator()
        self.context_menu.add_command(label="保存设置", command=self.save_settings)
        self.context_menu.add_command(label="重置设置", command=self.reset_settings)
        self.context_menu.add_separator()
        self.context_menu.add_command(label="关于", command=self.show_about)
        self.context_menu.add_command(label="退出", command=self.root.quit)
        
        # 绑定右键事件
        self.root.bind("<Button-3>", self.show_context_menu)
        
    def show_context_menu(self, event):
        """显示右键菜单"""
        self.context_menu.post(event.x_root, event.y_root)
        
    def update_time(self):
        """更新时间显示"""
        now = datetime.now()
        
        # 更新时间显示
        if self.clock_style == "digital":
            self.update_digital_clock(now)
        elif self.clock_style == "analog":
            self.update_analog_clock(now)
        elif self.clock_style == "binary":
            self.update_binary_clock(now)
        elif self.clock_style == "flip":
            self.update_flip_clock(now)
        
        # 更新日期显示
        if self.show_date:
            date_str = now.strftime("%Y年%m月%d日 星期")
            weekday_cn = ["一", "二", "三", "四", "五", "六", "日"]
            date_str += weekday_cn[now.weekday()]
            self.date_display.config(text=date_str)
            self.date_display.pack(pady=10)
        else:
            self.date_display.pack_forget()
        
        # 更新状态栏
        self.update_status_bar(now)
        
        # 检查闹钟
        self.check_alarm(now)
        
        # 每秒更新一次
        self.root.after(1000, self.update_time)
        
    def update_digital_clock(self, now):
        """更新数字时钟"""
        if self.military_time:
            time_format = "%H:%M"
        else:
            time_format = "%I:%M"
            
        if self.show_seconds:
            time_format += ":%S"
            
        time_str = now.strftime(time_format)
        
        # 移除前导零（12小时制时）
        if not self.military_time and time_str.startswith("0"):
            time_str = time_str[1:]
        
        # 添加AM/PM标记
        if not self.military_time:
            time_str += " " + ("AM" if now.hour < 12 else "PM")
        
        self.digital_clock.config(text=time_str)
        self.digital_clock.pack(expand=True)
        
        # 隐藏其他时钟
        self.analog_canvas.pack_forget()
        self.binary_frame.pack_forget()
        self.flip_hours.pack_forget()
        self.flip_minutes.pack_forget()
        self.flip_seconds.pack_forget()
        
    def update_analog_clock(self, now):
        """更新模拟时钟"""
        self.analog_canvas.delete("all")
        
        center_x = self.canvas_size // 2
        center_y = self.canvas_size // 2
        radius = min(center_x, center_y) - 20
        
        # 绘制表盘
        self.analog_canvas.create_oval(
            center_x - radius,
            center_y - radius,
            center_x + radius,
            center_y + radius,
            width=3,
            outline=self.themes[self.current_theme]["fg"]
        )
        
        # 绘制刻度
        for i in range(60):
            angle = math.radians(i * 6 - 90)
            if i % 5 == 0:  # 小时刻度
                length = 15
                width = 3
                # 绘制小时数字
                hour = i // 5 if i // 5 != 0 else 12
                x = center_x + (radius - 30) * math.cos(angle)
                y = center_y + (radius - 30) * math.sin(angle)
                self.analog_canvas.create_text(x, y, text=str(hour), 
                                              font=("Arial", 12, "bold"),
                                              fill=self.themes[self.current_theme]["fg"])
            else:  # 分钟刻度
                length = 5
                width = 1
            
            x1 = center_x + (radius - length) * math.cos(angle)
            y1 = center_y + (radius - length) * math.sin(angle)
            x2 = center_x + radius * math.cos(angle)
            y2 = center_y + radius * math.sin(angle)
            
            self.analog_canvas.create_line(x1, y1, x2, y2, 
                                         width=width,
                                         fill=self.themes[self.current_theme]["fg"])
        
        # 计算指针角度
        hour_angle = math.radians((now.hour % 12) * 30 + now.minute * 0.5 - 90)
        minute_angle = math.radians(now.minute * 6 - 90)
        second_angle = math.radians(now.second * 6 - 90)
        
        # 绘制时针
        hour_length = radius * 0.5
        hour_x = center_x + hour_length * math.cos(hour_angle)
        hour_y = center_y + hour_length * math.sin(hour_angle)
        self.analog_canvas.create_line(center_x, center_y, hour_x, hour_y,
                                     width=6, fill=self.themes[self.current_theme]["accent"])
        
        # 绘制分针
        minute_length = radius * 0.7
        minute_x = center_x + minute_length * math.cos(minute_angle)
        minute_y = center_y + minute_length * math.sin(minute_angle)
        self.analog_canvas.create_line(center_x, center_y, minute_x, minute_y,
                                     width=4, fill=self.themes[self.current_theme]["accent"])
        
        # 绘制秒针
        if self.show_seconds:
            second_length = radius * 0.9
            second_x = center_x + second_length * math.cos(second_angle)
            second_y = center_y + second_length * math.sin(second_angle)
            self.analog_canvas.create_line(center_x, center_y, second_x, second_y,
                                         width=2, fill="#e74c3c")
        
        # 绘制中心点
        self.analog_canvas.create_oval(center_x-5, center_y-5, center_x+5, center_y+5,
                                      fill=self.themes[self.current_theme]["accent"])
        
        self.analog_canvas.pack(expand=True)
        
        # 隐藏其他时钟
        self.digital_clock.pack_forget()
        self.binary_frame.pack_forget()
        self.flip_hours.pack_forget()
        self.flip_minutes.pack_forget()
        self.flip_seconds.pack_forget()
        
    def update_binary_clock(self, now):
        """更新二进制时钟"""
        for widget in self.binary_frame.winfo_children():
            widget.destroy()
        
        # 获取时间数字
        hours = now.hour
        minutes = now.minute
        seconds = now.second
        
        # 转换为二进制字符串
        hour_bin = format(hours, '06b')
        minute_bin = format(minutes, '06b')
        second_bin = format(seconds, '06b')
        
        # 创建二进制显示
        rows = []
        
        # 小时
        hour_frame = tk.Frame(self.binary_frame, bg=self.themes[self.current_theme]["bg"])
        hour_frame.pack(pady=5)
        tk.Label(hour_frame, text="时:", bg=self.themes[self.current_theme]["bg"], 
                fg=self.themes[self.current_theme]["fg"]).pack(side=tk.LEFT)
        for i, bit in enumerate(hour_bin):
            color = self.themes[self.current_theme]["accent"] if bit == '1' else self.themes[self.current_theme]["secondary"]
            tk.Label(hour_frame, text=" ", width=2, height=1, 
                    bg=color, relief=tk.RAISED).pack(side=tk.LEFT, padx=2)
        
        # 分钟
        minute_frame = tk.Frame(self.binary_frame, bg=self.themes[self.current_theme]["bg"])
        minute_frame.pack(pady=5)
        tk.Label(minute_frame, text="分:", bg=self.themes[self.current_theme]["bg"], 
                fg=self.themes[self.current_theme]["fg"]).pack(side=tk.LEFT)
        for i, bit in enumerate(minute_bin):
            color = self.themes[self.current_theme]["accent"] if bit == '1' else self.themes[self.current_theme]["secondary"]
            tk.Label(minute_frame, text=" ", width=2, height=1, 
                    bg=color, relief=tk.RAISED).pack(side=tk.LEFT, padx=2)
        
        # 秒
        if self.show_seconds:
            second_frame = tk.Frame(self.binary_frame, bg=self.themes[self.current_theme]["bg"])
            second_frame.pack(pady=5)
            tk.Label(second_frame, text="秒:", bg=self.themes[self.current_theme]["bg"], 
                    fg=self.themes[self.current_theme]["fg"]).pack(side=tk.LEFT)
            for i, bit in enumerate(second_bin):
                color = self.themes[self.current_theme]["accent"] if bit == '1' else self.themes[self.current_theme]["secondary"]
                tk.Label(second_frame, text=" ", width=2, height=1, 
                        bg=color, relief=tk.RAISED).pack(side=tk.LEFT, padx=2)
        
        # 显示数字值
        value_frame = tk.Frame(self.binary_frame, bg=self.themes[self.current_theme]["bg"])
        value_frame.pack(pady=10)
        tk.Label(value_frame, text=f"十进制: {hours:02d}:{minutes:02d}", 
                bg=self.themes[self.current_theme]["bg"], 
                fg=self.themes[self.current_theme]["fg"],
                font=("Arial", 10)).pack()
        
        self.binary_frame.pack(expand=True)
        
        # 隐藏其他时钟
        self.digital_clock.pack_forget()
        self.analog_canvas.pack_forget()
        self.flip_hours.pack_forget()
        self.flip_minutes.pack_forget()
        self.flip_seconds.pack_forget()
        
    def update_flip_clock(self, now):
        """更新翻页时钟"""
        hours = f"{now.hour:02d}" if self.military_time else f"{now.hour % 12:02d}"
        minutes = f"{now.minute:02d}"
        seconds = f"{now.second:02d}"
        
        if self.flip_hours['text'] != hours:
            self.flip_hours.config(text=hours, fg="#e74c3c")
            self.root.after(300, lambda: self.flip_hours.config(fg="white"))
        else:
            self.flip_hours.config(text=hours, fg="white")
        
        if self.flip_minutes['text'] != minutes:
            self.flip_minutes.config(text=minutes, fg="#e74c3c")
            self.root.after(300, lambda: self.flip_minutes.config(fg="white"))
        else:
            self.flip_minutes.config(text=minutes, fg="white")
            
        if self.show_seconds and self.flip_seconds['text'] != seconds:
            self.flip_seconds.config(text=seconds, fg="#e74c3c")
            self.root.after(300, lambda: self.flip_seconds.config(fg="white"))
        else:
            self.flip_seconds.config(text=seconds, fg="white")
        
        # 布局
        self.flip_hours.pack(side=tk.LEFT, padx=5, expand=True)
        tk.Label(self.clock_frame, text=":", font=("Arial", 60, "bold"), 
                bg=self.themes[self.current_theme]["bg"], 
                fg=self.themes[self.current_theme]["fg"]).pack(side=tk.LEFT, expand=True)
        self.flip_minutes.pack(side=tk.LEFT, padx=5, expand=True)
        
        if self.show_seconds:
            tk.Label(self.clock_frame, text=":", font=("Arial", 60, "bold"), 
                    bg=self.themes[self.current_theme]["bg"], 
                    fg=self.themes[self.current_theme]["fg"]).pack(side=tk.LEFT, expand=True)
            self.flip_seconds.pack(side=tk.LEFT, padx=5, expand=True)
        
        # 隐藏其他时钟
        self.digital_clock.pack_forget()
        self.analog_canvas.pack_forget()
        self.binary_frame.pack_forget()
        
    def update_status_bar(self, now):
        """更新状态栏信息"""
        time_str = now.strftime("%H:%M:%S")
        date_str = now.strftime("%Y-%m-%d")
        style_text = {
            "digital": "数字时钟",
            "analog": "模拟时钟", 
            "binary": "二进制时钟",
            "flip": "翻页时钟"
        }[self.clock_style]
        
        alarm_status = "闹钟: 开" if self.alarm_enabled else "闹钟: 关"
        military_status = "24小时制" if self.military_time else "12小时制"
        
        status_text = f"时间: {time_str} | 日期: {date_str} | 模式: {style_text} | {alarm_status} | {military_status}"
        self.status_bar.config(text=status_text)
        
    def change_clock_style(self):
        """切换时钟样式"""
        style_map = {
            "数字时钟": "digital",
            "模拟时钟": "analog",
            "二进制时钟": "binary",
            "翻页时钟": "flip"
        }
        self.clock_style = style_map[self.style_var.get()]
        
    def change_theme(self):
        """切换主题"""
        self.current_theme = self.theme_var.get()
        theme = self.themes[self.current_theme]
        
        # 更新所有组件的颜色
        self.main_container.config(bg=theme["bg"])
        self.clock_frame.config(bg=theme["bg"])
        self.digital_clock.config(bg=theme["bg"], fg=theme["accent"])
        self.date_display.config(bg=theme["bg"], fg=theme["fg"])
        self.analog_canvas.config(bg=theme["bg"])
        self.binary_frame.config(bg=theme["bg"])
        self.status_bar.config(bg=theme["secondary"], fg=theme["fg"])
        
    def toggle_seconds(self):
        """切换秒显示"""
        self.show_seconds = self.seconds_var.get()
        
    def toggle_date(self):
        """切换日期显示"""
        self.show_date = self.date_var.get()
        
    def toggle_military_time(self):
        """切换24小时制"""
        self.military_time = self.military_var.get()
        
    def toggle_alarm(self):
        """切换闹钟开关"""
        self.alarm_enabled = self.alarm_var.get()
        
    def set_alarm(self):
        """设置闹钟时间"""
        hour = self.alarm_hour.get()
        minute = self.alarm_minute.get()
        
        if hour and minute:
            self.alarm_time = f"{int(hour):02d}:{int(minute):02d}"
            messagebox.showinfo("闹钟设置", f"闹钟已设置为 {self.alarm_time}")
            self.alarm_enabled = True
            self.alarm_var.set(True)
        else:
            messagebox.showwarning("警告", "请选择有效的时间")
            
    def check_alarm(self, now):
        """检查闹钟"""
        if self.alarm_enabled:
            current_time = now.strftime("%H:%M")
            if current_time == self.alarm_time and now.second == 0:
                self.trigger_alarm()
                
    def trigger_alarm(self):
        """触发闹钟"""
        # 创建闪烁效果
        original_color = self.digital_clock.cget("fg")
        def flash():
            current_color = self.digital_clock.cget("fg")
            new_color = "#e74c3c" if current_color != "#e74c3c" else original_color
            self.digital_clock.config(fg=new_color)
            self.root.after(500, flash)
        
        flash()
        self.root.bell()  # 系统提示音
        
        # 显示提示
        messagebox.showinfo("闹钟", f"⏰ 时间到！现在是 {self.alarm_time}")
        
    def toggle_fullscreen(self):
        """切换全屏"""
        self.root.attributes("-fullscreen", not self.root.attributes("-fullscreen"))
        
    def toggle_always_on_top(self):
        """切换窗口置顶"""
        self.root.attributes("-topmost", not self.root.attributes("-topmost"))
        
    def save_settings(self):
        """保存设置到文件"""
        settings = {
            "theme": self.current_theme,
            "clock_style": self.clock_style,
            "show_seconds": self.show_seconds,
            "show_date": self.show_date,
            "military_time": self.military_time,
            "alarm_enabled": self.alarm_enabled,
            "alarm_time": self.alarm_time
        }
        
        try:
            with open("clock_settings.json", "w", encoding="utf-8") as f:
                json.dump(settings, f, ensure_ascii=False, indent=2)
            messagebox.showinfo("保存成功", "设置已保存到文件")
        except Exception as e:
            messagebox.showerror("保存失败", f"保存设置时出错: {str(e)}")
            
    def load_settings(self):
        """从文件加载设置"""
        try:
            if os.path.exists("clock_settings.json"):
                with open("clock_settings.json", "r", encoding="utf-8") as f:
                    settings = json.load(f)
                    
                self.current_theme = settings.get("theme", self.current_theme)
                self.clock_style = settings.get("clock_style", self.clock_style)
                self.show_seconds = settings.get("show_seconds", self.show_seconds)
                self.show_date = settings.get("show_date", self.show_date)
                self.military_time = settings.get("military_time", self.military_time)
                self.alarm_enabled = settings.get("alarm_enabled", self.alarm_enabled)
                self.alarm_time = settings.get("alarm_time", self.alarm_time)
                
                # 更新UI
                self.theme_var.set(self.current_theme)
                self.change_theme()
                
                style_map_reverse = {v: k for k, v in {
                    "数字时钟": "digital",
                    "模拟时钟": "analog", 
                    "二进制时钟": "binary",
                    "翻页时钟": "flip"
                }.items()}
                self.style_var.set(style_map_reverse.get(self.clock_style, "数字时钟"))
                self.change_clock_style()
                
                self.seconds_var.set(self.show_seconds)
                self.date_var.set(self.show_date)
                self.military_var.set(self.military_time)
                self.alarm_var.set(self.alarm_enabled)
                
                if ":" in self.alarm_time:
                    hour, minute = self.alarm_time.split(":")
                    self.alarm_hour.set(hour)
                    self.alarm_minute.set(minute)
                    
        except Exception as e:
            print(f"加载设置失败: {str(e)}")
            
    def reset_settings(self):
        """重置设置为默认值"""
        if messagebox.askyesno("重置设置", "确定要重置所有设置为默认值吗？"):
            self.current_theme = "深色主题"
            self.clock_style = "digital"
            self.show_seconds = True
            self.show_date = True
            self.military_time = False
            self.alarm_enabled = False
            self.alarm_time = "07:00"
            
            # 更新UI
            self.theme_var.set(self.current_theme)
            self.change_theme()
            self.style_var.set("数字时钟")
            self.change_clock_style()
            self.seconds_var.set(self.show_seconds)
            self.date_var.set(self.show_date)
            self.military_var.set(self.military_time)
            self.alarm_var.set(self.alarm_enabled)
            self.alarm_hour.set("07")
            self.alarm_minute.set("00")
            
    def show_about(self):
        """显示关于信息"""
        about_text = """高级数字时钟 v1.0

功能特点：
• 多种时钟样式：数字、模拟、二进制、翻页
• 多主题切换
• 闹钟功能
• 多种显示选项
• 设置保存和加载

作者：元宝
创建时间：2024年"""
        
        messagebox.showinfo("关于", about_text)

def main():
    root = tk.Tk()
    app = DigitalClockApp(root)
    
    # 设置窗口最小大小
    root.minsize(800, 600)
    
    # 绑定快捷键
    root.bind("<F11>", lambda e: app.toggle_fullscreen())
    root.bind("<Escape>", lambda e: root.attributes("-fullscreen", False))
    root.bind("<Control-s>", lambda e: app.save_settings())
    root.bind("<Control-q>", lambda e: root.quit())
    
    root.mainloop()

if __name__ == "__main__":
    main()