import tkinter as tk
from tkinter import ttk, messagebox, font
import time
import json
import os
from datetime import datetime, timedelta
import threading


class TimerApp:
    def __init__(self, root):
        """
        初始化定时器应用
        Args:
            root: Tkinter根窗口
        """
        self.root = root
        self.root.title("精美定时器")
        self.root.geometry("1000x700")

        # 设置窗口图标
        try:
            self.root.iconbitmap('timer.ico')
        except:
            pass

        # 主题系统
        self.setup_themes()

        # 用户数据
        self.load_user_data()

        # 应用当前主题
        self.apply_theme(self.current_theme)

        # 定时器状态
        self.timer_running = False
        self.timer_paused = False
        self.time_left = 0
        self.total_time = 0
        self.start_time = None
        self.end_time = None

        # 时间设置
        self.hours = 0
        self.minutes = 0
        self.seconds = 0

        # 商店状态
        self.shop_open = False

        # 动画状态
        self.animation_active = False

        # 创建界面
        self.create_widgets()

        # 绑定事件
        self.bind_events()

        # 启动动画循环
        self.animation_loop()

    def setup_themes(self):
        """设置所有主题的颜色配置"""
        self.themes = {
            'default': {
                'name': '默认主题',
                'bg_color': '#f0f8ff',  # 爱丽丝蓝
                'timer_bg': '#ffffff',
                'timer_fg': '#2c3e50',
                'accent_color': '#3498db',
                'button_bg': '#3498db',
                'button_fg': '#ffffff',
                'shop_bg': '#f8f9fa',
                'shop_fg': '#495057',
                'success_color': '#2ecc71',
                'warning_color': '#f39c12',
                'error_color': '#e74c3c',
                'price': 0,  # 价格
                'unlocked': True  # 是否已解锁
            },
            'dark': {
                'name': '暗黑主题',
                'bg_color': '#2c3e50',
                'timer_bg': '#34495e',
                'timer_fg': '#ecf0f1',
                'accent_color': '#9b59b6',
                'button_bg': '#8e44ad',
                'button_fg': '#ffffff',
                'shop_bg': '#34495e',
                'shop_fg': '#bdc3c7',
                'success_color': '#27ae60',
                'warning_color': '#d35400',
                'error_color': '#c0392b',
                'price': 100,
                'unlocked': False
            },
            'nature': {
                'name': '自然主题',
                'bg_color': '#d5f4e6',
                'timer_bg': '#ffffff',
                'timer_fg': '#2c3e50',
                'accent_color': '#16a085',
                'button_bg': '#1abc9c',
                'button_fg': '#ffffff',
                'shop_bg': '#e8f6f3',
                'shop_fg': '#2c3e50',
                'success_color': '#27ae60',
                'warning_color': '#f39c12',
                'error_color': '#e74c3c',
                'price': 150,
                'unlocked': False
            },
            'sunset': {
                'name': '日落主题',
                'bg_color': '#ffeaa7',
                'timer_bg': '#ffffff',
                'timer_fg': '#2d3436',
                'accent_color': '#e17055',
                'button_bg': '#fab1a0',
                'button_fg': '#2d3436',
                'shop_bg': '#fdcb6e',
                'shop_fg': '#2d3436',
                'success_color': '#00b894',
                'warning_color': '#fdcb6e',
                'error_color': '#d63031',
                'price': 200,
                'unlocked': False
            },
            'ocean': {
                'name': '海洋主题',
                'bg_color': '#dff9fb',
                'timer_bg': '#ffffff',
                'timer_fg': '#130f40',
                'accent_color': '#00cec9',
                'button_bg': '#81ecec',
                'button_fg': '#130f40',
                'shop_bg': '#c7ecee',
                'shop_fg': '#130f40',
                'success_color': '#00b894',
                'warning_color': '#fdcb6e',
                'error_color': '#d63031',
                'price': 250,
                'unlocked': False
            },
            'space': {
                'name': '太空主题',
                'bg_color': '#0c2461',
                'timer_bg': '#1e3799',
                'timer_fg': '#ffffff',
                'accent_color': '#6c5ce7',
                'button_bg': '#6c5ce7',
                'button_fg': '#ffffff',
                'shop_bg': '#0c2461',
                'shop_fg': '#dfe6e9',
                'success_color': '#00b894',
                'warning_color': '#fdcb6e',
                'error_color': '#d63031',
                'price': 300,
                'unlocked': False
            }
        }

        # 为已解锁的主题设置unlocked=True
        self.themes['default']['unlocked'] = True

    def load_user_data(self):
        """加载用户数据"""
        self.data_file = 'timer_data.json'
        if os.path.exists(self.data_file):
            try:
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.coins = data.get('coins', 100)
                    self.unlocked_themes = data.get(
                        'unlocked_themes', ['default'])
                    self.current_theme = data.get('current_theme', 'default')

                    # 更新主题解锁状态
                    for theme_name in self.unlocked_themes:
                        if theme_name in self.themes:
                            self.themes[theme_name]['unlocked'] = True
            except Exception as e:
                print(f"加载用户数据失败: {e}")
                self.reset_user_data()
        else:
            self.reset_user_data()

    def reset_user_data(self):
        """重置用户数据"""
        self.coins = 100
        self.unlocked_themes = ['default']
        self.current_theme = 'default'
        self.save_user_data()

    def save_user_data(self):
        """保存用户数据"""
        data = {
            'coins': self.coins,
            'unlocked_themes': self.unlocked_themes,
            'current_theme': self.current_theme
        }
        with open(self.data_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)

    def apply_theme(self, theme_name):
        """应用主题"""
        if theme_name in self.themes:
            theme = self.themes[theme_name]
            self.current_theme = theme_name
            self.current_theme_config = theme

            # 保存当前主题
            self.save_user_data()

    def create_widgets(self):
        """创建所有界面组件"""
        # 主容器
        self.main_frame = ttk.Frame(self.root)
        self.main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 顶部栏
        self.create_top_bar()

        # 计时器显示区域
        self.create_timer_display()

        # 时间设置区域
        self.create_time_setting()

        # 控制按钮区域
        self.create_control_buttons()

        # 商店区域（初始隐藏）
        self.create_shop_area()

        # 状态栏
        self.create_status_bar()

    def create_top_bar(self):
        """创建顶部栏"""
        top_frame = ttk.Frame(self.main_frame)
        top_frame.pack(fill=tk.X, pady=(0, 20))

        # 标题
        title_label = tk.Label(
            top_frame,
            text="定时器",
            font=('Microsoft YaHei', 24, 'bold'),
            fg=self.current_theme_config['timer_fg'],
            bg=self.current_theme_config['bg_color']
        )
        title_label.pack(side=tk.LEFT)

        # 商店按钮
        self.shop_button = tk.Button(
            top_frame,
            text="商店",
            command=self.toggle_shop,
            bg=self.current_theme_config['button_bg'],
            fg=self.current_theme_config['button_fg'],
            font=('Microsoft YaHei', 12, 'bold'),
            padx=15,
            pady=5,
            relief=tk.RAISED,
            bd=2
        )
        self.shop_button.pack(side=tk.RIGHT, padx=5)

        # 金币显示
        self.coin_label = tk.Label(
            top_frame,
            text=f"金币: {self.coins}",
            font=('Microsoft YaHei', 12, 'bold'),
            fg='#FFD700',
            bg=self.current_theme_config['bg_color']
        )
        self.coin_label.pack(side=tk.RIGHT, padx=10)

        # 当前主题显示
        self.theme_label = tk.Label(
            top_frame,
            text=f"主题: {self.current_theme_config['name']}",
            font=('Microsoft YaHei', 10),
            fg=self.current_theme_config['accent_color'],
            bg=self.current_theme_config['bg_color']
        )
        self.theme_label.pack(side=tk.RIGHT, padx=10)

    def create_timer_display(self):
        """创建计时器显示区域"""
        timer_frame = ttk.Frame(self.main_frame)
        timer_frame.pack(fill=tk.X, pady=20)

        # 计时器显示框
        self.timer_canvas = tk.Canvas(
            timer_frame,
            width=400,
            height=200,
            bg=self.current_theme_config['timer_bg'],
            highlightthickness=2,
            highlightbackground=self.current_theme_config['accent_color']
        )
        self.timer_canvas.pack()

        # 时间显示
        self.time_display = self.timer_canvas.create_text(
            200, 100,
            text="00:00:00",
            font=('Consolas', 48, 'bold'),
            fill=self.current_theme_config['timer_fg']
        )

        # 状态显示
        self.status_display = self.timer_canvas.create_text(
            200, 160,
            text="就绪",
            font=('Microsoft YaHei', 12),
            fill=self.current_theme_config['accent_color']
        )

        # 进度条背景
        self.progress_bg = self.timer_canvas.create_rectangle(
            50, 180, 350, 190,
            fill='#e0e0e0',
            outline=''
        )

        # 进度条
        self.progress_bar = self.timer_canvas.create_rectangle(
            50, 180, 50, 190,
            fill=self.current_theme_config['accent_color'],
            outline=''
        )

    def create_time_setting(self):
        """创建时间设置区域"""
        setting_frame = ttk.LabelFrame(
            self.main_frame,
            text="时间设置",
            padding=20
        )
        setting_frame.pack(fill=tk.X, pady=10)

        # 小时设置
        hour_frame = ttk.Frame(setting_frame)
        hour_frame.pack(side=tk.LEFT, expand=True)

        tk.Label(
            hour_frame,
            text="小时:",
            font=('Microsoft YaHei', 12)
        ).pack()

        self.hour_var = tk.StringVar(value="0")
        self.hour_spinbox = tk.Spinbox(  # 使用 tk.Spinbox 而不是 ttk.Spinbox
            hour_frame,
            from_=0,
            to=23,
            textvariable=self.hour_var,
            width=10,
            font=('Microsoft YaHei', 12)
        )
        self.hour_spinbox.pack(pady=5)

        # 分钟设置
        minute_frame = ttk.Frame(setting_frame)
        minute_frame.pack(side=tk.LEFT, expand=True)

        tk.Label(
            minute_frame,
            text="分钟:",
            font=('Microsoft YaHei', 12)
        ).pack()

        self.minute_var = tk.StringVar(value="0")
        self.minute_spinbox = tk.Spinbox(  # 使用 tk.Spinbox
            minute_frame,
            from_=0,
            to=59,
            textvariable=self.minute_var,
            width=10,
            font=('Microsoft YaHei', 12)
        )
        self.minute_spinbox.pack(pady=5)

        # 秒设置
        second_frame = ttk.Frame(setting_frame)
        second_frame.pack(side=tk.LEFT, expand=True)

        tk.Label(
            second_frame,
            text="秒:",
            font=('Microsoft YaHei', 12)
        ).pack()

        self.second_var = tk.StringVar(value="0")
        self.second_spinbox = tk.Spinbox(  # 使用 tk.Spinbox
            second_frame,
            from_=0,
            to=59,
            textvariable=self.second_var,
            width=10,
            font=('Microsoft YaHei', 12)
        )
        self.second_spinbox.pack(pady=5)

    def create_control_buttons(self):
        """创建控制按钮区域"""
        button_frame = ttk.Frame(self.main_frame)
        button_frame.pack(fill=tk.X, pady=20)

        # 开始按钮
        self.start_button = tk.Button(
            button_frame,
            text="开始",
            command=self.start_timer,
            bg=self.current_theme_config['success_color'],
            fg='white',
            font=('Microsoft YaHei', 14, 'bold'),
            width=10,
            padx=20,
            pady=10
        )
        self.start_button.pack(side=tk.LEFT, expand=True, padx=5)

        # 暂停按钮
        self.pause_button = tk.Button(
            button_frame,
            text="暂停",
            command=self.pause_timer,
            bg=self.current_theme_config['warning_color'],
            fg='white',
            font=('Microsoft YaHei', 14, 'bold'),
            width=10,
            padx=20,
            pady=10,
            state=tk.DISABLED
        )
        self.pause_button.pack(side=tk.LEFT, expand=True, padx=5)

        # 重置按钮
        self.reset_button = tk.Button(
            button_frame,
            text="重置",
            command=self.reset_timer,
            bg=self.current_theme_config['error_color'],
            fg='white',
            font=('Microsoft YaHei', 14, 'bold'),
            width=10,
            padx=20,
            pady=10
        )
        self.reset_button.pack(side=tk.LEFT, expand=True, padx=5)

    def create_shop_area(self):
        """创建商店区域"""
        # 商店主框架
        self.shop_frame = ttk.Frame(self.main_frame)

        # 商店标题
        shop_title = tk.Label(
            self.shop_frame,
            text="主题商店",
            font=('Microsoft YaHei', 20, 'bold'),
            fg=self.current_theme_config['shop_fg']
        )
        shop_title.pack(pady=10)

        # 主题显示区域
        theme_frame = ttk.Frame(self.shop_frame)
        theme_frame.pack(fill=tk.BOTH, expand=True, pady=10)

        # 创建主题按钮
        self.theme_buttons = []
        themes_per_row = 3

        for i, (theme_name, theme_config) in enumerate(self.themes.items()):
            row = i // themes_per_row
            col = i % themes_per_row

            # 主题按钮框架
            theme_btn_frame = ttk.Frame(theme_frame)
            theme_btn_frame.grid(row=row, column=col,
                                 padx=10, pady=10, sticky='nsew')

            # 主题预览
            preview_canvas = tk.Canvas(
                theme_btn_frame,
                width=200,
                height=100,
                bg=theme_config['bg_color'],
                highlightthickness=2,
                highlightbackground=theme_config['accent_color']
            )
            preview_canvas.pack()

            # 主题名称
            preview_canvas.create_text(
                100, 30,
                text=theme_config['name'],
                font=('Microsoft YaHei', 12, 'bold'),
                fill=theme_config['timer_fg']
            )

            # 价格或状态
            if theme_config['unlocked']:
                if theme_name == self.current_theme:
                    status = "使用中"
                    status_color = theme_config['success_color']
                else:
                    status = "已解锁"
                    status_color = theme_config['success_color']
            else:
                status = f"{theme_config['price']} 金币"
                status_color = '#FFD700'  # 金色

            preview_canvas.create_text(
                100, 70,
                text=status,
                font=('Microsoft YaHei', 10),
                fill=status_color
            )

            # 购买/使用按钮
            if theme_config['unlocked']:
                if theme_name == self.current_theme:
                    btn_text = "使用中"
                    btn_state = tk.DISABLED
                else:
                    btn_text = "使用主题"
                    btn_state = tk.NORMAL
            else:
                btn_text = f"购买 ({theme_config['price']}金币)"
                btn_state = tk.NORMAL

            theme_button = tk.Button(
                theme_btn_frame,
                text=btn_text,
                command=lambda tn=theme_name: self.handle_theme_button(tn),
                bg=theme_config['button_bg'],
                fg=theme_config['button_fg'],
                font=('Microsoft YaHei', 10),
                padx=10,
                pady=5,
                state=btn_state
            )
            theme_button.pack(pady=5)

            self.theme_buttons.append({
                'name': theme_name,
                'button': theme_button,
                'canvas': preview_canvas
            })

        # 设置网格权重
        for i in range(themes_per_row):
            theme_frame.columnconfigure(i, weight=1)

        # 关闭商店按钮
        close_shop_btn = tk.Button(
            self.shop_frame,
            text="关闭商店",
            command=self.toggle_shop,
            bg=self.current_theme_config['button_bg'],
            fg=self.current_theme_config['button_fg'],
            font=('Microsoft YaHei', 12, 'bold'),
            padx=20,
            pady=5
        )
        close_shop_btn.pack(pady=10)

    def create_status_bar(self):
        """创建状态栏"""
        status_frame = ttk.Frame(self.main_frame)
        status_frame.pack(fill=tk.X, pady=(20, 0))

        # 状态信息
        self.status_label = tk.Label(
            status_frame,
            text="就绪",
            font=('Microsoft YaHei', 10),
            fg=self.current_theme_config['accent_color']
        )
        self.status_label.pack(side=tk.LEFT)

        # 版本信息
        version_label = tk.Label(
            status_frame,
            text="定时器 v1.0",
            font=('Microsoft YaHei', 9),
            fg='gray'
        )
        version_label.pack(side=tk.RIGHT)

    def bind_events(self):
        """绑定事件"""
        # 绑定键盘事件
        self.root.bind('<Return>', lambda e: self.start_timer())
        self.root.bind('<space>', lambda e: self.pause_timer())
        self.root.bind('<r>', lambda e: self.reset_timer())
        self.root.bind('<Escape>', lambda e: self.root.quit())
        self.root.bind('<s>', lambda e: self.toggle_shop())

    def toggle_shop(self):
        """切换商店显示"""
        if self.shop_open:
            # 隐藏商店
            self.shop_frame.pack_forget()
            self.shop_open = False
        else:
            # 显示商店
            self.shop_frame.pack(fill=tk.BOTH, expand=True, pady=20)
            self.shop_open = True
            # 更新商店显示
            self.update_shop_display()

    def update_shop_display(self):
        """更新商店显示"""
        for theme_info in self.theme_buttons:
            theme_name = theme_info['name']
            theme_config = self.themes[theme_name]
            button = theme_info['button']
            canvas = theme_info['canvas']

            # 更新按钮状态
            if theme_config['unlocked']:
                if theme_name == self.current_theme:
                    btn_text = "使用中"
                    btn_state = tk.DISABLED
                else:
                    btn_text = "使用主题"
                    btn_state = tk.NORMAL
            else:
                btn_text = f"购买 ({theme_config['price']}金币)"
                btn_state = tk.NORMAL

            button.config(text=btn_text, state=btn_state)

            # 更新状态显示
            canvas.delete("all")
            canvas.config(bg=theme_config['bg_color'])

            # 主题名称
            canvas.create_text(
                100, 30,
                text=theme_config['name'],
                font=('Microsoft YaHei', 12, 'bold'),
                fill=theme_config['timer_fg']
            )

            # 价格或状态
            if theme_config['unlocked']:
                if theme_name == self.current_theme:
                    status = "使用中"
                    status_color = theme_config['success_color']
                else:
                    status = "已解锁"
                    status_color = theme_config['success_color']
            else:
                status = f"{theme_config['price']} 金币"
                status_color = '#FFD700'

            canvas.create_text(
                100, 70,
                text=status,
                font=('Microsoft YaHei', 10),
                fill=status_color
            )

    def handle_theme_button(self, theme_name):
        """处理主题按钮点击"""
        theme_config = self.themes[theme_name]

        if theme_config['unlocked']:
            # 使用主题
            self.apply_theme(theme_name)
            self.update_ui_theme()
            self.update_shop_display()
            messagebox.showinfo("成功", f"已切换到{theme_config['name']}")
        else:
            # 购买主题
            if self.coins >= theme_config['price']:
                if messagebox.askyesno("确认购买", f"确定花费{theme_config['price']}金币购买{theme_config['name']}吗？"):
                    self.coins -= theme_config['price']
                    theme_config['unlocked'] = True
                    self.unlocked_themes.append(theme_name)
                    self.apply_theme(theme_name)
                    self.update_ui_theme()
                    self.update_coin_display()
                    self.update_shop_display()
                    self.save_user_data()
                    messagebox.showinfo("成功", f"已购买{theme_config['name']}！")
            else:
                messagebox.showerror(
                    "金币不足", f"金币不足！需要{theme_config['price']}金币，当前有{self.coins}金币")

    def update_ui_theme(self):
        """更新UI主题"""
        config = self.current_theme_config

        # 更新背景
        self.root.configure(bg=config['bg_color'])

        # 更新顶部栏
        for widget in self.main_frame.winfo_children()[0].winfo_children():
            if isinstance(widget, tk.Label):
                widget.config(bg=config['bg_color'], fg=config['timer_fg'])

        self.shop_button.config(
            bg=config['button_bg'],
            fg=config['button_fg']
        )
        self.coin_label.config(bg=config['bg_color'])
        self.theme_label.config(
            text=f"主题: {config['name']}",
            fg=config['accent_color'],
            bg=config['bg_color']
        )

        # 更新计时器显示
        self.timer_canvas.config(
            bg=config['timer_bg'],
            highlightbackground=config['accent_color']
        )
        self.timer_canvas.itemconfig(
            self.time_display,
            fill=config['timer_fg']
        )
        self.timer_canvas.itemconfig(
            self.status_display,
            fill=config['accent_color']
        )
        self.timer_canvas.itemconfig(
            self.progress_bar,
            fill=config['accent_color']
        )

        # 更新按钮
        self.start_button.config(bg=config['success_color'])
        self.pause_button.config(bg=config['warning_color'])
        self.reset_button.config(bg=config['error_color'])

        # 更新状态栏
        self.status_label.config(fg=config['accent_color'])

    def update_coin_display(self):
        """更新金币显示"""
        self.coin_label.config(text=f"金币: {self.coins}")

    def get_time_from_input(self):
        """从输入框获取时间"""
        try:
            hours = int(self.hour_var.get())
            minutes = int(self.minute_var.get())
            seconds = int(self.second_var.get())

            if hours < 0 or minutes < 0 or minutes >= 60 or seconds < 0 or seconds >= 60:
                raise ValueError("时间范围无效")

            return hours, minutes, seconds
        except ValueError:
            messagebox.showerror("输入错误", "请输入有效的时间！")
            return None

    def start_timer(self):
        """开始计时器"""
        if self.timer_running:
            return

        time_input = self.get_time_from_input()
        if time_input is None:
            return

        hours, minutes, seconds = time_input

        if hours == 0 and minutes == 0 and seconds == 0:
            messagebox.showerror("错误", "请设置有效的时间！")
            return

        # 计算总秒数
        self.total_time = hours * 3600 + minutes * 60 + seconds
        self.time_left = self.total_time

        # 记录开始时间
        self.start_time = datetime.now()
        self.end_time = self.start_time + timedelta(seconds=self.total_time)

        # 更新状态
        self.timer_running = True
        self.timer_paused = False

        # 更新按钮状态
        self.start_button.config(state=tk.DISABLED)
        self.pause_button.config(state=tk.NORMAL)
        self.reset_button.config(state=tk.NORMAL)

        # 更新输入框状态
        self.hour_spinbox.config(state=tk.DISABLED)
        self.minute_spinbox.config(state=tk.DISABLED)
        self.second_spinbox.config(state=tk.DISABLED)

        # 更新状态显示
        self.timer_canvas.itemconfig(
            self.status_display,
            text="运行中..."
        )
        self.status_label.config(text="计时器运行中...")

        # 启动计时器线程
        self.timer_thread = threading.Thread(
            target=self.timer_countdown, daemon=True)
        self.timer_thread.start()

    def pause_timer(self):
        """暂停/继续计时器"""
        if not self.timer_running:
            return

        self.timer_paused = not self.timer_paused

        if self.timer_paused:
            self.pause_button.config(text="继续")
            self.timer_canvas.itemconfig(
                self.status_display,
                text="已暂停"
            )
            self.status_label.config(text="计时器已暂停")
        else:
            self.pause_button.config(text="暂停")
            self.timer_canvas.itemconfig(
                self.status_display,
                text="运行中..."
            )
            self.status_label.config(text="计时器运行中...")

    def reset_timer(self):
        """重置计时器"""
        # 停止计时器
        self.timer_running = False
        self.timer_paused = False

        # 重置时间
        self.time_left = 0

        # 更新按钮状态
        self.start_button.config(state=tk.NORMAL)
        self.pause_button.config(state=tk.DISABLED, text="暂停")
        self.reset_button.config(state=tk.NORMAL)

        # 更新输入框状态
        self.hour_spinbox.config(state=tk.NORMAL)
        self.minute_spinbox.config(state=tk.NORMAL)
        self.second_spinbox.config(state=tk.NORMAL)

        # 更新显示
        self.update_timer_display()
        self.timer_canvas.itemconfig(
            self.status_display,
            text="就绪"
        )
        self.status_label.config(text="就绪")

        # 重置进度条
        self.timer_canvas.coords(self.progress_bar, 50, 180, 50, 190)

    def timer_countdown(self):
        """计时器倒计时线程"""
        while self.timer_running and self.time_left > 0:
            if not self.timer_paused:
                # 更新显示
                self.root.after(0, self.update_timer_display)

                # 等待1秒
                time.sleep(1)
                self.time_left -= 1
            else:
                # 如果暂停，等待0.1秒后继续检查
                time.sleep(0.1)

        # 计时器结束
        if self.timer_running and self.time_left <= 0:
            self.root.after(0, self.timer_finished)

    def update_timer_display(self):
        """更新计时器显示"""
        if self.time_left <= 0:
            return

        # 格式化时间显示
        hours = self.time_left // 3600
        minutes = (self.time_left % 3600) // 60
        seconds = self.time_left % 60

        time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
        self.timer_canvas.itemconfig(self.time_display, text=time_str)

        # 更新进度条
        if self.total_time > 0:
            progress = 1.0 - (self.time_left / self.total_time)
            bar_width = 300 * progress
            self.timer_canvas.coords(
                self.progress_bar,
                50, 180, 50 + bar_width, 190
            )

        # 更新结束时间显示
        if self.end_time:
            end_str = self.end_time.strftime("%H:%M:%S")
            self.status_label.config(text=f"结束于: {end_str}")

    def timer_finished(self):
        """计时器结束处理"""
        # 停止计时器
        self.timer_running = False

        # 更新按钮状态
        self.start_button.config(state=tk.NORMAL)
        self.pause_button.config(state=tk.DISABLED)
        self.reset_button.config(state=tk.NORMAL)

        # 更新输入框状态
        self.hour_spinbox.config(state=tk.NORMAL)
        self.minute_spinbox.config(state=tk.NORMAL)
        self.second_spinbox.config(state=tk.NORMAL)

        # 显示完成画面
        self.show_completion_screen()

        # 给予金币奖励
        reward = 10
        self.coins += reward
        self.update_coin_display()
        self.save_user_data()

        # 显示奖励消息
        messagebox.showinfo("完成！", f"计时完成！获得{reward}金币")

        # 更新状态
        self.status_label.config(text="计时完成")

    def show_completion_screen(self):
        """显示完成画面（根据主题不同）"""
        theme_name = self.current_theme
        config = self.current_theme_config

        # 创建完成画面窗口
        completion_window = tk.Toplevel(self.root)
        completion_window.title("计时完成！")
        completion_window.geometry("400x300")
        completion_window.configure(bg=config['bg_color'])

        # 设置窗口居中
        completion_window.transient(self.root)
        completion_window.grab_set()

        # 根据主题显示不同的完成画面
        if theme_name == 'default':
            # 默认主题完成画面
            title = "时间到！"
            message = "定时器已完成计时"
            color = config['accent_color']

        elif theme_name == 'dark':
            # 暗黑主题完成画面
            title = "夜幕降临"
            message = "暗黑时刻已结束"
            color = config['accent_color']

        elif theme_name == 'nature':
            # 自然主题完成画面
            title = "自然韵律"
            message = "与自然同步完成"
            color = config['success_color']

        elif theme_name == 'sunset':
            # 日落主题完成画面
            title = "日落时分"
            message = "美好时光已流逝"
            color = config['accent_color']

        elif theme_name == 'ocean':
            # 海洋主题完成画面
            title = "潮起潮落"
            message = "海洋节奏已完成"
            color = config['accent_color']

        elif theme_name == 'space':
            # 太空主题完成画面
            title = "太空漫游"
            message = "宇宙旅行已结束"
            color = config['accent_color']

        else:
            # 默认
            title = "时间到！"
            message = "定时器已完成计时"
            color = config['accent_color']

        # 标题
        tk.Label(
            completion_window,
            text=title,
            font=('Microsoft YaHei', 24, 'bold'),
            fg=color,
            bg=config['bg_color']
        ).pack(pady=20)

        # 图标
        tk.Label(
            completion_window,
            text="✓",
            font=('Microsoft YaHei', 48),
            fg=color,
            bg=config['bg_color']
        ).pack(pady=10)

        # 消息
        tk.Label(
            completion_window,
            text=message,
            font=('Microsoft YaHei', 14),
            fg=config['timer_fg'],
            bg=config['bg_color']
        ).pack(pady=10)

        # 金币奖励
        tk.Label(
            completion_window,
            text="获得10金币！",
            font=('Microsoft YaHei', 12, 'bold'),
            fg='#FFD700',
            bg=config['bg_color']
        ).pack(pady=10)

        # 关闭按钮
        tk.Button(
            completion_window,
            text="关闭",
            command=completion_window.destroy,
            bg=config['button_bg'],
            fg=config['button_fg'],
            font=('Microsoft YaHei', 12, 'bold'),
            padx=20,
            pady=5
        ).pack(pady=20)

        # 自动关闭
        completion_window.after(5000, completion_window.destroy)

    def animation_loop(self):
        """动画循环"""
        if self.timer_running and not self.timer_paused:
            # 闪烁效果
            current_color = self.timer_canvas.itemcget(
                self.time_display, 'fill')
            if current_color == self.current_theme_config['timer_fg']:
                new_color = self.current_theme_config['accent_color']
            else:
                new_color = self.current_theme_config['timer_fg']

            self.timer_canvas.itemconfig(self.time_display, fill=new_color)

        # 继续循环
        self.root.after(500, self.animation_loop)

    def run(self):
        """运行应用"""
        self.root.mainloop()


def main():
    """主函数"""
    print("=" * 50)
    print("精美定时器应用")
    print("=" * 50)
    print("功能说明:")
    print("1. 设置小时、分钟、秒")
    print("2. 点击'开始'按钮启动定时器")
    print("3. 点击'暂停'按钮暂停/继续")
    print("4. 点击'重置'按钮重置定时器")
    print("5. 点击'商店'按钮购买新主题")
    print("6. 完成计时可获得金币奖励")
    print("=" * 50)
    print("快捷键:")
    print("回车键: 开始计时器")
    print("空格键: 暂停/继续")
    print("R键: 重置计时器")
    print("S键: 打开/关闭商店")
    print("ESC键: 退出应用")
    print("=" * 50)

    root = tk.Tk()
    app = TimerApp(root)
    app.run()


if __name__ == "__main__":
    main()
