import tkinter as tk
from tkinter import ttk, messagebox
import random
import math
import json
import os
from datetime import datetime
from tkinter import filedialog

class LuckyWheel:
    def __init__(self, root):
        self.root = root
        self.root.title("幸运大转盘抽奖系统")
        self.root.geometry("1000x700")
        self.root.configure(bg='#2c3e50')
        
        # 设置窗口图标
        try:
            self.root.iconbitmap(default='lucky_wheel.ico')
        except:
            pass
        
        # 颜色主题
        self.colors = {
            'bg': '#2c3e50',
            'primary': '#e74c3c',
            'secondary': '#3498db',
            'accent': '#2ecc71',
            'success': '#27ae60',
            'warning': '#f39c12',
            'danger': '#c0392b',
            'info': '#3498db',  # 添加了缺失的info颜色
            'card_bg': '#34495e',
            'text': '#ecf0f1',
            'light_text': '#bdc3c7',
            'wheel_bg': ['#e74c3c', '#3498db', '#2ecc71', '#f39c12', 
                        '#9b59b6', '#1abc9c', '#e67e22', '#d35400',
                        '#16a085', '#8e44ad', '#2c3e50', '#7f8c8d']
        }
        
        # 默认奖项设置
        self.default_prizes = [
            "一等奖\niPhone 15 Pro",
            "二等奖\niPad Air",
            "三等奖\nAirPods Pro",
            "幸运奖\n小米手环",
            "谢谢参与\n再接再厉",
            "特别奖\n蓝牙音箱",
            "鼓励奖\n精美笔记本",
            "惊喜奖\n100元红包"
        ]
        
        # 初始化奖项列表
        self.prizes = self.default_prizes.copy()
        
        # 抽奖记录
        self.history = []
        
        # 当前抽奖者
        self.current_participant = ""
        
        # 转盘状态
        self.is_spinning = False
        self.spin_angle = 0
        self.speed = 0
        
        # 动画参数
        self.deceleration = 0.5
        self.min_speed = 0.5
        
        # 转盘设置
        self.wheel_radius = 250
        self.center_x = 300
        self.center_y = 300
        
        # 创建界面
        self.setup_ui()
        
        # 加载保存的奖项
        self.load_prizes()
    
    def setup_ui(self):
        """设置用户界面"""
        # 主容器
        main_container = tk.Frame(self.root, bg=self.colors['bg'])
        main_container.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 标题区域
        title_frame = tk.Frame(main_container, bg=self.colors['primary'], height=80)
        title_frame.pack(fill=tk.X, pady=(0, 20))
        title_frame.pack_propagate(False)
        
        title_label = tk.Label(
            title_frame,
            text="🎡 幸运大转盘抽奖系统 🎡",
            font=('Microsoft YaHei', 24, 'bold'),
            fg='white',
            bg=self.colors['primary']
        )
        title_label.pack(expand=True)
        
        subtitle_label = tk.Label(
            title_frame,
            text="转动幸运轮盘，开启好运之旅！",
            font=('Microsoft YaHei', 12),
            fg='#f0f0f0',
            bg=self.colors['primary']
        )
        subtitle_label.pack(pady=(0, 10))
        
        # 主内容区域
        content_frame = tk.Frame(main_container, bg=self.colors['bg'])
        content_frame.pack(fill=tk.BOTH, expand=True)
        
        # 左侧：转盘和控制区
        left_frame = tk.Frame(content_frame, bg=self.colors['bg'], width=650)
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        left_frame.pack_propagate(False)
        
        # 右侧：设置和历史区
        right_frame = tk.Frame(content_frame, bg=self.colors['bg'], width=350)
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, padx=(20, 0))
        right_frame.pack_propagate(False)
        
        # 左侧内容
        self.setup_wheel_area(left_frame)
        self.setup_control_area(left_frame)
        
        # 右侧内容
        self.setup_settings_area(right_frame)
        self.setup_history_area(right_frame)
        
        # 状态栏
        self.setup_status_bar(main_container)
    
    def setup_wheel_area(self, parent):
        """设置转盘区域"""
        wheel_card = self.create_card(parent, "幸运大转盘")
        wheel_card.pack(fill=tk.BOTH, expand=True, pady=(0, 20))
        
        # 转盘画布
        self.wheel_canvas = tk.Canvas(
            wheel_card,
            bg='white',
            highlightthickness=0,
            width=600,
            height=600
        )
        self.wheel_canvas.pack(expand=True, padx=20, pady=20)
        
        # 绘制初始转盘
        self.draw_wheel()
        
        # 指针
        self.draw_pointer()
    
    def setup_control_area(self, parent):
        """设置控制区域"""
        control_card = self.create_card(parent, "抽奖控制")
        control_card.pack(fill=tk.X, pady=(0, 0))
        
        control_frame = tk.Frame(control_card, bg=self.colors['card_bg'])
        control_frame.pack(fill=tk.X, padx=20, pady=20)
        
        # 抽奖者输入
        input_frame = tk.Frame(control_frame, bg=self.colors['card_bg'])
        input_frame.pack(fill=tk.X, pady=(0, 15))
        
        tk.Label(
            input_frame,
            text="抽奖者姓名:",
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['text'],
            bg=self.colors['card_bg']
        ).pack(side=tk.LEFT, padx=(0, 10))
        
        self.participant_var = tk.StringVar()
        self.participant_entry = tk.Entry(
            input_frame,
            textvariable=self.participant_var,
            font=('Microsoft YaHei', 12),
            width=20,
            bd=2,
            relief=tk.GROOVE
        )
        self.participant_entry.pack(side=tk.LEFT, padx=(0, 20))
        self.participant_entry.bind('<Return>', lambda e: self.start_spin())
        
        # 结果显示
        self.result_var = tk.StringVar(value="等待抽奖...")
        result_label = tk.Label(
            input_frame,
            textvariable=self.result_var,
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['accent'],
            bg=self.colors['card_bg']
        )
        result_label.pack(side=tk.LEFT)
        
        # 控制按钮
        btn_frame = tk.Frame(control_frame, bg=self.colors['card_bg'])
        btn_frame.pack(fill=tk.X)
        
        buttons = [
            ("🎰 开始抽奖", self.start_spin, self.colors['success']),
            ("⏸️ 停止", self.stop_spin, self.colors['warning']),
            ("🔄 重置", self.reset_spin, self.colors['secondary']),
            ("🎯 随机测试", self.random_test, '#9b59b6')
        ]
        
        for i, (text, command, color) in enumerate(buttons):
            btn = tk.Button(
                btn_frame,
                text=text,
                command=command,
                font=('Microsoft YaHei', 11, 'bold'),
                bg=color,
                fg='white',
                activebackground=color,
                activeforeground='white',
                bd=0,
                padx=20,
                pady=10,
                cursor='hand2',
                relief=tk.RAISED
            )
            btn.grid(row=0, column=i, padx=5, pady=5, sticky='ew')
            btn_frame.grid_columnconfigure(i, weight=1)
    
    def setup_settings_area(self, parent):
        """设置奖项设置区域"""
        settings_card = self.create_card(parent, "奖项设置")
        settings_card.pack(fill=tk.BOTH, expand=True, pady=(0, 20))
        
        settings_frame = tk.Frame(settings_card, bg=self.colors['card_bg'])
        settings_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 奖项列表标题
        tk.Label(
            settings_frame,
            text="奖项列表:",
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['text'],
            bg=self.colors['card_bg']
        ).pack(anchor=tk.W, pady=(0, 10))
        
        # 奖项列表框
        list_frame = tk.Frame(settings_frame, bg=self.colors['card_bg'])
        list_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
        
        # 滚动条
        scrollbar = tk.Scrollbar(list_frame)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 列表框
        self.prize_listbox = tk.Listbox(
            list_frame,
            font=('Microsoft YaHei', 11),
            bg='white',
            fg='#2c3e50',
            selectbackground=self.colors['secondary'],
            selectforeground='white',
            height=8,
            yscrollcommand=scrollbar.set
        )
        self.prize_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.config(command=self.prize_listbox.yview)
        
        # 更新奖项列表显示
        self.update_prize_list()
        
        # 奖项编辑按钮
        edit_frame = tk.Frame(settings_frame, bg=self.colors['card_bg'])
        edit_frame.pack(fill=tk.X, pady=(0, 10))
        
        # 奖项输入
        self.prize_var = tk.StringVar()
        prize_entry = tk.Entry(
            edit_frame,
            textvariable=self.prize_var,
            font=('Microsoft YaHei', 11),
            width=20,
            bd=2,
            relief=tk.GROOVE
        )
        prize_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
        prize_entry.bind('<Return>', lambda e: self.add_prize())
        
        add_btn = tk.Button(
            edit_frame,
            text="添加",
            command=self.add_prize,
            font=('Microsoft YaHei', 10),
            bg=self.colors['success'],
            fg='white',
            bd=0,
            padx=15,
            cursor='hand2'
        )
        add_btn.pack(side=tk.LEFT, padx=(0, 5))
        
        remove_btn = tk.Button(
            edit_frame,
            text="删除",
            command=self.remove_prize,
            font=('Microsoft YaHei', 10),
            bg=self.colors['danger'],
            fg='white',
            bd=0,
            padx=15,
            cursor='hand2'
        )
        remove_btn.pack(side=tk.LEFT)
        
        # 管理按钮
        manage_frame = tk.Frame(settings_frame, bg=self.colors['card_bg'])
        manage_frame.pack(fill=tk.X)
        
        # 修复这里：使用正确的颜色键
        manage_buttons = [
            ("💾 保存", self.save_prizes, self.colors['info']),  # 使用info颜色
            ("📂 加载", self.load_prizes_dialog, self.colors['secondary']),
            ("🔄 重置", self.reset_prizes, self.colors['warning'])
        ]
        
        for i, (text, command, color) in enumerate(manage_buttons):
            btn = tk.Button(
                manage_frame,
                text=text,
                command=command,
                font=('Microsoft YaHei', 10),
                bg=color,
                fg='white',
                bd=0,
                padx=10,
                pady=5,
                cursor='hand2'
            )
            btn.grid(row=0, column=i, padx=2, sticky='ew')
            manage_frame.grid_columnconfigure(i, weight=1)
    
    def setup_history_area(self, parent):
        """设置历史记录区域"""
        history_card = self.create_card(parent, "📜 抽奖记录")
        history_card.pack(fill=tk.BOTH, expand=True)
        
        history_frame = tk.Frame(history_card, bg=self.colors['card_bg'])
        history_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 历史记录标题
        tk.Label(
            history_frame,
            text="最近抽奖记录:",
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['text'],
            bg=self.colors['card_bg']
        ).pack(anchor=tk.W, pady=(0, 10))
        
        # 历史记录文本框
        self.history_text = tk.Text(
            history_frame,
            font=('Microsoft YaHei', 10),
            bg='white',
            fg='#2c3e50',
            width=30,
            height=8,
            wrap=tk.WORD,
            state=tk.DISABLED
        )
        self.history_text.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
        
        # 历史记录控制按钮
        history_btn_frame = tk.Frame(history_frame, bg=self.colors['card_bg'])
        history_btn_frame.pack(fill=tk.X)
        
        clear_btn = tk.Button(
            history_btn_frame,
            text="清空记录",
            command=self.clear_history,
            font=('Microsoft YaHei', 10),
            bg=self.colors['danger'],
            fg='white',
            bd=0,
            padx=15,
            pady=5,
            cursor='hand2'
        )
        clear_btn.pack(side=tk.LEFT, padx=(0, 10))
        
        export_btn = tk.Button(
            history_btn_frame,
            text="导出记录",
            command=self.export_history,
            font=('Microsoft YaHei', 10),
            bg=self.colors['success'],
            fg='white',
            bd=0,
            padx=15,
            pady=5,
            cursor='hand2'
        )
        export_btn.pack(side=tk.LEFT)
    
    def setup_status_bar(self, parent):
        """设置状态栏"""
        status_frame = tk.Frame(parent, bg='#1a252f', height=30)
        status_frame.pack(fill=tk.X, side=tk.BOTTOM)
        status_frame.pack_propagate(False)
        
        self.status_var = tk.StringVar(value="就绪 | 奖项数量: {} | 总抽奖次数: {}".format(
            len(self.prizes), len(self.history)))
        
        status_label = tk.Label(
            status_frame,
            textvariable=self.status_var,
            font=('Microsoft YaHei', 9),
            fg='white',
            bg='#1a252f',
            anchor=tk.W,
            padx=10
        )
        status_label.pack(fill=tk.X)
    
    def create_card(self, parent, title):
        """创建卡片式容器"""
        card = tk.Frame(parent, bg=self.colors['card_bg'], relief=tk.RAISED, bd=2)
        
        # 标题
        title_label = tk.Label(
            card,
            text=title,
            font=('Microsoft YaHei', 12, 'bold'),
            fg=self.colors['text'],
            bg=self.colors['card_bg'],
            anchor='w'
        )
        title_label.pack(fill=tk.X, padx=15, pady=10)
        
        # 分隔线
        separator = tk.Frame(card, height=1, bg='#4a6572')
        separator.pack(fill=tk.X, padx=10)
        
        return card
    
    def draw_wheel(self):
        """绘制转盘"""
        self.wheel_canvas.delete("wheel")
        
        n = len(self.prizes)
        if n == 0:
            n = 1
            angle = 360
        else:
            angle = 360 / n
        
        for i in range(n):
            # 计算扇形起始和结束角度
            start_angle = i * angle
            end_angle = (i + 1) * angle
            
            # 转换为弧度
            start_rad = math.radians(start_angle)
            end_rad = math.radians(end_angle)
            
            # 计算扇形边界点
            points = [self.center_x, self.center_y]
            
            # 起始点
            x1 = self.center_x + self.wheel_radius * math.cos(start_rad)
            y1 = self.center_y + self.wheel_radius * math.sin(start_rad)
            points.extend([x1, y1])
            
            # 绘制扇形
            for a in range(int(start_angle), int(end_angle) + 1):
                rad = math.radians(a)
                x = self.center_x + self.wheel_radius * math.cos(rad)
                y = self.center_y + self.wheel_radius * math.sin(rad)
                points.extend([x, y])
            
            # 结束点
            x2 = self.center_x + self.wheel_radius * math.cos(end_rad)
            y2 = self.center_y + self.wheel_radius * math.sin(end_rad)
            points.extend([x2, y2])
            
            # 闭合图形
            points.extend([self.center_x, self.center_y])
            
            # 绘制扇形
            color = self.colors['wheel_bg'][i % len(self.colors['wheel_bg'])]
            self.wheel_canvas.create_polygon(
                points,
                fill=color,
                outline='white',
                width=2,
                tags="wheel"
            )
            
            # 绘制文本
            mid_angle = math.radians(start_angle + angle / 2)
            text_radius = self.wheel_radius * 0.6
            text_x = self.center_x + text_radius * math.cos(mid_angle)
            text_y = self.center_y + text_radius * math.sin(mid_angle)
            
            # 分割奖品文本
            prize_text = self.prizes[i] if i < len(self.prizes) else "空白"
            lines = prize_text.split('\n')
            
            for j, line in enumerate(lines):
                y_offset = (j - len(lines)/2 + 0.5) * 20
                self.wheel_canvas.create_text(
                    text_x,
                    text_y + y_offset,
                    text=line,
                    font=('Microsoft YaHei', 10, 'bold'),
                    fill='white',
                    angle=start_angle + angle/2,
                    tags="wheel"
                )
        
        # 绘制中心圆
        self.wheel_canvas.create_oval(
            self.center_x - 20,
            self.center_y - 20,
            self.center_x + 20,
            self.center_y + 20,
            fill=self.colors['primary'],
            outline='white',
            width=3,
            tags="wheel"
        )
        
        # 绘制外圈装饰
        self.wheel_canvas.create_oval(
            self.center_x - self.wheel_radius - 5,
            self.center_y - self.wheel_radius - 5,
            self.center_x + self.wheel_radius + 5,
            self.center_y + self.wheel_radius + 5,
            outline='#e74c3c',
            width=4,
            tags="wheel"
        )
    
    def draw_pointer(self):
        """绘制指针"""
        self.wheel_canvas.delete("pointer")
        
        # 绘制指针三角形
        pointer_length = 20
        pointer_width = 15
        
        points = [
            self.center_x, self.center_y - self.wheel_radius - pointer_length,
            self.center_x - pointer_width, self.center_y - self.wheel_radius + 5,
            self.center_x + pointer_width, self.center_y - self.wheel_radius + 5
        ]
        
        self.wheel_canvas.create_polygon(
            points,
            fill=self.colors['danger'],
            outline='white',
            width=2,
            tags="pointer"
        )
        
        # 绘制指针圆点
        self.wheel_canvas.create_oval(
            self.center_x - 5,
            self.center_y - 5,
            self.center_x + 5,
            self.center_y + 5,
            fill=self.colors['danger'],
            outline='white',
            width=2,
            tags="pointer"
        )
    
    def update_prize_list(self):
        """更新奖项列表显示"""
        self.prize_listbox.delete(0, tk.END)
        for i, prize in enumerate(self.prizes, 1):
            self.prize_listbox.insert(tk.END, f"{i}. {prize}")
    
    def update_history_display(self):
        """更新历史记录显示"""
        self.history_text.config(state=tk.NORMAL)
        self.history_text.delete(1.0, tk.END)
        
        if not self.history:
            self.history_text.insert(tk.END, "暂无抽奖记录")
        else:
            for i, record in enumerate(reversed(self.history[-10:]), 1):
                timestamp, participant, prize = record
                self.history_text.insert(tk.END, f"{i}. {timestamp}\n")
                self.history_text.insert(tk.END, f"   参与者: {participant}\n")
                self.history_text.insert(tk.END, f"   奖项: {prize}\n")
                self.history_text.insert(tk.END, "-" * 30 + "\n")
        
        self.history_text.config(state=tk.DISABLED)
        self.status_var.set("就绪 | 奖项数量: {} | 总抽奖次数: {}".format(
            len(self.prizes), len(self.history)))
    
    def add_prize(self):
        """添加奖项"""
        prize = self.prize_var.get().strip()
        if prize:
            self.prizes.append(prize)
            self.prize_var.set("")
            self.update_prize_list()
            self.draw_wheel()
            self.status_var.set("✅ 已添加奖项: {}".format(prize))
        else:
            messagebox.showwarning("输入错误", "请输入奖项内容")
    
    def remove_prize(self):
        """删除选中奖项"""
        selection = self.prize_listbox.curselection()
        if selection:
            index = selection[0]
            prize = self.prizes.pop(index)
            self.update_prize_list()
            self.draw_wheel()
            self.status_var.set("🗑️ 已删除奖项: {}".format(prize))
        else:
            messagebox.showwarning("选择错误", "请选择一个奖项进行删除")
    
    def reset_prizes(self):
        """重置奖项为默认"""
        if messagebox.askyesno("重置确认", "确定要重置奖项为默认设置吗？"):
            self.prizes = self.default_prizes.copy()
            self.update_prize_list()
            self.draw_wheel()
            self.status_var.set("🔄 已重置奖项为默认设置")
    
    def save_prizes(self):
        """保存奖项设置"""
        try:
            with open('prizes.json', 'w', encoding='utf-8') as f:
                json.dump(self.prizes, f, ensure_ascii=False, indent=2)
            
            with open('history.json', 'w', encoding='utf-8') as f:
                json.dump(self.history, f, ensure_ascii=False, indent=2)
            
            self.status_var.set("💾 奖项和历史记录已保存")
        except Exception as e:
            messagebox.showerror("保存错误", f"保存失败: {str(e)}")
    
    def load_prizes(self):
        """加载奖项设置"""
        try:
            if os.path.exists('prizes.json'):
                with open('prizes.json', 'r', encoding='utf-8') as f:
                    self.prizes = json.load(f)
            
            if os.path.exists('history.json'):
                with open('history.json', 'r', encoding='utf-8') as f:
                    self.history = json.load(f)
            
            self.update_prize_list()
            self.update_history_display()
            self.draw_wheel()
        except:
            pass
    
    def load_prizes_dialog(self):
        """打开文件对话框加载奖项"""
        filename = filedialog.askopenfilename(
            title="选择奖项文件",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if filename:
            try:
                with open(filename, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                
                if isinstance(data, list):
                    self.prizes = data
                    self.update_prize_list()
                    self.draw_wheel()
                    self.status_var.set("📂 已从文件加载奖项")
                else:
                    messagebox.showerror("文件错误", "文件格式不正确")
            except Exception as e:
                messagebox.showerror("加载错误", f"加载失败: {str(e)}")
    
    def clear_history(self):
        """清空历史记录"""
        if messagebox.askyesno("清空确认", "确定要清空所有抽奖记录吗？"):
            self.history.clear()
            self.update_history_display()
            self.status_var.set("🗑️ 已清空所有抽奖记录")
    
    def export_history(self):
        """导出历史记录"""
        filename = filedialog.asksaveasfilename(
            title="保存历史记录",
            defaultextension=".txt",
            filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
        )
        
        if filename:
            try:
                with open(filename, 'w', encoding='utf-8') as f:
                    f.write("=== 幸运大转盘抽奖记录 ===\n")
                    f.write(f"导出时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                    f.write(f"总抽奖次数: {len(self.history)}\n")
                    f.write("=" * 40 + "\n\n")
                    
                    for i, record in enumerate(self.history, 1):
                        timestamp, participant, prize = record
                        f.write(f"第{i}次抽奖:\n")
                        f.write(f"  时间: {timestamp}\n")
                        f.write(f"  参与者: {participant}\n")
                        f.write(f"  奖项: {prize}\n")
                        f.write("-" * 30 + "\n")
                
                self.status_var.set("📤 历史记录已导出到: {}".format(filename))
                messagebox.showinfo("导出成功", "历史记录已成功导出！")
            except Exception as e:
                messagebox.showerror("导出错误", f"导出失败: {str(e)}")
    
    def start_spin(self):
        """开始抽奖"""
        if self.is_spinning:
            return
        
        if len(self.prizes) == 0:
            messagebox.showwarning("奖项错误", "请先添加至少一个奖项")
            return
        
        # 获取参与者姓名
        self.current_participant = self.participant_var.get().strip()
        if not self.current_participant:
            self.current_participant = "匿名参与者"
        
        # 初始化转盘参数
        self.is_spinning = True
        self.speed = random.uniform(20, 30)  # 随机初始速度
        
        # 开始动画
        self.animate_spin()
        
        # 更新结果显示
        self.result_var.set("转盘转动中...")
        self.status_var.set("🎰 {} 正在抽奖中...".format(self.current_participant))
    
    def stop_spin(self):
        """停止转盘"""
        if self.is_spinning and self.speed > 5:
            self.speed = 5  # 立即减速
    
    def reset_spin(self):
        """重置转盘"""
        self.is_spinning = False
        self.spin_angle = 0
        self.speed = 0
        self.draw_wheel()
        self.result_var.set("等待抽奖...")
        self.status_var.set("🔄 转盘已重置")
    
    def random_test(self):
        """随机测试抽奖"""
        test_names = ["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"]
        self.participant_var.set(random.choice(test_names))
        self.start_spin()
    
    def animate_spin(self):
        """转盘动画"""
        if not self.is_spinning:
            return
        
        # 更新角度
        self.spin_angle += self.speed
        
        # 减速
        if self.speed > self.min_speed:
            self.speed -= self.deceleration * 0.1
        else:
            self.speed = self.min_speed
        
        # 绘制转盘
        self.draw_wheel()
        
        # 旋转转盘
        self.wheel_canvas.delete("wheel_rotated")
        
        n = len(self.prizes)
        if n == 0:
            n = 1
        angle = 360 / n
        
        for i in range(n):
            # 计算旋转后的角度
            rotated_start_angle = i * angle + self.spin_angle
            rotated_end_angle = (i + 1) * angle + self.spin_angle
            
            start_rad = math.radians(rotated_start_angle)
            end_rad = math.radians(rotated_end_angle)
            
            # 绘制旋转后的扇形
            points = [self.center_x, self.center_y]
            
            x1 = self.center_x + self.wheel_radius * math.cos(start_rad)
            y1 = self.center_y + self.wheel_radius * math.sin(start_rad)
            points.extend([x1, y1])
            
            for a in range(int(rotated_start_angle), int(rotated_end_angle) + 1):
                rad = math.radians(a)
                x = self.center_x + self.wheel_radius * math.cos(rad)
                y = self.center_y + self.wheel_radius * math.sin(rad)
                points.extend([x, y])
            
            x2 = self.center_x + self.wheel_radius * math.cos(end_rad)
            y2 = self.center_y + self.wheel_radius * math.sin(end_rad)
            points.extend([x2, y2])
            points.extend([self.center_x, self.center_y])
            
            color = self.colors['wheel_bg'][i % len(self.colors['wheel_bg'])]
            self.wheel_canvas.create_polygon(
                points,
                fill=color,
                outline='white',
                width=2,
                tags="wheel_rotated"
            )
        
        # 检查是否停止
        if self.speed <= 0.1:
            self.is_spinning = False
            self.get_result()
        else:
            # 继续动画
            self.root.after(20, self.animate_spin)
    
    def get_result(self):
        """获取抽奖结果"""
        if len(self.prizes) == 0:
            return
        
        # 计算最终指向的奖项
        final_angle = self.spin_angle % 360
        n = len(self.prizes)
        sector_angle = 360 / n
        
        # 计算奖项索引（指针指向0度，需要调整）
        # 指针在顶部，所以需要加上180度偏移
        pointer_angle = (final_angle + 180) % 360
        prize_index = int(pointer_angle // sector_angle) % n
        
        # 获取奖项
        prize = self.prizes[prize_index]
        
        # 显示结果
        self.result_var.set("恭喜获得: {}".format(prize))
        
        # 记录历史
        timestamp = datetime.now().strftime("%H:%M:%S")
        self.history.append((timestamp, self.current_participant, prize))
        
        # 更新显示
        self.update_history_display()
        
        # 播放音效提示
        self.root.bell()
        
        # 显示恭喜信息
        messagebox.showinfo("🎉 恭喜中奖！", 
            f"🎉 恭喜 {self.current_participant}！\n\n"
            f"🏆 您获得了：{prize}\n\n"
            f"⏰ 抽奖时间：{timestamp}")
        
        self.status_var.set("🎉 {} 获得了: {}".format(self.current_participant, prize))

def main():
    root = tk.Tk()
    
    # 设置窗口居中
    window_width = 1000
    window_height = 700
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    center_x = int(screen_width/2 - window_width/2)
    center_y = int(screen_height/2 - window_height/2)
    root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
    
    # 设置样式
    style = ttk.Style()
    style.theme_use('clam')
    
    # 创建应用
    app = LuckyWheel(root)
    
    # 运行主循环
    root.mainloop()

if __name__ == "__main__":
    main()