import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
import random
import json
import os
from datetime import datetime, timedelta
from typing import List, Dict, Tuple
import time

class Word:
    """单词类"""
    def __init__(self, english: str, chinese: str, example: str = "", 
                 difficulty: int = 0, last_review: datetime = None, 
                 next_review: datetime = None, correct_count: int = 0):
        self.english = english
        self.chinese = chinese
        self.example = example
        self.difficulty = difficulty  # 0:容易, 1:中等, 2:困难
        self.last_review = last_review or datetime.now()
        self.next_review = next_review or datetime.now()
        self.correct_count = correct_count
        self.wrong_count = 0
        self.mastery = 0  # 掌握程度 0-100
    
    def to_dict(self):
        """转换为字典"""
        return {
            'english': self.english,
            'chinese': self.chinese,
            'example': self.example,
            'difficulty': self.difficulty,
            'last_review': self.last_review.isoformat() if self.last_review else None,
            'next_review': self.next_review.isoformat() if self.next_review else None,
            'correct_count': self.correct_count,
            'wrong_count': self.wrong_count,
            'mastery': self.mastery
        }
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建"""
        word = cls(
            english=data['english'],
            chinese=data['chinese'],
            example=data.get('example', ''),
            difficulty=data.get('difficulty', 0)
        )
        word.last_review = datetime.fromisoformat(data['last_review']) if data.get('last_review') else datetime.now()
        word.next_review = datetime.fromisoformat(data['next_review']) if data.get('next_review') else datetime.now()
        word.correct_count = data.get('correct_count', 0)
        word.wrong_count = data.get('wrong_count', 0)
        word.mastery = data.get('mastery', 0)
        return word

class EnglishWordApp:
    def __init__(self, root):
        self.root = root
        self.root.title("📚 英语单词背诵助手 v2.0")
        
        # 窗口设置
        self.width = 1200
        self.height = 700
        self.root.geometry(f"{self.width}x{self.height}")
        self.root.configure(bg='#f0f8ff')
        
        # 单词库
        self.words: List[Word] = []
        self.current_word: Word = None
        self.review_list: List[Word] = []
        
        # 学习统计
        self.stats = {
            'total_words': 0,
            'reviewed_today': 0,
            'streak_days': 0,
            'total_reviews': 0,
            'accuracy': 0.0
        }
        
        # 默认单词库
        self.default_words = [
            ("hello", "你好", "Hello, how are you?"),
            ("world", "世界", "The world is beautiful."),
            ("apple", "苹果", "I eat an apple every day."),
            ("book", "书", "This is an interesting book."),
            ("computer", "电脑", "I use computer for work."),
            ("teacher", "老师", "Our teacher is very kind."),
            ("student", "学生", "He is a good student."),
            ("family", "家庭", "Family is important."),
            ("friend", "朋友", "She is my best friend."),
            ("school", "学校", "I go to school every day."),
            ("time", "时间", "Time is precious."),
            ("water", "水", "Please drink some water."),
            ("food", "食物", "Chinese food is delicious."),
            ("house", "房子", "They live in a big house."),
            ("car", "汽车", "My father drives a car."),
            ("city", "城市", "Shanghai is a big city."),
            ("country", "国家", "China is a beautiful country."),
            ("music", "音乐", "I love listening to music."),
            ("movie", "电影", "Let's watch a movie."),
            ("game", "游戏", "Children like playing games."),
            ("money", "钱", "Money is not everything."),
            ("work", "工作", "I go to work at 9 AM."),
            ("study", "学习", "I study English every day."),
            ("travel", "旅行", "I want to travel around the world."),
            ("dream", "梦想", "Follow your dreams."),
            ("love", "爱", "Love makes the world go round."),
            ("life", "生活", "Life is full of surprises."),
            ("sun", "太阳", "The sun is shining."),
            ("moon", "月亮", "The moon is beautiful tonight."),
            ("star", "星星", "Stars twinkle in the sky.")
        ]
        
        # 加载数据
        self.load_data()
        
        # 创建界面
        self.create_ui()
        
        # 启动每日提醒
        self.check_daily_review()
    
    def create_ui(self):
        """创建用户界面"""
        # 设置样式
        self.setup_styles()
        
        # 主框架
        main_frame = tk.Frame(self.root, bg='#f0f8ff')
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 标题栏
        self.create_header(main_frame)
        
        # 主内容区
        self.create_main_content(main_frame)
        
        # 状态栏
        self.create_statusbar(main_frame)
    
    def setup_styles(self):
        """设置样式"""
        style = ttk.Style()
        style.theme_use('clam')
    
    def create_header(self, parent):
        """创建标题栏"""
        header_frame = tk.Frame(parent, bg='#f0f8ff')
        header_frame.pack(fill=tk.X, pady=(0, 20))
        
        # 标题
        title_label = tk.Label(header_frame, text="📚 英语单词背诵助手", 
                              font=("Microsoft YaHei", 24, "bold"),
                              fg="#2c3e50", bg='#f0f8ff')
        title_label.pack(side=tk.LEFT)
        
        # 统计信息
        stats_frame = tk.Frame(header_frame, bg='#f0f8ff')
        stats_frame.pack(side=tk.RIGHT)
        
        self.stats_label = tk.Label(stats_frame, 
                                   text=f"单词数: {len(self.words)} | 今日复习: {self.stats['reviewed_today']}",
                                   font=("Microsoft YaHei", 10),
                                   fg="#7f8c8d", bg='#f0f8ff')
        self.stats_label.pack()
    
    def create_main_content(self, parent):
        """创建主内容区"""
        # 左侧面板
        left_panel = tk.Frame(parent, width=300, bg='#f0f8ff')
        left_panel.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))
        left_panel.pack_propagate(False)
        
        # 学习模式
        self.create_mode_panel(left_panel)
        
        # 单词管理
        self.create_word_management(left_panel)
        
        # 中间主面板
        main_panel = tk.Frame(parent, bg='#f0f8ff')
        main_panel.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # 单词显示区
        self.create_word_display(main_panel)
        
        # 右侧面板
        right_panel = tk.Frame(parent, width=300, bg='#f0f8ff')
        right_panel.pack(side=tk.RIGHT, fill=tk.Y, padx=(10, 0))
        right_panel.pack_propagate(False)
        
        # 进度统计
        self.create_progress_panel(right_panel)
        
        # 复习计划
        self.create_review_plan(right_panel)
    
    def create_mode_panel(self, parent):
        """创建学习模式面板"""
        mode_frame = tk.LabelFrame(parent, text="学习模式", 
                                  font=("Microsoft YaHei", 12, "bold"),
                                  bg='#f0f8ff', fg="#2c3e50",
                                  padx=10, pady=10)
        mode_frame.pack(fill=tk.X, pady=(0, 10))
        
        modes = [
            ("🎯 背单词", self.start_learning),
            ("🔄 复习", self.start_review),
            ("🎮 拼写测试", self.start_spelling),
            ("🎵 听力练习", self.start_listening),
            ("📊 模拟考试", self.start_exam)
        ]
        
        for name, command in modes:
            btn = tk.Button(mode_frame, text=name, command=command,
                          font=("Microsoft YaHei", 11),
                          bg="#3498db", fg="white",
                          relief=tk.RAISED, bd=2,
                          width=20, height=2)
            btn.pack(pady=5)
    
    def create_word_management(self, parent):
        """创建单词管理面板"""
        mgmt_frame = tk.LabelFrame(parent, text="单词管理", 
                                  font=("Microsoft YaHei", 12, "bold"),
                                  bg='#f0f8ff', fg="#2c3e50",
                                  padx=10, pady=10)
        mgmt_frame.pack(fill=tk.BOTH, expand=True)
        
        # 管理按钮
        mgmt_buttons = [
            ("➕ 添加单词", self.add_word),
            ("📋 导入单词", self.import_words),
            ("💾 导出单词", self.export_words),
            ("🗑️ 删除单词", self.delete_word),
            ("🔄 重置进度", self.reset_progress)
        ]
        
        for name, command in mgmt_buttons:
            btn = tk.Button(mgmt_frame, text=name, command=command,
                          font=("Microsoft YaHei", 10),
                          bg="#2ecc71", fg="white",
                          relief=tk.FLAT,
                          width=15)
            btn.pack(pady=5)
        
        # 单词列表
        list_frame = tk.Frame(mgmt_frame, bg='#f0f8ff')
        list_frame.pack(fill=tk.BOTH, expand=True, pady=(10, 0))
        
        tk.Label(list_frame, text="单词列表:", 
                font=("Microsoft YaHei", 10, "bold"),
                bg='#f0f8ff', fg="#34495e").pack(anchor=tk.W)
        
        self.word_listbox = tk.Listbox(list_frame, font=("Microsoft YaHei", 10),
                                      height=8, selectmode=tk.SINGLE)
        scrollbar = tk.Scrollbar(list_frame, orient=tk.VERTICAL)
        self.word_listbox.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.word_listbox.yview)
        
        self.word_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 更新单词列表
        self.update_word_list()
        
        # 绑定选择事件
        self.word_listbox.bind('<<ListboxSelect>>', self.on_word_selected)
    
    def create_word_display(self, parent):
        """创建单词显示区"""
        # 单词卡片
        card_frame = tk.LabelFrame(parent, text="单词卡片", 
                                  font=("Microsoft YaHei", 14, "bold"),
                                  bg='white', fg="#2c3e50",
                                  padx=20, pady=20)
        card_frame.pack(fill=tk.BOTH, expand=True)
        
        # 英文单词
        self.english_label = tk.Label(card_frame, text="", 
                                     font=("Arial", 48, "bold"),
                                     fg="#2c3e50", bg='white')
        self.english_label.pack(pady=20)
        
        # 音标
        self.phonetic_label = tk.Label(card_frame, text="", 
                                      font=("Arial", 20, "italic"),
                                      fg="#7f8c8d", bg='white')
        self.phonetic_label.pack(pady=5)
        
        # 中文释义
        self.chinese_label = tk.Label(card_frame, text="", 
                                     font=("Microsoft YaHei", 24),
                                     fg="#e74c3c", bg='white')
        self.chinese_label.pack(pady=20)
        
        # 例句
        self.example_label = tk.Label(card_frame, text="", 
                                     font=("Microsoft YaHei", 16),
                                     fg="#34495e", bg='white',
                                     wraplength=600, justify=tk.LEFT)
        self.example_label.pack(pady=20, padx=20)
        
        # 掌握程度
        self.mastery_frame = tk.Frame(card_frame, bg='white')
        self.mastery_frame.pack(pady=20)
        
        self.mastery_label = tk.Label(self.mastery_frame, text="掌握程度: ", 
                                     font=("Microsoft YaHei", 12),
                                     fg="#34495e", bg='white')
        self.mastery_label.pack(side=tk.LEFT)
        
        # 难度标签
        self.difficulty_label = tk.Label(card_frame, text="", 
                                        font=("Microsoft YaHei", 10),
                                        fg="#7f8c8d", bg='white')
        self.difficulty_label.pack(pady=5)
        
        # 控制按钮
        control_frame = tk.Frame(parent, bg='#f0f8ff')
        control_frame.pack(fill=tk.X, pady=20)
        
        # 学习控制
        self.control_buttons = []
        controls = [
            ("✅ 我会了", self.mark_correct, "#2ecc71"),
            ("❌ 忘记了", self.mark_wrong, "#e74c3c"),
            ("➡️ 下一个", self.next_word, "#3498db"),
            ("🔄 显示答案", self.show_answer, "#f39c12"),
            ("🔊 发音", self.speak_word, "#9b59b6")
        ]
        
        for name, command, color in controls:
            btn = tk.Button(control_frame, text=name, command=command,
                          font=("Microsoft YaHei", 12),
                          bg=color, fg="white",
                          relief=tk.RAISED, bd=2,
                          width=10, height=2)
            btn.pack(side=tk.LEFT, padx=5)
            self.control_buttons.append(btn)
        
        # 答案输入框（拼写模式）
        self.answer_frame = tk.Frame(parent, bg='#f0f8ff')
        self.answer_frame.pack(fill=tk.X, pady=10)
        
        self.answer_label = tk.Label(self.answer_frame, text="请输入英文:", 
                                    font=("Microsoft YaHei", 12),
                                    bg='#f0f8ff', fg="#34495e")
        self.answer_label.pack(side=tk.LEFT, padx=5)
        
        self.answer_var = tk.StringVar()
        self.answer_entry = tk.Entry(self.answer_frame, 
                                    textvariable=self.answer_var,
                                    font=("Arial", 16),
                                    width=30)
        self.answer_entry.pack(side=tk.LEFT, padx=5)
        
        self.check_button = tk.Button(self.answer_frame, text="检查答案", 
                                     command=self.check_spelling,
                                     font=("Microsoft YaHei", 12),
                                     bg="#3498db", fg="white")
        self.check_button.pack(side=tk.LEFT, padx=5)
        
        # 隐藏答案区域
        self.hide_answer_area()
    
    def create_progress_panel(self, parent):
        """创建进度统计面板"""
        progress_frame = tk.LabelFrame(parent, text="学习进度", 
                                      font=("Microsoft YaHei", 12, "bold"),
                                      bg='#f0f8ff', fg="#2c3e50",
                                      padx=10, pady=10)
        progress_frame.pack(fill=tk.X, pady=(0, 10))
        
        # 总单词数
        tk.Label(progress_frame, text=f"总单词数: {len(self.words)}", 
                font=("Microsoft YaHei", 10),
                bg='#f0f8ff', fg="#34495e").pack(anchor=tk.W, pady=2)
        
        # 今日复习
        tk.Label(progress_frame, text=f"今日复习: {self.stats['reviewed_today']}", 
                font=("Microsoft YaHei", 10),
                bg='#f0f8ff', fg="#34495e").pack(anchor=tk.W, pady=2)
        
        # 连续天数
        tk.Label(progress_frame, text=f"连续天数: {self.stats['streak_days']}", 
                font=("Microsoft YaHei", 10),
                bg='#f0f8ff', fg="#34495e").pack(anchor=tk.W, pady=2)
        
        # 正确率
        tk.Label(progress_frame, text=f"正确率: {self.stats['accuracy']:.1f}%", 
                font=("Microsoft YaHei", 10),
                bg='#f0f8ff', fg="#34495e").pack(anchor=tk.W, pady=2)
        
        # 掌握程度分布
        mastery_frame = tk.Frame(progress_frame, bg='#f0f8ff')
        mastery_frame.pack(fill=tk.X, pady=(10, 0))
        
        tk.Label(mastery_frame, text="掌握程度分布:", 
                font=("Microsoft YaHei", 10, "bold"),
                bg='#f0f8ff', fg="#34495e").pack(anchor=tk.W)
        
        # 计算掌握程度
        levels = {"生词": 0, "一般": 0, "熟悉": 0, "掌握": 0}
        for word in self.words:
            if word.mastery < 30:
                levels["生词"] += 1
            elif word.mastery < 60:
                levels["一般"] += 1
            elif word.mastery < 90:
                levels["熟悉"] += 1
            else:
                levels["掌握"] += 1
        
        for level, count in levels.items():
            tk.Label(mastery_frame, text=f"{level}: {count}", 
                    font=("Microsoft YaHei", 9),
                    bg='#f0f8ff', fg="#7f8c8d").pack(anchor=tk.W, pady=1)
    
    def create_review_plan(self, parent):
        """创建复习计划面板"""
        review_frame = tk.LabelFrame(parent, text="复习计划", 
                                    font=("Microsoft YaHei", 12, "bold"),
                                    bg='#f0f8ff', fg="#2c3e50",
                                    padx=10, pady=10)
        review_frame.pack(fill=tk.BOTH, expand=True)
        
        # 今日需要复习的单词
        today_review = self.get_today_review_words()
        
        tk.Label(review_frame, text=f"今日复习: {len(today_review)} 个单词", 
                font=("Microsoft YaHei", 10, "bold"),
                bg='#f0f8ff', fg="#e74c3c").pack(anchor=tk.W, pady=5)
        
        # 复习单词列表
        self.review_listbox = tk.Listbox(review_frame, font=("Microsoft YaHei", 9),
                                        height=8, selectmode=tk.SINGLE)
        scrollbar = tk.Scrollbar(review_frame, orient=tk.VERTICAL)
        self.review_listbox.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.review_listbox.yview)
        
        self.review_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 更新复习列表
        self.update_review_list()
    
    def create_statusbar(self, parent):
        """创建状态栏"""
        status_frame = tk.Frame(parent, bg='#ecf0f1', height=30)
        status_frame.pack(fill=tk.X, pady=(10, 0))
        status_frame.pack_propagate(False)
        
        self.status_label = tk.Label(status_frame, text="欢迎使用英语单词背诵助手！", 
                                    font=("Microsoft YaHei", 9),
                                    fg="#7f8c8d", bg='#ecf0f1')
        self.status_label.pack(side=tk.LEFT, padx=10)
    
    def update_word_list(self):
        """更新单词列表"""
        self.word_listbox.delete(0, tk.END)
        for word in self.words:
            mastery_icon = "🔴" if word.mastery < 30 else "🟡" if word.mastery < 60 else "🟢"
            self.word_listbox.insert(tk.END, f"{mastery_icon} {word.english} - {word.chinese}")
    
    def update_review_list(self):
        """更新复习列表"""
        self.review_listbox.delete(0, tk.END)
        today_review = self.get_today_review_words()
        for word in today_review:
            self.review_listbox.insert(tk.END, f"{word.english} - {word.chinese}")
    
    def update_progress(self):
        """更新进度统计"""
        self.stats['total_words'] = len(self.words)
        self.stats['reviewed_today'] = self.get_today_reviewed_count()
        
        # 更新标签
        self.stats_label.config(text=f"单词数: {len(self.words)} | 今日复习: {self.stats['reviewed_today']}")
    
    def on_word_selected(self, event):
        """单词列表选择事件"""
        selection = self.word_listbox.curselection()
        if selection:
            index = selection[0]
            if 0 <= index < len(self.words):
                self.show_word_detail(self.words[index])
    
    def show_word_detail(self, word):
        """显示单词详情"""
        self.current_word = word
        
        # 显示英文
        self.english_label.config(text=word.english)
        
        # 显示中文（初始隐藏）
        self.chinese_label.config(text="")
        
        # 显示例句
        if word.example:
            self.example_label.config(text=f"例句: {word.example}")
        else:
            self.example_label.config(text="")
        
        # 显示掌握程度
        mastery_color = "#e74c3c" if word.mastery < 30 else "#f39c12" if word.mastery < 60 else "#2ecc71"
        mastery_text = f"掌握程度: {word.mastery}%"
        self.mastery_label.config(text=mastery_text, fg=mastery_color)
        
        # 显示难度
        difficulty_text = ["容易", "中等", "困难"][word.difficulty]
        difficulty_color = ["#2ecc71", "#f39c12", "#e74c3c"][word.difficulty]
        self.difficulty_label.config(text=f"难度: {difficulty_text}", fg=difficulty_color)
        
        # 更新状态
        self.status_label.config(text=f"当前单词: {word.english}")
    
    def show_answer(self):
        """显示答案"""
        if self.current_word:
            self.chinese_label.config(text=self.current_word.chinese)
            self.status_label.config(text="已显示答案")
    
    def next_word(self):
        """下一个单词"""
        if not self.words:
            self.status_label.config(text="单词库为空，请先添加单词")
            return
        
        # 如果有复习列表，优先从复习列表中选择
        if self.review_list:
            word = random.choice(self.review_list)
        else:
            # 根据记忆曲线选择单词
            word = self.select_word_by_spaced_repetition()
        
        self.show_word_detail(word)
        self.hide_answer_area()
        self.answer_entry.delete(0, tk.END)
        self.status_label.config(text=f"新单词: {word.english}")
    
    def mark_correct(self):
        """标记为正确"""
        if self.current_word:
            self.current_word.correct_count += 1
            self.current_word.mastery = min(100, self.current_word.mastery + 10)
            self.current_word.last_review = datetime.now()
            
            # 更新下次复习时间（基于记忆曲线）
            interval = self.get_next_review_interval(self.current_word)
            self.current_word.next_review = datetime.now() + timedelta(days=interval)
            
            # 从复习列表中移除
            if self.current_word in self.review_list:
                self.review_list.remove(self.current_word)
            
            self.save_data()
            self.update_progress()
            self.update_review_list()
            self.status_label.config(text=f"✓ 正确！{self.current_word.english} 已掌握")
            
            # 自动下一个单词
            self.root.after(1000, self.next_word)
    
    def mark_wrong(self):
        """标记为错误"""
        if self.current_word:
            self.current_word.wrong_count += 1
            self.current_word.mastery = max(0, self.current_word.mastery - 5)
            
            # 添加到复习列表
            if self.current_word not in self.review_list:
                self.review_list.append(self.current_word)
            
            self.save_data()
            self.update_progress()
            self.update_review_list()
            self.status_label.config(text=f"✗ 错误！{self.current_word.english} 需要更多练习")
            
            # 显示答案
            self.show_answer()
    
    def get_next_review_interval(self, word):
        """获取下次复习间隔（基于SM-2算法简化版）"""
        if word.correct_count == 0:
            return 1  # 第一次正确，明天复习
        elif word.correct_count == 1:
            return 3  # 第二次正确，3天后复习
        elif word.correct_count == 2:
            return 7  # 第三次正确，7天后复习
        elif word.correct_count == 3:
            return 14  # 第4次正确，14天后复习
        else:
            return 30  # 后续，30天后复习
    
    def select_word_by_spaced_repetition(self):
        """根据记忆曲线选择单词"""
        now = datetime.now()
        
        # 1. 优先选择需要复习的单词
        due_words = [w for w in self.words if w.next_review <= now]
        if due_words:
            return random.choice(due_words)
        
        # 2. 选择掌握程度低的单词
        weak_words = [w for w in self.words if w.mastery < 50]
        if weak_words:
            return random.choice(weak_words)
        
        # 3. 随机选择
        return random.choice(self.words)
    
    def get_today_review_words(self):
        """获取今天需要复习的单词"""
        now = datetime.now()
        today_start = datetime(now.year, now.month, now.day)
        return [w for w in self.words if w.next_review <= now]
    
    def get_today_reviewed_count(self):
        """获取今日已复习单词数"""
        today = datetime.now().date()
        return sum(1 for w in self.words if w.last_review.date() == today)
    
    def start_learning(self):
        """开始学习模式"""
        self.status_label.config(text="学习模式：记忆新单词")
        self.next_word()
    
    def start_review(self):
        """开始复习模式"""
        self.review_list = self.get_today_review_words()
        if not self.review_list:
            self.status_label.config(text="今天没有需要复习的单词！")
            return
        
        self.status_label.config(text=f"复习模式：{len(self.review_list)} 个单词需要复习")
        self.next_word()
    
    def start_spelling(self):
        """开始拼写模式"""
        self.status_label.config(text="拼写模式：请拼写显示的单词")
        self.next_word()
        self.show_answer_area()
        self.chinese_label.config(text=self.current_word.chinese)
        self.english_label.config(text="")
    
    def show_answer_area(self):
        """显示答案输入区域"""
        self.answer_frame.pack(fill=tk.X, pady=10)
        self.answer_entry.focus()
    
    def hide_answer_area(self):
        """隐藏答案输入区域"""
        self.answer_frame.pack_forget()
    
    def check_spelling(self):
        """检查拼写"""
        if not self.current_word:
            return
        
        user_answer = self.answer_var.get().strip().lower()
        correct_answer = self.current_word.english.lower()
        
        if user_answer == correct_answer:
            messagebox.showinfo("正确！", f"✓ 拼写正确！\n{self.current_word.english}")
            self.mark_correct()
        else:
            messagebox.showinfo("错误！", f"✗ 拼写错误！\n正确答案: {self.current_word.english}")
            self.mark_wrong()
        
        self.answer_entry.delete(0, tk.END)
    
    def start_listening(self):
        """开始听力模式"""
        self.status_label.config(text="听力模式开发中...")
    
    def start_exam(self):
        """开始考试模式"""
        self.status_label.config(text="考试模式开发中...")
    
    def add_word(self):
        """添加单词"""
        dialog = AddWordDialog(self.root)
        if dialog.result:
            english, chinese, example = dialog.result
            word = Word(english, chinese, example)
            self.words.append(word)
            self.save_data()
            self.update_word_list()
            self.update_progress()
            self.status_label.config(text=f"已添加单词: {english}")
    
    def import_words(self):
        """导入单词"""
        # 添加默认单词
        for english, chinese, example in self.default_words:
            if not any(w.english == english for w in self.words):
                word = Word(english, chinese, example)
                self.words.append(word)
        
        self.save_data()
        self.update_word_list()
        self.update_progress()
        self.status_label.config(text=f"已导入 {len(self.default_words)} 个默认单词")
    
    def export_words(self):
        """导出单词"""
        try:
            with open("english_words.json", "w", encoding="utf-8") as f:
                data = [w.to_dict() for w in self.words]
                json.dump(data, f, ensure_ascii=False, indent=2)
            self.status_label.config(text="单词已导出到 english_words.json")
        except Exception as e:
            messagebox.showerror("错误", f"导出失败: {e}")
    
    def delete_word(self):
        """删除单词"""
        selection = self.word_listbox.curselection()
        if not selection:
            messagebox.showwarning("提示", "请先选择一个单词")
            return
        
        index = selection[0]
        if 0 <= index < len(self.words):
            word = self.words[index]
            if messagebox.askyesno("确认删除", f"确定要删除单词 '{word.english}' 吗？"):
                del self.words[index]
                self.save_data()
                self.update_word_list()
                self.update_progress()
                self.status_label.config(text=f"已删除单词: {word.english}")
    
    def reset_progress(self):
        """重置进度"""
        if messagebox.askyesno("确认重置", "确定要重置所有单词的学习进度吗？"):
            for word in self.words:
                word.correct_count = 0
                word.wrong_count = 0
                word.mastery = 0
                word.last_review = datetime.now()
                word.next_review = datetime.now()
            
            self.save_data()
            self.update_progress()
            self.status_label.config(text="已重置所有单词的学习进度")
    
    def speak_word(self):
        """发音（模拟）"""
        if self.current_word:
            self.status_label.config(text=f"发音: {self.current_word.english}")
    
    def check_daily_review(self):
        """检查每日复习"""
        today_review = len(self.get_today_review_words())
        if today_review > 0:
            self.status_label.config(text=f"今日有 {today_review} 个单词需要复习！")
    
    def load_data(self):
        """加载数据"""
        try:
            if os.path.exists("english_words.json"):
                with open("english_words.json", "r", encoding="utf-8") as f:
                    data = json.load(f)
                    self.words = [Word.from_dict(item) for item in data]
            else:
                # 加载默认单词
                for english, chinese, example in self.default_words:
                    self.words.append(Word(english, chinese, example))
        except:
            # 加载默认单词
            for english, chinese, example in self.default_words:
                self.words.append(Word(english, chinese, example))
    
    def save_data(self):
        """保存数据"""
        try:
            with open("english_words.json", "w", encoding="utf-8") as f:
                data = [w.to_dict() for w in self.words]
                json.dump(data, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存数据失败: {e}")

class AddWordDialog:
    """添加单词对话框"""
    def __init__(self, parent):
        self.parent = parent
        self.result = None
        
        self.dialog = tk.Toplevel(parent)
        self.dialog.title("添加单词")
        self.dialog.geometry("400x300")
        self.dialog.transient(parent)
        self.dialog.grab_set()
        
        # 居中显示
        x = parent.winfo_x() + (parent.winfo_width() - 400) // 2
        y = parent.winfo_y() + (parent.winfo_height() - 300) // 2
        self.dialog.geometry(f"400x300+{x}+{y}")
        
        # 创建表单
        self.create_form()
    
    def create_form(self):
        """创建表单"""
        tk.Label(self.dialog, text="英文单词:", 
                font=("Microsoft YaHei", 12)).pack(pady=10)
        
        self.english_var = tk.StringVar()
        tk.Entry(self.dialog, textvariable=self.english_var,
                font=("Arial", 16), width=30).pack()
        
        tk.Label(self.dialog, text="中文释义:", 
                font=("Microsoft YaHei", 12)).pack(pady=10)
        
        self.chinese_var = tk.StringVar()
        tk.Entry(self.dialog, textvariable=self.chinese_var,
                font=("Microsoft YaHei", 16), width=30).pack()
        
        tk.Label(self.dialog, text="例句 (可选):", 
                font=("Microsoft YaHei", 12)).pack(pady=10)
        
        self.example_var = tk.StringVar()
        tk.Entry(self.dialog, textvariable=self.example_var,
                font=("Microsoft YaHei", 12), width=40).pack()
        
        # 按钮
        btn_frame = tk.Frame(self.dialog)
        btn_frame.pack(pady=20)
        
        tk.Button(btn_frame, text="确定", command=self.save,
                 font=("Microsoft YaHei", 12), bg="#2ecc71", fg="white",
                 width=10).pack(side=tk.LEFT, padx=10)
        
        tk.Button(btn_frame, text="取消", command=self.dialog.destroy,
                 font=("Microsoft YaHei", 12), bg="#e74c3c", fg="white",
                 width=10).pack(side=tk.LEFT, padx=10)
    
    def save(self):
        """保存"""
        english = self.english_var.get().strip()
        chinese = self.chinese_var.get().strip()
        example = self.example_var.get().strip()
        
        if not english or not chinese:
            messagebox.showwarning("警告", "英文单词和中文释义不能为空！")
            return
        
        self.result = (english, chinese, example)
        self.dialog.destroy()

def main():
    """主函数"""
    root = tk.Tk()
    
    # 设置窗口居中
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    width = 1200
    height = 700
    x = (screen_width - width) // 2
    y = (screen_height - height) // 2
    root.geometry(f"{width}x{height}+{x}+{y}")
    
    app = EnglishWordApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()