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

class ModernLuckyWheel:
    def __init__(self, root):
        self.root = root
        self.root.title("🎰 幸运大转盘 - 豪华版")
        self.root.geometry("1000x750")
        self.root.resizable(False, False)
        
        # 设置窗口背景
        self.root.configure(bg='#1a1a2e')
        
        # 数据文件
        self.data_file = "wheel_data.json"
        
        # 初始化数据
        self.load_data()
        
        # 当前状态
        self.current_angle = 0
        self.is_spinning = False
        self.animation_id = None
        self.total_spins = 0
        self.win_count = {}
        
        # 创建界面
        self.create_widgets()
        
        # 绘制初始转盘
        self.draw_wheel()
        
        # 更新统计
        self.update_stats()
        
        # 绑定键盘事件
        self.root.bind('<space>', lambda e: self.spin())
        self.root.bind('<Return>', lambda e: self.spin())
        
    def load_data(self):
        """加载保存的数据"""
        default_data = {
            'prizes': [
                {'name': '一等奖 🏆', 'weight': 1, 'color': '#FF4757', 'icon': '🏆'},
                {'name': '二等奖 🎁', 'weight': 3, 'color': '#FF6B81', 'icon': '🎁'},
                {'name': '三等奖 🎈', 'weight': 5, 'color': '#2ED573', 'icon': '🎈'},
                {'name': '四等奖 🎀', 'weight': 8, 'color': '#1E90FF', 'icon': '🎀'},
                {'name': '五等奖 🎊', 'weight': 12, 'color': '#FFA502', 'icon': '🎊'},
                {'name': '谢谢参与 😊', 'weight': 30, 'color': '#A4B0BE', 'icon': '😊'},
                {'name': '再来一次 🔄', 'weight': 5, 'color': '#A29BFE', 'icon': '🔄'},
                {'name': '幸运奖 🍀', 'weight': 6, 'color': '#55EFC4', 'icon': '🍀'}
            ],
            'history': [],
            'total_spins': 0,
            'win_count': {}
        }
        
        if os.path.exists(self.data_file):
            try:
                with open(self.data_file, 'r', encoding='utf-8') as f:
                    data = json.load(f)
                    self.prizes = data.get('prizes', default_data['prizes'])
                    self.history = data.get('history', default_data['history'])
                    self.total_spins = data.get('total_spins', 0)
                    self.win_count = data.get('win_count', {})
            except:
                self.prizes = default_data['prizes']
                self.history = default_data['history']
                self.total_spins = 0
                self.win_count = {}
        else:
            self.prizes = default_data['prizes']
            self.history = default_data['history']
            self.total_spins = 0
            self.win_count = {}
            
        # 确保每个奖品都有颜色
        default_colors = ['#FF4757', '#FF6B81', '#2ED573', '#1E90FF', 
                         '#FFA502', '#A4B0BE', '#A29BFE', '#55EFC4']
        for i, prize in enumerate(self.prizes):
            if 'color' not in prize:
                prize['color'] = default_colors[i % len(default_colors)]
            if 'icon' not in prize:
                prize['icon'] = ''
    
    def save_data(self):
        """保存数据"""
        data = {
            'prizes': self.prizes,
            'history': self.history,
            'total_spins': self.total_spins,
            'win_count': self.win_count
        }
        with open(self.data_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
    
    def create_widgets(self):
        """创建界面组件"""
        # 主容器
        main_container = tk.Frame(self.root, bg='#1a1a2e')
        main_container.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 标题
        title_frame = tk.Frame(main_container, bg='#1a1a2e')
        title_frame.pack(fill='x', pady=(0, 20))
        
        title_label = tk.Label(
            title_frame,
            text="🎰 幸运大转盘",
            font=('微软雅黑', 28, 'bold'),
            bg='#1a1a2e',
            fg='#ffd700'
        )
        title_label.pack()
        
        subtitle_label = tk.Label(
            title_frame,
            text="按 空格键 或 回车键 快速抽奖",
            font=('微软雅黑', 10),
            bg='#1a1a2e',
            fg='#8892b0'
        )
        subtitle_label.pack()
        
        # 内容区域（左右布局）
        content_frame = tk.Frame(main_container, bg='#1a1a2e')
        content_frame.pack(fill='both', expand=True)
        
        # ===== 左侧：转盘区域 =====
        left_frame = tk.Frame(content_frame, bg='#1a1a2e')
        left_frame.pack(side='left', expand=True, fill='both')
        
        # 转盘容器
        wheel_container = tk.Frame(
            left_frame, 
            bg='#16213e',
            highlightthickness=2,
            highlightbackground='#ffd700',
            relief='ridge'
        )
        wheel_container.pack(pady=10)
        
        # 转盘画布
        self.canvas = tk.Canvas(
            wheel_container, 
            width=500, 
            height=500, 
            bg='#16213e',
            highlightthickness=0
        )
        self.canvas.pack()
        
        # 控制按钮区域
        control_frame = tk.Frame(left_frame, bg='#1a1a2e')
        control_frame.pack(pady=15)
        
        # 抽奖按钮
        self.spin_btn = tk.Button(
            control_frame,
            text="🎰 抽奖",
            command=self.spin,
            font=('微软雅黑', 20, 'bold'),
            bg='#e94560',
            fg='white',
            padx=50,
            pady=12,
            cursor='hand2',
            relief='raised',
            bd=0,
            activebackground='#c73652',
            activeforeground='white'
        )
        self.spin_btn.pack(side='left', padx=10)
        
        # 悬浮效果
        def on_enter(e):
            self.spin_btn.config(bg='#ff6b81')
        def on_leave(e):
            self.spin_btn.config(bg='#e94560')
        self.spin_btn.bind('<Enter>', on_enter)
        self.spin_btn.bind('<Leave>', on_leave)
        
        # 重置按钮
        reset_btn = tk.Button(
            control_frame,
            text="🔄 重置",
            command=self.reset_wheel,
            font=('微软雅黑', 14),
            bg='#0f3460',
            fg='white',
            padx=25,
            pady=12,
            cursor='hand2',
            relief='flat',
            activebackground='#1a4a7a'
        )
        reset_btn.pack(side='left', padx=10)
        
        # 结果显示
        self.result_frame = tk.Frame(left_frame, bg='#16213e', relief='ridge', bd=2)
        self.result_frame.pack(fill='x', pady=10)
        
        self.result_label = tk.Label(
            self.result_frame,
            text="✨ 点击「抽奖」或按空格键开始",
            font=('微软雅黑', 16, 'bold'),
            bg='#16213e',
            fg='#ffd700',
            pady=10
        )
        self.result_label.pack()
        
        # 统计信息
        stats_frame = tk.Frame(left_frame, bg='#1a1a2e')
        stats_frame.pack(fill='x', pady=5)
        
        self.stats_label = tk.Label(
            stats_frame,
            text="总抽奖：0次  |  中奖统计：无",
            font=('微软雅黑', 11),
            bg='#1a1a2e',
            fg='#8892b0'
        )
        self.stats_label.pack()
        
        # ===== 右侧：管理面板 =====
        right_frame = tk.Frame(
            content_frame, 
            bg='#16213e',
            width=300,
            relief='ridge',
            bd=2
        )
        right_frame.pack(side='right', fill='both', padx=(20, 0))
        right_frame.pack_propagate(False)
        
        # 面板标题
        panel_title = tk.Label(
            right_frame,
            text="⚙️ 奖品管理",
            font=('微软雅黑', 16, 'bold'),
            bg='#16213e',
            fg='#ffd700',
            pady=10
        )
        panel_title.pack()
        
        # 奖品列表
        list_container = tk.Frame(right_frame, bg='#16213e')
        list_container.pack(fill='both', expand=True, padx=10, pady=5)
        
        # 列表标题
        list_header = tk.Frame(list_container, bg='#16213e')
        list_header.pack(fill='x')
        tk.Label(list_header, text="奖品列表", font=('微软雅黑', 11, 'bold'),
                bg='#16213e', fg='#8892b0').pack(side='left')
        tk.Label(list_header, text=f"共 {len(self.prizes)} 项", font=('微软雅黑', 10),
                bg='#16213e', fg='#8892b0').pack(side='right')
        
        # 列表
        list_frame = tk.Frame(list_container, bg='#0f3460')
        list_frame.pack(fill='both', expand=True, pady=5)
        
        scrollbar = tk.Scrollbar(list_frame)
        scrollbar.pack(side='right', fill='y')
        
        self.prize_listbox = tk.Listbox(
            list_frame,
            yscrollcommand=scrollbar.set,
            font=('微软雅黑', 10),
            bg='#0f3460',
            fg='#ffffff',
            selectmode='single',
            height=10,
            selectbackground='#e94560',
            relief='flat'
        )
        self.prize_listbox.pack(side='left', fill='both', expand=True)
        scrollbar.config(command=self.prize_listbox.yview)
        
        # 更新列表
        self.update_prize_list()
        
        # 操作按钮
        btn_frame = tk.Frame(right_frame, bg='#16213e')
        btn_frame.pack(pady=10, fill='x', padx=10)
        
        # 第一行按钮
        btn_row1 = tk.Frame(btn_frame, bg='#16213e')
        btn_row1.pack(fill='x', pady=2)
        
        add_btn = self.create_style_button(
            btn_row1, "➕ 添加", self.add_prize, '#2ED573'
        )
        add_btn.pack(side='left', fill='x', expand=True, padx=2)
        
        edit_btn = self.create_style_button(
            btn_row1, "✏️ 编辑", self.edit_prize, '#1E90FF'
        )
        edit_btn.pack(side='left', fill='x', expand=True, padx=2)
        
        # 第二行按钮
        btn_row2 = tk.Frame(btn_frame, bg='#16213e')
        btn_row2.pack(fill='x', pady=2)
        
        del_btn = self.create_style_button(
            btn_row2, "🗑️ 删除", self.delete_prize, '#FF4757'
        )
        del_btn.pack(side='left', fill='x', expand=True, padx=2)
        
        clear_btn = self.create_style_button(
            btn_row2, "🧹 清空", self.clear_all_prizes, '#FF6B6B'
        )
        clear_btn.pack(side='left', fill='x', expand=True, padx=2)
        
        # 第三行按钮
        btn_row3 = tk.Frame(btn_frame, bg='#16213e')
        btn_row3.pack(fill='x', pady=2)
        
        history_btn = self.create_style_button(
            btn_row3, "📊 历史", self.show_history, '#A29BFE'
        )
        history_btn.pack(side='left', fill='x', expand=True, padx=2)
        
        export_btn = self.create_style_button(
            btn_row3, "💾 导出", self.export_data, '#FFA502'
        )
        export_btn.pack(side='left', fill='x', expand=True, padx=2)
        
        # 快速预设按钮
        preset_label = tk.Label(
            right_frame,
            text="快速预设",
            font=('微软雅黑', 10, 'bold'),
            bg='#16213e',
            fg='#8892b0'
        )
        preset_label.pack(pady=(10, 5))
        
        preset_frame = tk.Frame(right_frame, bg='#16213e')
        preset_frame.pack(fill='x', padx=10, pady=(0, 10))
        
        presets = [
            ("🎪 标准", self.load_standard_preset),
            ("🎯 大奖", self.load_big_prize_preset),
            ("🎭 娱乐", self.load_fun_preset)
        ]
        
        for text, command in presets:
            btn = tk.Button(
                preset_frame,
                text=text,
                command=command,
                font=('微软雅黑', 9),
                bg='#0f3460',
                fg='white',
                padx=10,
                pady=3,
                cursor='hand2',
                relief='flat'
            )
            btn.pack(side='left', fill='x', expand=True, padx=2)
    
    def create_style_button(self, parent, text, command, color):
        """创建统一样式的按钮"""
        btn = tk.Button(
            parent,
            text=text,
            command=command,
            font=('微软雅黑', 10, 'bold'),
            bg=color,
            fg='white',
            padx=10,
            pady=5,
            cursor='hand2',
            relief='flat'
        )
        return btn
    
    def update_prize_list(self):
        """更新奖品列表显示"""
        self.prize_listbox.delete(0, tk.END)
        for i, prize in enumerate(self.prizes):
            display_text = f"{prize.get('icon', '')} {prize['name']} (权重:{prize['weight']})"
            self.prize_listbox.insert(tk.END, display_text)
    
    def draw_wheel(self):
        """绘制转盘"""
        self.canvas.delete("all")
        
        center_x, center_y = 250, 250
        radius = 220
        n = len(self.prizes)
        
        if n == 0:
            self.canvas.create_text(
                center_x, center_y,
                text="请添加奖品",
                font=('微软雅黑', 24, 'bold'),
                fill='#8892b0'
            )
            return
        
        angle_step = 360 / n
        
        # 绘制外圈发光效果
        for i in range(3, 0, -1):
            glow_radius = radius + i * 2
            self.canvas.create_oval(
                center_x - glow_radius, center_y - glow_radius,
                center_x + glow_radius, center_y + glow_radius,
                outline='#ffd700' if i == 1 else '',
                width=0 if i > 1 else 3,
                fill=''
            )
        
        # 绘制扇形
        for i, prize in enumerate(self.prizes):
            start_angle = i * angle_step + self.current_angle
            end_angle = start_angle + angle_step
            
            # 绘制扇形
            self.canvas.create_arc(
                center_x - radius, center_y - radius,
                center_x + radius, center_y + radius,
                start=start_angle, extent=angle_step,
                fill=prize['color'],
                outline='white',
                width=2
            )
            
            # 添加文字
            mid_angle = math.radians(start_angle + angle_step / 2)
            text_x = center_x + (radius * 0.7) * math.cos(mid_angle)
            text_y = center_y + (radius * 0.7) * math.sin(mid_angle)
            
            # 文字方向
            text_angle = start_angle + angle_step / 2
            if text_angle > 90 and text_angle <= 270:
                text_angle += 180
            
            # 显示文字和图标
            text = prize.get('icon', '') + ' ' + prize['name']
            if len(text) > 8:
                text = text[:6] + '..'
            
            self.canvas.create_text(
                text_x, text_y,
                text=text,
                font=('微软雅黑', 11, 'bold'),
                angle=text_angle,
                fill='white'
            )
            
            # 添加权重小标签 - 使用白色半透明效果（通过设置较浅的颜色）
            weight_text = str(prize['weight'])
            weight_x = center_x + (radius * 0.4) * math.cos(mid_angle)
            weight_y = center_y + (radius * 0.4) * math.sin(mid_angle)
            self.canvas.create_text(
                weight_x, weight_y,
                text=weight_text,
                font=('微软雅黑', 8),
                fill='#cccccc'  # 使用浅灰色代替半透明白色
            )
        
        # 绘制中心装饰
        # 主圆
        self.canvas.create_oval(
            center_x - 40, center_y - 40,
            center_x + 40, center_y + 40,
            fill='#ffd700',
            outline='#ffa500',
            width=3
        )
        
        # 内圈
        self.canvas.create_oval(
            center_x - 28, center_y - 28,
            center_x + 28, center_y + 28,
            fill='#ffa500',
            outline='#ff8c00',
            width=2
        )
        
        # 中心文字
        self.canvas.create_text(
            center_x, center_y - 5,
            text="GO!",
            font=('Arial', 20, 'bold'),
            fill='#1a1a2e'
        )
        self.canvas.create_text(
            center_x, center_y + 18,
            text="抽奖",
            font=('微软雅黑', 10, 'bold'),
            fill='#1a1a2e'
        )
        
        # 绘制指针（固定在上方）
        pointer_points = [
            center_x, 15,
            center_x - 18, 40,
            center_x + 18, 40
        ]
        self.canvas.create_polygon(
            pointer_points,
            fill='#e94560',
            outline='#c73652',
            width=2
        )
        
        # 指针装饰圆
        self.canvas.create_oval(
            center_x - 8, 32,
            center_x + 8, 48,
            fill='#ffd700',
            outline='#ffa500',
            width=1
        )
        
        # 装饰小点
        for i in range(12):
            angle = i * 30
            x = center_x + (radius + 5) * math.cos(math.radians(angle))
            y = center_y + (radius + 5) * math.sin(math.radians(angle))
            self.canvas.create_oval(
                x - 3, y - 3,
                x + 3, y + 3,
                fill='#ffd700',
                outline=''
            )
    
    def spin(self):
        """执行抽奖"""
        if self.is_spinning:
            return
        
        if len(self.prizes) == 0:
            messagebox.showwarning("提示", "请先添加奖品！")
            return
        
        self.is_spinning = True
        self.spin_btn.config(state='disabled')
        self.result_label.config(text="🎡 转动中...", fg='#FF6B6B')
        
        # 加权随机选择
        weights = [p['weight'] for p in self.prizes]
        winner_index = random.choices(range(len(self.prizes)), weights=weights, k=1)[0]
        
        # 计算目标角度
        n = len(self.prizes)
        angle_step = 360 / n
        target_angle = 270 - (winner_index * angle_step + angle_step / 2)
        extra_spins = random.randint(5, 10) * 360
        total_rotation = extra_spins + target_angle - self.current_angle
        
        # 动画参数
        steps = 100
        angle_per_step = total_rotation / steps
        current_step = 0
        
        # 速度曲线（先快后慢）
        def ease_out(t):
            return 1 - (1 - t) ** 3
        
        def animate():
            nonlocal current_step
            if current_step < steps:
                progress = current_step / steps
                eased = ease_out(progress)
                current_angle_step = angle_per_step * (0.3 + 0.7 * (1 - eased))
                
                self.current_angle = (self.current_angle + current_angle_step) % 360
                self.draw_wheel()
                
                current_step += 1
                self.animation_id = self.root.after(20, animate)
            else:
                # 完成抽奖
                self.finish_spin(winner_index)
        
        animate()
    
    def finish_spin(self, winner_index):
        """完成抽奖"""
        winner = self.prizes[winner_index]
        
        # 特效：闪烁结果
        self.result_label.config(
            text=f"🎉 恭喜获得：{winner['name']}",
            fg='#2ED573'
        )
        
        # 更新统计
        self.total_spins += 1
        prize_name = winner['name']
        self.win_count[prize_name] = self.win_count.get(prize_name, 0) + 1
        
        # 记录历史
        record = {
            'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            'prize': prize_name,
            'icon': winner.get('icon', '')
        }
        self.history.append(record)
        self.save_data()
        
        # 更新统计显示
        self.update_stats()
        
        # 恢复按钮
        self.is_spinning = False
        self.spin_btn.config(state='normal')
        
        # 特殊处理：再来一次
        if "再来一次" in prize_name:
            self.root.after(1500, self.spin)
        elif "谢谢参与" in prize_name:
            self.result_label.config(fg='#A4B0BE')
    
    def update_stats(self):
        """更新统计信息"""
        total = self.total_spins
        if total == 0:
            stats_text = "总抽奖：0次  |  中奖统计：无"
        else:
            # 显示最常中奖的奖品
            if self.win_count:
                most_win = max(self.win_count.items(), key=lambda x: x[1])
                stats_text = f"总抽奖：{total}次  |  最常中奖：{most_win[0]} ({most_win[1]}次)"
            else:
                stats_text = f"总抽奖：{total}次"
        
        self.stats_label.config(text=stats_text)
    
    def reset_wheel(self):
        """重置转盘"""
        if self.is_spinning:
            return
        
        self.current_angle = 0
        self.draw_wheel()
        self.result_label.config(text="✨ 已重置", fg='#ffd700')
    
    def add_prize(self):
        """添加奖品"""
        self.create_prize_dialog("添加奖品", None)
    
    def edit_prize(self):
        """编辑奖品"""
        selection = self.prize_listbox.curselection()
        if not selection:
            messagebox.showwarning("提示", "请先选择一个奖品！")
            return
        
        index = selection[0]
        prize = self.prizes[index]
        self.create_prize_dialog("编辑奖品", (index, prize))
    
    def create_prize_dialog(self, title, data):
        """创建奖品编辑对话框"""
        dialog = tk.Toplevel(self.root)
        dialog.title(title)
        dialog.geometry("400x350")
        dialog.configure(bg='#16213e')
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 居中
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (400 // 2)
        y = (dialog.winfo_screenheight() // 2) - (350 // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 标题
        tk.Label(dialog, text=title, font=('微软雅黑', 16, 'bold'),
                bg='#16213e', fg='#ffd700').pack(pady=(20, 10))
        
        # 表单
        form_frame = tk.Frame(dialog, bg='#16213e')
        form_frame.pack(fill='both', expand=True, padx=30)
        
        # 名称
        tk.Label(form_frame, text="奖品名称：", font=('微软雅黑', 11),
                bg='#16213e', fg='white').pack(anchor='w', pady=(0, 5))
        name_entry = tk.Entry(form_frame, font=('微软雅黑', 11), bg='#0f3460',
                             fg='white', insertbackground='white')
        name_entry.pack(fill='x', pady=(0, 15))
        if data:
            name_entry.insert(0, data[1]['name'])
        
        # 图标
        tk.Label(form_frame, text="图标（Emoji）：", font=('微软雅黑', 11),
                bg='#16213e', fg='white').pack(anchor='w', pady=(0, 5))
        icon_entry = tk.Entry(form_frame, font=('微软雅黑', 11), bg='#0f3460',
                             fg='white', insertbackground='white')
        icon_entry.pack(fill='x', pady=(0, 15))
        if data and data[1].get('icon'):
            icon_entry.insert(0, data[1]['icon'])
        
        # 权重
        tk.Label(form_frame, text="权重（数字越大越容易中奖）：", 
                font=('微软雅黑', 11), bg='#16213e', fg='white').pack(anchor='w', pady=(0, 5))
        weight_entry = tk.Entry(form_frame, font=('微软雅黑', 11), bg='#0f3460',
                               fg='white', insertbackground='white')
        weight_entry.pack(fill='x', pady=(0, 15))
        if data:
            weight_entry.insert(0, str(data[1]['weight']))
        else:
            weight_entry.insert(0, "10")
        
        # 颜色选择
        color_frame = tk.Frame(form_frame, bg='#16213e')
        color_frame.pack(fill='x', pady=(0, 15))
        
        tk.Label(color_frame, text="颜色：", font=('微软雅黑', 11),
                bg='#16213e', fg='white').pack(side='left')
        
        color_var = tk.StringVar(value=data[1]['color'] if data else '#FF6B6B')
        color_preview = tk.Label(color_frame, bg=color_var.get(), 
                                 width=10, height=1, relief='ridge')
        color_preview.pack(side='left', padx=10)
        
        def choose_color():
            color = colorchooser.askcolor(title="选择颜色")[1]
            if color:
                color_var.set(color)
                color_preview.config(bg=color)
        
        tk.Button(color_frame, text="选择颜色", command=choose_color,
                 font=('微软雅黑', 10), bg='#0f3460', fg='white',
                 cursor='hand2').pack(side='left')
        
        # 确认按钮
        def confirm():
            name = name_entry.get().strip()
            if not name:
                messagebox.showerror("错误", "请输入奖品名称！")
                return
            
            try:
                weight = int(weight_entry.get())
                if weight <= 0:
                    raise ValueError
            except:
                messagebox.showerror("错误", "权重必须为正整数！")
                return
            
            icon = icon_entry.get().strip()
            prize_data = {
                'name': name,
                'weight': weight,
                'color': color_var.get(),
                'icon': icon
            }
            
            if data:
                # 编辑
                self.prizes[data[0]] = prize_data
                messagebox.showinfo("成功", "奖品已更新！")
            else:
                # 添加
                self.prizes.append(prize_data)
                messagebox.showinfo("成功", f"已添加奖品：{name}")
            
            self.save_data()
            self.update_prize_list()
            self.draw_wheel()
            dialog.destroy()
        
        btn_frame = tk.Frame(dialog, bg='#16213e')
        btn_frame.pack(pady=20)
        
        tk.Button(btn_frame, text="确认", command=confirm,
                 font=('微软雅黑', 12, 'bold'), bg='#2ED573',
                 fg='white', padx=30, pady=8, cursor='hand2',
                 relief='flat').pack(side='left', padx=5)
        
        tk.Button(btn_frame, text="取消", command=dialog.destroy,
                 font=('微软雅黑', 12), bg='#FF4757',
                 fg='white', padx=30, pady=8, cursor='hand2',
                 relief='flat').pack(side='left', padx=5)
    
    def delete_prize(self):
        """删除奖品"""
        selection = self.prize_listbox.curselection()
        if not selection:
            messagebox.showwarning("提示", "请先选择一个奖品！")
            return
        
        index = selection[0]
        prize_name = self.prizes[index]['name']
        
        if messagebox.askyesno("确认删除", f"确定要删除奖品「{prize_name}」吗？"):
            del self.prizes[index]
            self.save_data()
            self.update_prize_list()
            self.draw_wheel()
            messagebox.showinfo("成功", "奖品已删除！")
    
    def clear_all_prizes(self):
        """清空所有奖品"""
        if not self.prizes:
            messagebox.showinfo("提示", "没有奖品可删除")
            return
        
        if messagebox.askyesno("确认清空", "确定要删除所有奖品吗？"):
            self.prizes = []
            self.save_data()
            self.update_prize_list()
            self.draw_wheel()
            messagebox.showinfo("成功", "所有奖品已删除！")
    
    def show_history(self):
        """显示历史记录"""
        if not self.history:
            messagebox.showinfo("历史记录", "暂无抽奖记录")
            return
        
        # 创建历史窗口
        history_win = tk.Toplevel(self.root)
        history_win.title("📊 抽奖历史")
        history_win.geometry("600x500")
        history_win.configure(bg='#16213e')
        
        # 标题
        title_frame = tk.Frame(history_win, bg='#16213e')
        title_frame.pack(fill='x', padx=20, pady=10)
        
        tk.Label(title_frame, text="📊 抽奖历史记录", 
                font=('微软雅黑', 18, 'bold'),
                bg='#16213e', fg='#ffd700').pack(side='left')
        
        total = len(self.history)
        tk.Label(title_frame, text=f"总次数：{total}次",
                font=('微软雅黑', 12),
                bg='#16213e', fg='#8892b0').pack(side='right')
        
        # 统计信息
        stats_frame = tk.Frame(history_win, bg='#0f3460')
        stats_frame.pack(fill='x', padx=20, pady=(0, 10))
        
        # 计算中奖统计
        prize_stats = {}
        for record in self.history:
            prize = record['prize']
            prize_stats[prize] = prize_stats.get(prize, 0) + 1
        
        stats_text = " | ".join([f"{p}: {c}次" for p, c in sorted(prize_stats.items(), key=lambda x: x[1], reverse=True)[:5]])
        if stats_text:
            tk.Label(stats_frame, text=stats_text, font=('微软雅黑', 10),
                    bg='#0f3460', fg='#8892b0', pady=5).pack()
        
        # 列表框架
        list_frame = tk.Frame(history_win, bg='#0f3460')
        list_frame.pack(fill='both', expand=True, padx=20, pady=10)
        
        scrollbar = tk.Scrollbar(list_frame)
        scrollbar.pack(side='right', fill='y')
        
        history_list = tk.Listbox(
            list_frame,
            yscrollcommand=scrollbar.set,
            font=('微软雅黑', 10),
            bg='#0f3460',
            fg='#ffffff',
            selectmode='single',
            height=15
        )
        history_list.pack(side='left', fill='both', expand=True)
        scrollbar.config(command=history_list.yview)
        
        # 填充数据（最新的在前）
        for record in reversed(self.history):
            icon = record.get('icon', '')
            history_list.insert(tk.END, f"{record['time']}  {icon} {record['prize']}")
        
        # 关闭按钮
        btn_frame = tk.Frame(history_win, bg='#16213e')
        btn_frame.pack(pady=10)
        
        tk.Button(btn_frame, text="关闭", command=history_win.destroy,
                 font=('微软雅黑', 12), bg='#e94560',
                 fg='white', padx=40, pady=8, cursor='hand2',
                 relief='flat').pack()
    
    def export_data(self):
        """导出数据"""
        if not self.history:
            messagebox.showinfo("提示", "没有数据可导出")
            return
        
        file_path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")],
            title="导出数据"
        )
        
        if file_path:
            try:
                data = {
                    'prizes': self.prizes,
                    'history': self.history,
                    'total_spins': self.total_spins,
                    'win_count': self.win_count,
                    'export_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                }
                with open(file_path, 'w', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)
                messagebox.showinfo("成功", f"数据已导出到：{file_path}")
            except Exception as e:
                messagebox.showerror("错误", f"导出失败：{str(e)}")
    
    def load_standard_preset(self):
        """加载标准预设"""
        self.prizes = [
            {'name': '一等奖 🏆', 'weight': 1, 'color': '#FF4757', 'icon': '🏆'},
            {'name': '二等奖 🎁', 'weight': 3, 'color': '#FF6B81', 'icon': '🎁'},
            {'name': '三等奖 🎈', 'weight': 5, 'color': '#2ED573', 'icon': '🎈'},
            {'name': '四等奖 🎀', 'weight': 8, 'color': '#1E90FF', 'icon': '🎀'},
            {'name': '五等奖 🎊', 'weight': 12, 'color': '#FFA502', 'icon': '🎊'},
            {'name': '谢谢参与 😊', 'weight': 30, 'color': '#A4B0BE', 'icon': '😊'},
            {'name': '再来一次 🔄', 'weight': 5, 'color': '#A29BFE', 'icon': '🔄'},
            {'name': '幸运奖 🍀', 'weight': 6, 'color': '#55EFC4', 'icon': '🍀'}
        ]
        self.save_data()
        self.update_prize_list()
        self.draw_wheel()
        messagebox.showinfo("成功", "已加载标准预设！")
    
    def load_big_prize_preset(self):
        """加载大奖预设"""
        self.prizes = [
            {'name': '超级大奖 💎', 'weight': 1, 'color': '#FF0000', 'icon': '💎'},
            {'name': '一等奖 🏆', 'weight': 2, 'color': '#FF4757', 'icon': '🏆'},
            {'name': '二等奖 🎁', 'weight': 4, 'color': '#FF6B81', 'icon': '🎁'},
            {'name': '三等奖 🎈', 'weight': 6, 'color': '#2ED573', 'icon': '🎈'},
            {'name': '谢谢参与 😊', 'weight': 40, 'color': '#A4B0BE', 'icon': '😊'},
            {'name': '幸运奖 🍀', 'weight': 5, 'color': '#55EFC4', 'icon': '🍀'}
        ]
        self.save_data()
        self.update_prize_list()
        self.draw_wheel()
        messagebox.showinfo("成功", "已加载大奖预设！")
    
    def load_fun_preset(self):
        """加载娱乐预设"""
        self.prizes = [
            {'name': '免作业 ✅', 'weight': 5, 'color': '#2ED573', 'icon': '✅'},
            {'name': '看电影 🎬', 'weight': 8, 'color': '#1E90FF', 'icon': '🎬'},
            {'name': '吃大餐 🍕', 'weight': 10, 'color': '#FF6B81', 'icon': '🍕'},
            {'name': '玩游戏 🎮', 'weight': 12, 'color': '#A29BFE', 'icon': '🎮'},
            {'name': '唱歌 🎤', 'weight': 15, 'color': '#FFA502', 'icon': '🎤'},
            {'name': '做运动 💪', 'weight': 10, 'color': '#55EFC4', 'icon': '💪'},
            {'name': '继续努力 📚', 'weight': 20, 'color': '#A4B0BE', 'icon': '📚'}
        ]
        self.save_data()
        self.update_prize_list()
        self.draw_wheel()
        messagebox.showinfo("成功", "已加载娱乐预设！")

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

if __name__ == "__main__":
    main()