import tkinter as tk
from datetime import datetime
import random
from PIL import Image, ImageDraw, ImageTk
import math

class CartoonClock:
    def __init__(self, root):
        self.root = root
        self.root.title("🐰 卡通时钟 🎀")
        self.root.geometry("500x300")
        self.root.configure(bg='#FFF0F5')
        self.root.resizable(False, False)
        
        # 去除窗口边框
        self.root.overrideredirect(True)
        
        # 卡通主题颜色
        self.theme = {
            'bg': '#FFF0F5',  # 浅粉背景
            'clock_bg': '#FFE4E1',  # 时钟背景
            'clock_fg': '#FF69B4',  # 时钟文字
            'accent': '#FFB6C1',  # 装饰色
            'animal': '#FFC0CB',  # 动物颜色
            'secondary': '#DDA0DD'  # 次要颜色
        }
        
        # 卡通动物表情
        self.animals = ["🐰", "🐱", "🐶", "🐻", "🐼", "🐨", "🦊", "🐯"]
        self.current_animal = random.choice(self.animals)
        
        # 天气表情
        self.weathers = ["☀️", "⛅", "☁️", "🌧️", "❄️", "🌈", "☁️"]
        self.current_weather = random.choice(self.weathers)
        
        # 气泡消息列表
        self.messages = [
            "美好的一天开始啦！🎀",
            "要记得喝水哦！💧",
            "保持微笑~ 😊",
            "今天也要加油！💪",
            "休息一下吧！🍵",
            "时间过得真快！⏰"
        ]
        self.message_index = 0
        
        # 时钟样式
        self.show_seconds = True
        self.is_24_hour = True
        self.show_date = True
        
        # 动画相关
        self.bubbles = []
        self.stars = []
        self.create_bubbles()
        self.create_stars()
        
        # 鼠标位置（用于拖动）
        self.x = 0
        self.y = 0
        
        # 创建界面
        self.setup_ui()
        
        # 启动动画
        self.update_clock()
        self.animate()
        
        # 绑定事件
        self.bind_events()
    
    def setup_ui(self):
        """创建界面"""
        # 主容器
        self.main_frame = tk.Frame(self.root, bg=self.theme['bg'], 
                                  highlightthickness=2, highlightbackground=self.theme['accent'])
        self.main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题栏
        self.create_title_bar()
        
        # 动物显示区域
        self.create_animal_section()
        
        # 时钟显示区域
        self.create_clock_section()
        
        # 底部信息栏
        self.create_bottom_section()
        
        # 控制按钮
        self.create_control_buttons()
    
    def create_title_bar(self):
        """创建标题栏"""
        title_frame = tk.Frame(self.main_frame, bg=self.theme['accent'], height=30)
        title_frame.pack(fill=tk.X)
        title_frame.pack_propagate(False)
        
        # 标题
        title_label = tk.Label(title_frame, text="🐾 卡通时钟 🎨", 
                              bg=self.theme['accent'], fg='white',
                              font=('Arial Rounded MT Bold', 12))
        title_label.pack(side=tk.LEFT, padx=10)
        
        # 关闭按钮
        close_btn = tk.Label(title_frame, text="×", 
                           bg=self.theme['accent'], fg='white',
                           font=('Arial', 16, 'bold'), cursor='hand2')
        close_btn.pack(side=tk.RIGHT, padx=10)
        close_btn.bind('<Button-1>', lambda e: self.root.quit())
        
        # 最小化按钮
        min_btn = tk.Label(title_frame, text="－", 
                          bg=self.theme['accent'], fg='white',
                          font=('Arial', 16, 'bold'), cursor='hand2')
        min_btn.pack(side=tk.RIGHT, padx=5)
        min_btn.bind('<Button-1>', lambda e: self.root.iconify())
        
        # 绑定拖动事件
        title_frame.bind('<Button-1>', self.start_move)
        title_frame.bind('<B1-Motion>', self.on_move)
    
    def create_animal_section(self):
        """创建动物显示区域"""
        animal_frame = tk.Frame(self.main_frame, bg=self.theme['bg'], height=100)
        animal_frame.pack(fill=tk.X, pady=(10, 0))
        animal_frame.pack_propagate(False)
        
        # 大动物表情
        self.animal_label = tk.Label(animal_frame, text=self.current_animal,
                                    font=('Arial', 48), bg=self.theme['bg'])
        self.animal_label.pack()
        
        # 动物名称
        animal_names = {
            "🐰": "兔兔", "🐱": "猫猫", "🐶": "狗狗", "🐻": "熊熊",
            "🐼": "熊猫", "🐨": "考拉", "🦊": "狐狸", "🐯": "老虎"
        }
        
        self.animal_name = tk.Label(animal_frame, 
                                   text=animal_names.get(self.current_animal, "朋友"),
                                   font=('Microsoft YaHei', 12, 'bold'),
                                   bg=self.theme['bg'], fg=self.theme['clock_fg'])
        self.animal_name.pack()
        
        # 点击切换动物
        self.animal_label.bind('<Button-1>', self.change_animal)
        self.animal_name.bind('<Button-1>', self.change_animal)
    
    def create_clock_section(self):
        """创建时钟显示区域"""
        # 时钟背景
        clock_bg = tk.Frame(self.main_frame, bg=self.theme['clock_bg'],
                           relief=tk.RAISED, bd=3)
        clock_bg.pack(fill=tk.X, padx=20, pady=10)
        
        # 时间显示
        self.time_label = tk.Label(clock_bg, text="00:00:00",
                                  font=('Digital-7', 36, 'bold'),
                                  bg=self.theme['clock_bg'],
                                  fg=self.theme['clock_fg'])
        self.time_label.pack(pady=5)
        
        # 日期和星期显示
        self.date_label = tk.Label(clock_bg, text="2026年3月1日 星期六",
                                  font=('Microsoft YaHei', 12),
                                  bg=self.theme['clock_bg'],
                                  fg=self.theme['secondary'])
        self.date_label.pack(pady=(0, 5))
        
        # 气泡消息
        self.bubble_label = tk.Label(clock_bg, 
                                    text=self.messages[self.message_index],
                                    font=('Microsoft YaHei', 10, 'italic'),
                                    bg=self.theme['clock_bg'],
                                    fg=self.theme['clock_fg'],
                                    wraplength=300)
        self.bubble_label.pack(pady=(0, 5))
        
        # 点击切换消息
        self.bubble_label.bind('<Button-1>', self.change_message)
    
    def create_bottom_section(self):
        """创建底部信息栏"""
        bottom_frame = tk.Frame(self.main_frame, bg=self.theme['bg'])
        bottom_frame.pack(fill=tk.X, pady=(0, 10))
        
        # 天气显示
        weather_frame = tk.Frame(bottom_frame, bg=self.theme['bg'])
        weather_frame.pack(side=tk.LEFT, padx=20)
        
        self.weather_label = tk.Label(weather_frame, text=self.current_weather,
                                     font=('Arial', 20), bg=self.theme['bg'])
        self.weather_label.pack()
        
        weather_text = tk.Label(weather_frame, text="天气",
                               font=('Microsoft YaHei', 9),
                               bg=self.theme['bg'], fg=self.theme['secondary'])
        weather_text.pack()
        
        # 点击切换天气
        self.weather_label.bind('<Button-1>', self.change_weather)
        weather_text.bind('<Button-1>', self.change_weather)
        
        # 爱心计数器
        heart_frame = tk.Frame(bottom_frame, bg=self.theme['bg'])
        heart_frame.pack(side=tk.RIGHT, padx=20)
        
        self.heart_label = tk.Label(heart_frame, text="❤️ 0",
                                   font=('Arial', 20), bg=self.theme['bg'])
        self.heart_label.pack()
        
        heart_text = tk.Label(heart_frame, text="今日爱心",
                             font=('Microsoft YaHei', 9),
                             bg=self.theme['bg'], fg=self.theme['secondary'])
        heart_text.pack()
        
        # 点击增加爱心
        self.heart_label.bind('<Button-1>', self.add_heart)
        heart_text.bind('<Button-1>', self.add_heart)
        
        self.heart_count = 0
    
    def create_control_buttons(self):
        """创建控制按钮"""
        control_frame = tk.Frame(self.main_frame, bg=self.theme['bg'])
        control_frame.pack(fill=tk.X, pady=(0, 10))
        
        # 控制按钮容器
        btn_container = tk.Frame(control_frame, bg=self.theme['bg'])
        btn_container.pack()
        
        # 样式按钮
        buttons = [
            ("🎨 颜色", self.change_color),
            ("⏰ 格式", self.toggle_format),
            ("📅 日期", self.toggle_date),
            ("🌟 特效", self.toggle_effects)
        ]
        
        for text, command in buttons:
            btn = tk.Label(btn_container, text=text,
                          font=('Microsoft YaHei', 9),
                          bg=self.theme['accent'], fg='white',
                          padx=10, pady=5, cursor='hand2',
                          relief=tk.RAISED, bd=2)
            btn.pack(side=tk.LEFT, padx=5)
            btn.bind('<Button-1>', command)
        
        # 创建画布用于气泡和星星动画
        self.canvas = tk.Canvas(self.main_frame, bg=self.theme['bg'],
                               highlightthickness=0, height=0)
        self.canvas.pack(fill=tk.BOTH, expand=True)
    
    def create_bubbles(self):
        """创建气泡"""
        for _ in range(10):
            x = random.randint(0, 500)
            y = random.randint(0, 300)
            size = random.randint(5, 20)
            speed = random.uniform(0.5, 2)
            color = random.choice(['#FFB6C1', '#FFC0CB', '#DDA0DD', '#FF69B4'])
            self.bubbles.append({
                'x': x, 'y': y, 'size': size,
                'speed': speed, 'color': color
            })
    
    def create_stars(self):
        """创建星星"""
        for _ in range(15):
            x = random.randint(0, 500)
            y = random.randint(0, 300)
            size = random.randint(2, 8)
            speed = random.uniform(0.3, 1)
            self.stars.append({
                'x': x, 'y': y, 'size': size,
                'speed': speed, 'angle': random.uniform(0, 360)
            })
    
    def update_clock(self):
        """更新时间显示"""
        now = datetime.now()
        
        # 格式化时间
        if self.is_24_hour:
            time_format = "%H:%M" + (":%S" if self.show_seconds else "")
        else:
            time_format = "%I:%M" + (":%S" if self.show_seconds else " %p")
        
        time_str = now.strftime(time_format)
        
        # 添加数字时钟的特殊字体效果
        self.time_label.config(text=time_str)
        
        # 更新日期
        if self.show_date:
            date_str = now.strftime("%Y年%m月%d日 星期")
            weekdays = ["一", "二", "三", "四", "五", "六", "日"]
            date_str += weekdays[now.weekday()]
            self.date_label.config(text=date_str)
        else:
            self.date_label.config(text="")
        
        # 动物表情随小时变化
        hour = now.hour
        if 6 <= hour < 12:  # 早上
            morning_animals = ["🐰", "🐱", "🐶"]
            if self.current_animal not in morning_animals:
                self.change_animal(None)
        elif 12 <= hour < 18:  # 下午
            afternoon_animals = ["🐻", "🐼", "🐨"]
            if self.current_animal not in afternoon_animals:
                self.change_animal(None)
        else:  # 晚上
            evening_animals = ["🦊", "🐯", "🦉"]
            if self.current_animal not in evening_animals:
                self.change_animal(None)
        
        # 每100ms更新一次
        self.root.after(100, self.update_clock)
    
    def animate(self):
        """动画效果"""
        # 清空画布
        self.canvas.delete("all")
        
        # 绘制气泡
        for bubble in self.bubbles:
            bubble['y'] -= bubble['speed']
            if bubble['y'] < -bubble['size']:
                bubble['y'] = 300
                bubble['x'] = random.randint(0, 500)
            
            # 绘制气泡
            x1 = bubble['x'] - bubble['size']
            y1 = bubble['y'] - bubble['size']
            x2 = bubble['x'] + bubble['size']
            y2 = bubble['y'] + bubble['size']
            
            self.canvas.create_oval(x1, y1, x2, y2,
                                   fill=bubble['color'],
                                   outline='', width=0,
                                   stipple='gray50')
        
        # 绘制星星
        for star in self.stars:
            # 计算新位置
            star['angle'] += star['speed']
            star['x'] = 250 + math.cos(math.radians(star['angle'])) * 100
            star['y'] = 150 + math.sin(math.radians(star['angle'])) * 80
            
            # 绘制星星
            points = []
            for i in range(5):
                angle = math.radians(star['angle'] + i * 72)
                if i % 2 == 0:
                    r = star['size']
                else:
                    r = star['size'] / 2
                x = star['x'] + r * math.cos(angle)
                y = star['y'] + r * math.sin(angle)
                points.extend([x, y])
            
            self.canvas.create_polygon(points, fill='#FFD700',
                                      outline='', width=0)
        
        # 下一帧动画
        self.root.after(50, self.animate)
    
    def change_animal(self, event):
        """切换动物"""
        animals_copy = self.animals.copy()
        animals_copy.remove(self.current_animal)
        self.current_animal = random.choice(animals_copy)
        self.animal_label.config(text=self.current_animal)
        
        # 更新动物名称
        animal_names = {
            "🐰": "兔兔", "🐱": "猫猫", "🐶": "狗狗", "🐻": "熊熊",
            "🐼": "熊猫", "🐨": "考拉", "🦊": "狐狸", "🐯": "老虎"
        }
        self.animal_name.config(text=animal_names.get(self.current_animal, "朋友"))
        
        # 添加动画效果
        self.animal_label.config(fg=random.choice(['#FF69B4', '#FF1493', '#C71585']))
        self.root.after(200, lambda: self.animal_label.config(fg='black'))
    
    def change_weather(self, event):
        """切换天气"""
        weathers_copy = self.weathers.copy()
        weathers_copy.remove(self.current_weather)
        self.current_weather = random.choice(weathers_copy)
        self.weather_label.config(text=self.current_weather)
    
    def add_heart(self, event):
        """增加爱心"""
        self.heart_count += 1
        self.heart_label.config(text=f"❤️ {self.heart_count}")
        
        # 添加爱心动画
        x, y = self.heart_label.winfo_rootx(), self.heart_label.winfo_rooty()
        heart_pop = tk.Label(self.root, text="+❤️", 
                            font=('Arial', 12, 'bold'),
                            fg='#FF1493', bg=self.theme['bg'])
        heart_pop.place(x=x, y=y)
        
        # 上升动画
        def rise():
            for i in range(20):
                y_pos = y - i * 3
                heart_pop.place(y=y_pos)
                self.root.update()
                self.root.after(20)
            heart_pop.destroy()
        
        self.root.after(0, rise)
    
    def change_message(self, event):
        """切换气泡消息"""
        self.message_index = (self.message_index + 1) % len(self.messages)
        self.bubble_label.config(text=self.messages[self.message_index])
    
    def change_color(self, event):
        """切换颜色主题"""
        themes = [
            {
                'name': '粉色',
                'bg': '#FFF0F5', 'clock_bg': '#FFE4E1',
                'clock_fg': '#FF69B4', 'accent': '#FFB6C1',
                'animal': '#FFC0CB', 'secondary': '#DDA0DD'
            },
            {
                'name': '蓝色',
                'bg': '#F0F8FF', 'clock_bg': '#E6F3FF',
                'clock_fg': '#1E90FF', 'accent': '#87CEFA',
                'animal': '#ADD8E6', 'secondary': '#B0C4DE'
            },
            {
                'name': '绿色',
                'bg': '#F0FFF0', 'clock_bg': '#E8F5E8',
                'clock_fg': '#32CD32', 'accent': '#98FB98',
                'animal': '#90EE90', 'secondary': '#AFEEEE'
            },
            {
                'name': '紫色',
                'bg': '#F8F0FF', 'clock_bg': '#F0E6FF',
                'clock_fg': '#9370DB', 'accent': '#D8BFD8',
                'animal': '#DDA0DD', 'secondary': '#EE82EE'
            }
        ]
        
        # 循环切换主题
        current_index = 0
        for i, theme in enumerate(themes):
            if theme['clock_fg'] == self.theme['clock_fg']:
                current_index = i
                break
        
        next_index = (current_index + 1) % len(themes)
        self.theme = themes[next_index]
        
        # 应用新主题
        self.apply_theme()
        
        # 显示主题名称
        self.show_notification(f"切换到{themes[next_index]['name']}主题")
    
    def apply_theme(self):
        """应用主题"""
        # 更新根窗口
        self.root.configure(bg=self.theme['bg'])
        self.main_frame.configure(bg=self.theme['bg'], 
                                 highlightbackground=self.theme['accent'])
        
        # 更新标题栏
        for widget in self.main_frame.winfo_children()[0].winfo_children():
            widget.configure(bg=self.theme['accent'])
        
        # 更新动物区域
        for widget in self.main_frame.winfo_children()[1].winfo_children():
            widget.configure(bg=self.theme['bg'])
        
        # 更新时钟区域
        clock_bg = self.main_frame.winfo_children()[2]
        clock_bg.configure(bg=self.theme['clock_bg'])
        for widget in clock_bg.winfo_children():
            if isinstance(widget, tk.Label):
                widget.configure(bg=self.theme['clock_bg'], 
                               fg=self.theme['clock_fg'])
        
        # 更新底部区域
        bottom_frame = self.main_frame.winfo_children()[3]
        bottom_frame.configure(bg=self.theme['bg'])
        for widget in bottom_frame.winfo_children():
            for child in widget.winfo_children():
                child.configure(bg=self.theme['bg'])
        
        # 更新控制按钮
        control_frame = self.main_frame.winfo_children()[4]
        control_frame.configure(bg=self.theme['bg'])
        for widget in control_frame.winfo_children():
            for child in widget.winfo_children():
                if isinstance(child, tk.Label):
                    child.configure(bg=self.theme['accent'])
        
        # 更新画布
        self.canvas.configure(bg=self.theme['bg'])
    
    def toggle_format(self, event):
        """切换时间格式"""
        self.is_24_hour = not self.is_24_hour
        format_text = "24小时制" if self.is_24_hour else "12小时制"
        self.show_notification(f"切换到{format_text}")
    
    def toggle_date(self, event):
        """切换日期显示"""
        self.show_date = not self.show_date
        date_text = "显示日期" if self.show_date else "隐藏日期"
        self.show_notification(date_text)
    
    def toggle_effects(self, event):
        """切换特效"""
        if self.canvas.winfo_height() == 0:
            self.canvas.configure(height=100)
            self.show_notification("开启特效")
        else:
            self.canvas.configure(height=0)
            self.show_notification("关闭特效")
    
    def show_notification(self, message):
        """显示通知"""
        # 创建通知标签
        notification = tk.Label(self.main_frame, text=message,
                               font=('Microsoft YaHei', 10, 'bold'),
                               bg=self.theme['accent'], fg='white',
                               padx=10, pady=5)
        notification.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
        
        # 淡出效果
        def fade_out(alpha=1.0):
            if alpha > 0:
                color = self.mix_colors(self.theme['accent'], 'white', alpha)
                notification.configure(bg=color)
                notification.place(relx=0.5, rely=0.5 - (1-alpha)*0.1, anchor=tk.CENTER)
                self.root.after(50, fade_out, alpha-0.1)
            else:
                notification.destroy()
        
        fade_out()
    
    def mix_colors(self, color1, color2, ratio):
        """混合两种颜色"""
        # 简化版本，实际使用中可以实现完整的颜色混合
        return color1
    
    def start_move(self, event):
        """开始移动窗口"""
        self.x = event.x
        self.y = event.y
    
    def on_move(self, event):
        """移动窗口"""
        deltax = event.x - self.x
        deltay = event.y - self.y
        x = self.root.winfo_x() + deltax
        y = self.root.winfo_y() + deltay
        self.root.geometry(f"+{x}+{y}")
    
    def bind_events(self):
        """绑定事件"""
        # 双击退出
        self.root.bind('<Double-Button-1>', lambda e: self.root.quit())
        
        # 右键菜单
        self.root.bind('<Button-3>', self.show_context_menu)
    
    def show_context_menu(self, event):
        """显示右键菜单"""
        menu = tk.Menu(self.root, tearoff=0, bg=self.theme['accent'], fg='white')
        menu.add_command(label="🎨 随机主题", command=lambda: self.change_color(None))
        menu.add_command(label="🔄 随机动物", command=lambda: self.change_animal(None))
        menu.add_command(label="✨ 随机天气", command=lambda: self.change_weather(None))
        menu.add_separator()
        menu.add_command(label="❌ 退出", command=self.root.quit)
        
        try:
            menu.tk_popup(event.x_root, event.y_root)
        finally:
            menu.grab_release()

def main():
    root = tk.Tk()
    
    # 设置窗口居中
    window_width = 500
    window_height = 300
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = (screen_width - window_width) // 2
    y = (screen_height - window_height) // 2
    root.geometry(f"{window_width}x{window_height}+{x}+{y}")
    
    # 设置窗口透明度
    root.attributes('-alpha', 0.95)
    
    # 创建应用
    clock = CartoonClock(root)
    
    root.mainloop()

if __name__ == "__main__":
    main()