import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
import json
import random
import time
from datetime import datetime, timedelta
import os
import sqlite3
from collections import defaultdict
import math

class EnglishVocabularyApp:
    def __init__(self, root):
        self.root = root
        self.root.title("英语单词背诵小程序 v2.0")
        self.root.geometry("1000x700")
        
        # 颜色方案
        self.colors = {
            'primary': '#2c3e50',
            'secondary': '#3498db',
            'success': '#2ecc71',
            'warning': '#f39c12',
            'danger': '#e74c3c',
            'light': '#ecf0f1',
            'dark': '#34495e',
            'info': '#3498db',
            'bg': '#f5f7fa'
        }
        
        # 数据库连接
        self.init_database()
        
        # 当前学习状态
        self.current_mode = 'learn'  # learn, test, review
        self.current_word = None
        self.current_index = 0
        self.test_results = []
        self.learning_words = []
        self.review_words = []
        self.total_words = 0
        self.correct_count = 0
        self.incorrect_count = 0
        
        # 用户设置
        self.settings = {
            'words_per_session': 20,
            'test_questions': 10,
            'difficulty': 'medium',
            'show_pronunciation': True,
            'auto_play_audio': False,
            'review_interval': 1,  # 天
            'theme': 'light'
        }
        
        # 加载设置
        self.load_settings()
        
        # 单词列表
        self.word_lists = {
            '初级': self.get_beginner_words(),
            '中级': self.get_intermediate_words(),
            '高级': self.get_advanced_words(),
            '四六级': self.get_cet_words(),
            '考研': self.get_kaoyan_words(),
            '托福': self.get_toefl_words(),
            '雅思': self.get_ielts_words(),
            'GRE': self.get_gre_words()
        }
        
        # 当前选择的单词列表
        self.current_word_list = '初级'
        
        # 创建UI
        self.setup_ui()
        
        # 加载学习进度
        self.load_progress()
        
        # 开始学习
        self.load_word_list()
        
    def init_database(self):
        """初始化数据库"""
        self.conn = sqlite3.connect('vocabulary.db')
        self.cursor = self.conn.cursor()
        
        # 创建用户进度表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS user_progress (
                word TEXT PRIMARY KEY,
                level INTEGER DEFAULT 0,
                last_reviewed TEXT,
                next_review TEXT,
                correct_count INTEGER DEFAULT 0,
                incorrect_count INTEGER DEFAULT 0,
                mastery_level INTEGER DEFAULT 0
            )
        ''')
        
        # 创建学习记录表
        self.cursor.execute('''
            CREATE TABLE IF NOT EXISTS study_records (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                date TEXT,
                mode TEXT,
                correct INTEGER,
                incorrect INTEGER,
                duration INTEGER
            )
        ''')
        
        self.conn.commit()
        
    def get_beginner_words(self):
        """获取初级单词"""
        return [
            {'word': 'apple', 'translation': '苹果', 'pronunciation': 'ˈæpl', 
             'example': 'I eat an apple every day.', 
             'example_translation': '我每天吃一个苹果。'},
            {'word': 'book', 'translation': '书', 'pronunciation': 'bʊk', 
             'example': 'I am reading an interesting book.', 
             'example_translation': '我正在读一本有趣的书。'},
            {'word': 'cat', 'translation': '猫', 'pronunciation': 'kæt', 
             'example': 'The cat is sleeping on the sofa.', 
             'example_translation': '猫正在沙发上睡觉。'},
            {'word': 'dog', 'translation': '狗', 'pronunciation': 'dɒɡ', 
             'example': 'My dog likes to play in the park.', 
             'example_translation': '我的狗喜欢在公园里玩。'},
            {'word': 'house', 'translation': '房子', 'pronunciation': 'haʊs', 
             'example': 'They live in a big house.', 
             'example_translation': '他们住在一所大房子里。'},
            {'word': 'water', 'translation': '水', 'pronunciation': 'ˈwɔːtə(r)', 
             'example': 'I drink eight glasses of water daily.', 
             'example_translation': '我每天喝八杯水。'},
            {'word': 'friend', 'translation': '朋友', 'pronunciation': 'frend', 
             'example': 'She is my best friend.', 
             'example_translation': '她是我最好的朋友。'},
            {'word': 'school', 'translation': '学校', 'pronunciation': 'skuːl', 
             'example': 'Children go to school to learn.', 
             'example_translation': '孩子们去学校学习。'},
            {'word': 'time', 'translation': '时间', 'pronunciation': 'taɪm', 
             'example': 'Time is very precious.', 
             'example_translation': '时间非常宝贵。'},
            {'word': 'work', 'translation': '工作', 'pronunciation': 'wɜːk', 
             'example': 'He goes to work at 9 AM.', 
             'example_translation': '他早上9点去上班。'},
        ]
        
    def get_intermediate_words(self):
        """获取中级单词"""
        return [
            {'word': 'abundant', 'translation': '丰富的，充足的', 'pronunciation': 'əˈbʌndənt', 
             'example': 'There is abundant evidence to support the theory.', 
             'example_translation': '有充足的证据支持这个理论。'},
            {'word': 'comprehend', 'translation': '理解，领会', 'pronunciation': 'ˌkɒmprɪˈhend', 
             'example': 'It is difficult to comprehend the complexity of the issue.', 
             'example_translation': '理解这个问题的复杂性很困难。'},
            {'word': 'diligent', 'translation': '勤奋的，刻苦的', 'pronunciation': 'ˈdɪlɪdʒənt', 
             'example': 'She is a diligent student who always finishes her homework on time.', 
             'example_translation': '她是个勤奋的学生，总是按时完成作业。'},
            {'word': 'eloquent', 'translation': '雄辩的，有口才的', 'pronunciation': 'ˈeləkwənt', 
             'example': 'The speaker gave an eloquent speech that moved the audience.', 
             'example_translation': '演讲者发表了雄辩的演讲，感动了观众。'},
            {'word': 'frugal', 'translation': '节俭的，朴素的', 'pronunciation': 'ˈfruːɡl', 
             'example': 'Despite being wealthy, he leads a frugal lifestyle.', 
             'example_translation': '尽管很富有，他过着节俭的生活。'},
        ]
        
    def get_advanced_words(self):
        """获取高级单词"""
        return [
            {'word': 'aberration', 'translation': '偏差，异常', 'pronunciation': 'ˌæbəˈreɪʃn', 
             'example': 'The sudden snowstorm in May was an aberration in the weather pattern.', 
             'example_translation': '五月突然的暴风雪是天气模式的一个异常。'},
            {'word': 'cacophony', 'translation': '刺耳的声音，不和谐音', 'pronunciation': 'kəˈkɒfəni', 
             'example': 'The cacophony of car horns during rush hour was deafening.', 
             'example_translation': '高峰时段汽车喇叭的刺耳声震耳欲聋。'},
            {'word': 'ephemeral', 'translation': '短暂的，瞬息的', 'pronunciation': 'ɪˈfemərəl', 
             'example': 'The beauty of cherry blossoms is ephemeral.', 
             'example_translation': '樱花之美是短暂的。'},
            {'word': 'lucid', 'translation': '清晰的，易懂的', 'pronunciation': 'ˈluːsɪd', 
             'example': 'Her explanation was lucid and easy to understand.', 
             'example_translation': '她的解释清晰易懂。'},
            {'word': 'quintessential', 'translation': '典型的，精髓的', 'pronunciation': 'ˌkwɪntɪˈsenʃl', 
             'example': 'This painting is the quintessential example of Renaissance art.', 
             'example_translation': '这幅画是文艺复兴艺术的典型例子。'},
        ]
        
    def get_cet_words(self):
        """获取四六级单词"""
        return [
            {'word': 'accommodate', 'translation': '容纳，适应', 'pronunciation': 'əˈkɒmədeɪt', 
             'example': 'The hotel can accommodate up to 500 guests.', 
             'example_translation': '这家酒店最多可容纳500位客人。'},
            {'word': 'beneficial', 'translation': '有益的，有利的', 'pronunciation': 'ˌbenɪˈfɪʃl', 
             'example': 'Regular exercise is beneficial to health.', 
             'example_translation': '定期锻炼对健康有益。'},
            {'word': 'controversial', 'translation': '有争议的', 'pronunciation': 'ˌkɒntrəˈvɜːʃl', 
             'example': 'It is a controversial issue that divides public opinion.', 
             'example_translation': '这是一个引起公众意见分歧的有争议的问题。'},
            {'word': 'dilemma', 'translation': '困境，进退两难', 'pronunciation': 'dɪˈlemə', 
             'example': 'She faced the dilemma of choosing between career and family.', 
             'example_translation': '她面临着在事业和家庭之间做出选择的困境。'},
            {'word': 'essential', 'translation': '必要的，基本的', 'pronunciation': 'ɪˈsenʃl', 
             'example': 'Water is essential for all living things.', 
             'example_translation': '水对所有生物都是必不可少的。'},
        ]
        
    def get_kaoyan_words(self):
        """获取考研单词"""
        return [
            {'word': 'alleviate', 'translation': '减轻，缓解', 'pronunciation': 'əˈliːvieɪt', 
             'example': 'The medicine helps to alleviate the pain.', 
             'example_translation': '这种药有助于缓解疼痛。'},
            {'word': 'conspicuous', 'translation': '明显的，显著的', 'pronunciation': 'kənˈspɪkjuəs', 
             'example': 'There was a conspicuous lack of evidence.', 
             'example_translation': '明显缺乏证据。'},
            {'word': 'elaborate', 'translation': '详尽的，复杂的', 'pronunciation': 'ɪˈlæbərət', 
             'example': 'They made elaborate preparations for the party.', 
             'example_translation': '他们为聚会做了精心的准备。'},
            {'word': 'feasible', 'translation': '可行的，可能的', 'pronunciation': 'ˈfiːzəbl', 
             'example': 'The plan sounds feasible in theory.', 
             'example_translation': '这个计划理论上听起来可行。'},
            {'word': 'hypothesis', 'translation': '假设，假说', 'pronunciation': 'haɪˈpɒθəsɪs', 
             'example': 'The researcher proposed a new hypothesis.', 
             'example_translation': '研究人员提出了一个新的假设。'},
        ]
        
    def get_toefl_words(self):
        """获取托福单词"""
        return [
            {'word': 'ambiguous', 'translation': '模糊的，不明确的', 'pronunciation': 'æmˈbɪɡjuəs', 
             'example': 'His answer was ambiguous and confusing.', 
             'example_translation': '他的回答含糊不清，令人困惑。'},
            {'word': 'comprehensive', 'translation': '全面的，综合的', 'pronunciation': 'ˌkɒmprɪˈhensɪv', 
             'example': 'The report provides a comprehensive analysis of the market.', 
             'example_translation': '该报告提供了对市场的全面分析。'},
            {'word': 'diverse', 'translation': '多样的，不同的', 'pronunciation': 'daɪˈvɜːs', 
             'example': 'The city has a diverse population.', 
             'example_translation': '这个城市人口多样化。'},
            {'word': 'exemplify', 'translation': '例证，举例说明', 'pronunciation': 'ɪɡˈzemplɪfaɪ', 
             'example': 'This case exemplifies the need for reform.', 
             'example_translation': '这个案例说明了改革的必要性。'},
            {'word': 'impartial', 'translation': '公正的，不偏不倚的', 'pronunciation': 'ɪmˈpɑːʃl', 
             'example': 'The judge must remain impartial throughout the trial.', 
             'example_translation': '法官在整个审判过程中必须保持公正。'},
        ]
        
    def get_ielts_words(self):
        """获取雅思单词"""
        return [
            {'word': 'adequate', 'translation': '足够的，适当的', 'pronunciation': 'ˈædɪkwət', 
             'example': 'The food supply is adequate for the winter.', 
             'example_translation': '食物供应足够过冬。'},
            {'word': 'consequence', 'translation': '结果，后果', 'pronunciation': 'ˈkɒnsɪkwəns', 
             'example': 'His actions had serious consequences.', 
             'example_translation': '他的行为产生了严重的后果。'},
            {'word': 'eradicate', 'translation': '根除，消灭', 'pronunciation': 'ɪˈrædɪkeɪt', 
             'example': 'Efforts to eradicate poverty continue.', 
             'example_translation': '消除贫困的努力仍在继续。'},
            {'word': 'facilitate', 'translation': '促进，使容易', 'pronunciation': 'fəˈsɪlɪteɪt', 
             'example': 'The new software will facilitate data analysis.', 
             'example_translation': '新软件将促进数据分析。'},
            {'word': 'innovative', 'translation': '创新的，革新的', 'pronunciation': 'ˈɪnəveɪtɪv', 
             'example': 'The company is known for its innovative products.', 
             'example_translation': '这家公司以其创新产品而闻名。'},
        ]
        
    def get_gre_words(self):
        """获取GRE单词"""
        return [
            {'word': 'abstruse', 'translation': '深奥的，难解的', 'pronunciation': 'əbˈstruːs', 
             'example': 'The professor gave an abstruse lecture on quantum physics.', 
             'example_translation': '教授做了一场关于量子物理的深奥讲座。'},
            {'word': 'capricious', 'translation': '变幻无常的，任性的', 'pronunciation': 'kəˈprɪʃəs', 
             'example': 'The weather in spring is often capricious.', 
             'example_translation': '春天的天气常常变幻无常。'},
            {'word': 'esoteric', 'translation': '深奥的，只有内行才懂的', 'pronunciation': 'ˌesəˈterɪk', 
             'example': 'The book deals with esoteric philosophical concepts.', 
             'example_translation': '这本书涉及深奥的哲学概念。'},
            {'word': 'garrulous', 'translation': '饶舌的，多话的', 'pronunciation': 'ˈɡærələs', 
             'example': 'The garrulous old man talked for hours.', 
             'example_translation': '那个饶舌的老人讲了几个小时。'},
            {'word': 'obfuscate', 'translation': '使困惑，使模糊', 'pronunciation': 'ˈɒbfəskeɪt', 
             'example': 'The politician tried to obfuscate the issue.', 
             'example_translation': '这位政治家试图混淆这个问题。'},
        ]
        
    def setup_ui(self):
        """设置用户界面"""
        # 主框架
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 顶部工具栏
        self.setup_toolbar(main_frame)
        
        # 左侧导航栏
        self.setup_sidebar(main_frame)
        
        # 右侧主内容区域
        self.setup_main_content(main_frame)
        
        # 底部状态栏
        self.setup_statusbar()
        
    def setup_toolbar(self, parent):
        """设置工具栏"""
        toolbar = ttk.Frame(parent)
        toolbar.pack(fill=tk.X, pady=(0, 10))
        
        # 应用标题
        title_label = tk.Label(toolbar, text="📚 英语单词背诵小程序", 
                               font=('Microsoft YaHei', 18, 'bold'),
                               fg=self.colors['primary'])
        title_label.pack(side=tk.LEFT)
        
        # 学习进度
        self.progress_label = tk.Label(toolbar, text="", font=('Microsoft YaHei', 10))
        self.progress_label.pack(side=tk.RIGHT, padx=10)
        
    def setup_sidebar(self, parent):
        """设置侧边栏"""
        sidebar = ttk.Frame(parent, width=200)
        sidebar.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))
        sidebar.pack_propagate(False)
        
        # 学习模式按钮
        ttk.Label(sidebar, text="学习模式", font=('Microsoft YaHei', 12, 'bold')).pack(anchor='w', pady=(0, 5))
        
        self.mode_var = tk.StringVar(value='learn')
        
        modes = [
            ("📖 学习模式", "learn"),
            ("📝 测试模式", "test"),
            ("🔄 复习模式", "review"),
            ("📊 进度统计", "stats")
        ]
        
        for text, value in modes:
            btn = ttk.Radiobutton(sidebar, text=text, value=value, 
                                 variable=self.mode_var, 
                                 command=self.change_mode)
            btn.pack(fill=tk.X, pady=2)
            
        ttk.Separator(sidebar, orient='horizontal').pack(fill=tk.X, pady=10)
        
        # 单词列表选择
        ttk.Label(sidebar, text="单词列表", font=('Microsoft YaHei', 12, 'bold')).pack(anchor='w', pady=(0, 5))
        
        self.list_var = tk.StringVar(value=self.current_word_list)
        for list_name in self.word_lists.keys():
            btn = ttk.Radiobutton(sidebar, text=list_name, value=list_name, 
                                 variable=self.list_var, 
                                 command=self.change_word_list)
            btn.pack(fill=tk.X, pady=2)
            
        ttk.Separator(sidebar, orient='horizontal').pack(fill=tk.X, pady=10)
        
        # 设置按钮
        ttk.Button(sidebar, text="⚙️ 设置", command=self.open_settings).pack(fill=tk.X, pady=2)
        ttk.Button(sidebar, text="💾 导出进度", command=self.export_progress).pack(fill=tk.X, pady=2)
        ttk.Button(sidebar, text="❓ 帮助", command=self.show_help).pack(fill=tk.X, pady=2)
        
    def setup_main_content(self, parent):
        """设置主内容区域"""
        self.main_content = ttk.Frame(parent)
        self.main_content.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # 学习模式内容
        self.setup_learn_mode()
        
        # 测试模式内容
        self.setup_test_mode()
        
        # 复习模式内容
        self.setup_review_mode()
        
        # 统计模式内容
        self.setup_stats_mode()
        
    def setup_learn_mode(self):
        """设置学习模式内容"""
        self.learn_frame = ttk.Frame(self.main_content)
        
        # 单词显示区域
        word_frame = ttk.LabelFrame(self.learn_frame, text="当前单词", padding=20)
        word_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
        
        # 英语单词
        self.word_label = tk.Label(word_frame, text="", 
                                   font=('Arial', 48, 'bold'),
                                   fg=self.colors['primary'])
        self.word_label.pack(pady=(0, 10))
        
        # 音标
        self.pronunciation_label = tk.Label(word_frame, text="", 
                                           font=('Arial', 20),
                                           fg=self.colors['secondary'])
        self.pronunciation_label.pack(pady=(0, 20))
        
        # 显示中文按钮
        show_translation_btn = ttk.Button(word_frame, text="显示中文释义", 
                                         command=self.show_translation)
        show_translation_btn.pack(pady=(0, 20))
        
        # 中文释义（初始隐藏）
        self.translation_frame = ttk.Frame(word_frame)
        self.translation_frame.pack(fill=tk.X, pady=(0, 20))
        
        self.translation_label = tk.Label(self.translation_frame, text="", 
                                         font=('Microsoft YaHei', 20, 'bold'),
                                         fg=self.colors['success'], 
                                         wraplength=600, justify='center')
        self.translation_label.pack()
        
        # 例句
        self.example_frame = ttk.Frame(word_frame)
        self.example_frame.pack(fill=tk.X, pady=(0, 20))
        
        ttk.Label(self.example_frame, text="例句:", font=('Microsoft YaHei', 12, 'bold')).pack(anchor='w')
        self.example_label = tk.Label(self.example_frame, text="", 
                                     font=('Arial', 12, 'italic'),
                                     wraplength=600, justify='left')
        self.example_label.pack(anchor='w', pady=(5, 0))
        
        ttk.Label(self.example_frame, text="翻译:", font=('Microsoft YaHei', 12, 'bold')).pack(anchor='w', pady=(10, 0))
        self.example_translation_label = tk.Label(self.example_frame, text="", 
                                                 font=('Microsoft YaHei', 12),
                                                 wraplength=600, justify='left')
        self.example_translation_label.pack(anchor='w', pady=(5, 0))
        
        # 学习控制按钮
        control_frame = ttk.Frame(self.learn_frame)
        control_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Button(control_frame, text="认识", command=lambda: self.mark_word('known')).pack(side=tk.LEFT, padx=5)
        ttk.Button(control_frame, text="模糊", command=lambda: self.mark_word('vague')).pack(side=tk.LEFT, padx=5)
        ttk.Button(control_frame, text="不认识", command=lambda: self.mark_word('unknown')).pack(side=tk.LEFT, padx=5)
        
        # 导航按钮
        nav_frame = ttk.Frame(self.learn_frame)
        nav_frame.pack(fill=tk.X)
        
        ttk.Button(nav_frame, text="上一个", command=self.prev_word).pack(side=tk.LEFT, padx=5)
        ttk.Button(nav_frame, text="下一个", command=self.next_word).pack(side=tk.LEFT, padx=5)
        ttk.Button(nav_frame, text="随机", command=self.random_word).pack(side=tk.LEFT, padx=5)
        
    def setup_test_mode(self):
        """设置测试模式内容"""
        self.test_frame = ttk.Frame(self.main_content)
        
        # 测试状态显示
        test_status_frame = ttk.Frame(self.test_frame)
        test_status_frame.pack(fill=tk.X, pady=(0, 20))
        
        self.test_progress_label = tk.Label(test_status_frame, text="", font=('Microsoft YaHei', 12))
        self.test_progress_label.pack(side=tk.LEFT)
        
        self.test_score_label = tk.Label(test_status_frame, text="", font=('Microsoft YaHei', 12))
        self.test_score_label.pack(side=tk.RIGHT)
        
        # 测试问题区域
        test_question_frame = ttk.LabelFrame(self.test_frame, text="测试题目", padding=20)
        test_question_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
        
        self.test_question_label = tk.Label(test_question_frame, text="", 
                                           font=('Microsoft YaHei', 16),
                                           wraplength=600, justify='center')
        self.test_question_label.pack(pady=(0, 30))
        
        # 选项区域
        self.test_options_frame = ttk.Frame(test_question_frame)
        self.test_options_frame.pack(fill=tk.X)
        
        self.test_option_vars = []
        self.test_option_buttons = []
        
        for i in range(4):
            var = tk.StringVar()
            btn = ttk.Radiobutton(self.test_options_frame, text="", variable=var, 
                                 value=str(i), style='TRadiobutton')
            btn.pack(fill=tk.X, pady=5)
            self.test_option_vars.append(var)
            self.test_option_buttons.append(btn)
            
        # 测试控制按钮
        test_control_frame = ttk.Frame(self.test_frame)
        test_control_frame.pack(fill=tk.X)
        
        ttk.Button(test_control_frame, text="开始测试", command=self.start_test).pack(side=tk.LEFT, padx=5)
        ttk.Button(test_control_frame, text="提交答案", command=self.submit_test_answer).pack(side=tk.LEFT, padx=5)
        ttk.Button(test_control_frame, text="结束测试", command=self.end_test).pack(side=tk.LEFT, padx=5)
        
    def setup_review_mode(self):
        """设置复习模式内容"""
        self.review_frame = ttk.Frame(self.main_content)
        
        # 复习列表
        review_list_frame = ttk.LabelFrame(self.review_frame, text="需要复习的单词", padding=10)
        review_list_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
        
        # 创建Treeview
        columns = ('word', 'translation', 'next_review', 'mastery')
        self.review_tree = ttk.Treeview(review_list_frame, columns=columns, show='headings', height=15)
        
        # 设置列
        self.review_tree.heading('word', text='单词')
        self.review_tree.heading('translation', text='释义')
        self.review_tree.heading('next_review', text='下次复习')
        self.review_tree.heading('mastery', text='掌握度')
        
        # 设置列宽
        self.review_tree.column('word', width=150)
        self.review_tree.column('translation', width=200)
        self.review_tree.column('next_review', width=150)
        self.review_tree.column('mastery', width=100)
        
        # 滚动条
        scrollbar = ttk.Scrollbar(review_list_frame, orient=tk.VERTICAL, command=self.review_tree.yview)
        self.review_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.review_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 控制按钮
        review_control_frame = ttk.Frame(self.review_frame)
        review_control_frame.pack(fill=tk.X)
        
        ttk.Button(review_control_frame, text="刷新列表", command=self.refresh_review_list).pack(side=tk.LEFT, padx=5)
        ttk.Button(review_control_frame, text="开始复习", command=self.start_review).pack(side=tk.LEFT, padx=5)
        ttk.Button(review_control_frame, text="标记为已掌握", command=self.mark_as_mastered).pack(side=tk.LEFT, padx=5)
        
    def setup_stats_mode(self):
        """设置统计模式内容"""
        self.stats_frame = ttk.Frame(self.main_content)
        
        # 统计信息显示
        stats_display_frame = ttk.Frame(self.stats_frame)
        stats_display_frame.pack(fill=tk.BOTH, expand=True, pady=20)
        
        # 创建统计卡片
        stats_cards = [
            ("总学习单词数", "total_words", "📊"),
            ("已掌握单词数", "mastered_words", "✅"),
            ("需要复习单词数", "review_words_count", "🔄"),
            ("学习时长", "study_time", "⏱️"),
            ("正确率", "accuracy_rate", "🎯"),
            ("连续学习天数", "streak_days", "🔥")
        ]
        
        for i, (title, key, icon) in enumerate(stats_cards):
            card = ttk.Frame(stats_display_frame)
            card.grid(row=i//3, column=i%3, padx=10, pady=10, sticky='nsew')
            
            # 设置网格权重
            stats_display_frame.grid_columnconfigure(i%3, weight=1)
            stats_display_frame.grid_rowconfigure(i//3, weight=1)
            
            # 图标
            icon_label = tk.Label(card, text=icon, font=('Arial', 24))
            icon_label.pack(pady=(10, 5))
            
            # 标题
            title_label = tk.Label(card, text=title, font=('Microsoft YaHei', 10))
            title_label.pack()
            
            # 数值
            value_label = tk.Label(card, text="0", font=('Arial', 20, 'bold'), fg=self.colors['primary'])
            value_label.pack(pady=(5, 10))
            
            # 保存引用
            setattr(self, f"{key}_label", value_label)
            
        # 学习记录表格
        ttk.Label(self.stats_frame, text="学习记录", font=('Microsoft YaHei', 12, 'bold')).pack(anchor='w', pady=(20, 5))
        
        # 创建Treeview
        columns = ('date', 'mode', 'correct', 'incorrect', 'duration')
        self.stats_tree = ttk.Treeview(self.stats_frame, columns=columns, show='headings', height=8)
        
        # 设置列
        self.stats_tree.heading('date', text='日期')
        self.stats_tree.heading('mode', text='模式')
        self.stats_tree.heading('correct', text='正确数')
        self.stats_tree.heading('incorrect', text='错误数')
        self.stats_tree.heading('duration', text='时长(秒)')
        
        # 滚动条
        scrollbar = ttk.Scrollbar(self.stats_frame, orient=tk.VERTICAL, command=self.stats_tree.yview)
        self.stats_tree.configure(yscrollcommand=scrollbar.set)
        
        # 布局
        self.stats_tree.pack(fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
    def setup_statusbar(self):
        """设置状态栏"""
        self.status_var = tk.StringVar(value="就绪")
        statusbar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W)
        statusbar.pack(side=tk.BOTTOM, fill=tk.X)
        
    def change_mode(self):
        """切换模式"""
        mode = self.mode_var.get()
        self.current_mode = mode
        
        # 隐藏所有内容框架
        for frame in [self.learn_frame, self.test_frame, self.review_frame, self.stats_frame]:
            frame.pack_forget()
            
        # 显示当前模式的内容框架
        if mode == 'learn':
            self.learn_frame.pack(fill=tk.BOTH, expand=True)
            self.load_learning_word()
        elif mode == 'test':
            self.test_frame.pack(fill=tk.BOTH, expand=True)
            self.update_test_display()
        elif mode == 'review':
            self.review_frame.pack(fill=tk.BOTH, expand=True)
            self.refresh_review_list()
        elif mode == 'stats':
            self.stats_frame.pack(fill=tk.BOTH, expand=True)
            self.update_stats()
            
    def change_word_list(self):
        """切换单词列表"""
        self.current_word_list = self.list_var.get()
        self.load_word_list()
        self.status_var.set(f"已切换到 {self.current_word_list} 单词列表")
        
    def load_word_list(self):
        """加载单词列表"""
        self.learning_words = self.word_lists[self.current_word_list]
        self.total_words = len(self.learning_words)
        self.current_index = 0
        self.update_progress_display()
        
        if self.current_mode == 'learn':
            self.load_learning_word()
            
    def load_learning_word(self):
        """加载学习单词"""
        if not self.learning_words:
            self.word_label.config(text="没有单词可学习")
            return
            
        self.current_word = self.learning_words[self.current_index]
        
        # 更新显示
        self.word_label.config(text=self.current_word['word'])
        self.pronunciation_label.config(text=f"/{self.current_word['pronunciation']}/")
        
        # 隐藏中文释义和例句
        self.translation_frame.pack_forget()
        self.example_frame.pack_forget()
        
        # 更新进度显示
        self.update_progress_display()
        
    def show_translation(self):
        """显示中文释义和例句"""
        if not self.current_word:
            return
            
        # 显示中文释义
        self.translation_label.config(text=self.current_word['translation'])
        self.translation_frame.pack(fill=tk.X, pady=(0, 20))
        
        # 显示例句
        self.example_label.config(text=self.current_word['example'])
        self.example_translation_label.config(text=self.current_word['example_translation'])
        self.example_frame.pack(fill=tk.X, pady=(0, 20))
        
    def mark_word(self, status):
        """标记单词掌握状态"""
        if not self.current_word:
            return
            
        word = self.current_word['word']
        
        # 更新数据库
        self.cursor.execute('''
            INSERT OR REPLACE INTO user_progress 
            (word, level, last_reviewed, next_review, correct_count, incorrect_count, mastery_level)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ''', (
            word,
            1 if status == 'known' else 2 if status == 'vague' else 3,
            datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            (datetime.now() + timedelta(days=self.settings['review_interval'])).strftime('%Y-%m-%d %H:%M:%S'),
            1 if status == 'known' else 0,
            1 if status == 'unknown' else 0,
            self.calculate_mastery_level(status)
        ))
        
        self.conn.commit()
        
        # 下一个单词
        self.next_word()
        
    def calculate_mastery_level(self, status):
        """计算掌握等级"""
        if status == 'known':
            return 3
        elif status == 'vague':
            return 2
        else:
            return 1
            
    def prev_word(self):
        """上一个单词"""
        if self.current_index > 0:
            self.current_index -= 1
            self.load_learning_word()
            
    def next_word(self):
        """下一个单词"""
        if self.current_index < len(self.learning_words) - 1:
            self.current_index += 1
            self.load_learning_word()
        else:
            messagebox.showinfo("完成", "已经是最后一个单词了！")
            
    def random_word(self):
        """随机单词"""
        if self.learning_words:
            self.current_index = random.randint(0, len(self.learning_words) - 1)
            self.load_learning_word()
            
    def update_progress_display(self):
        """更新进度显示"""
        progress_text = f"进度: {self.current_index + 1}/{self.total_words}"
        self.progress_label.config(text=progress_text)
        
    def start_test(self):
        """开始测试"""
        if not self.learning_words:
            messagebox.showwarning("提示", "没有单词可测试")
            return
            
        # 重置测试状态
        self.test_results = []
        self.correct_count = 0
        self.incorrect_count = 0
        
        # 随机选择测试单词
        test_words = random.sample(self.learning_words, min(self.settings['test_questions'], len(self.learning_words)))
        self.test_words = test_words
        
        # 生成测试题目
        self.generate_test_questions(test_words)
        
        # 显示第一个题目
        self.current_test_index = 0
        self.show_test_question()
        
    def generate_test_questions(self, words):
        """生成测试题目"""
        self.test_questions = []
        
        for word in words:
            # 随机选择题目类型
            question_type = random.choice(['meaning', 'word'])
            
            if question_type == 'meaning':
                # 测试释义
                question = {
                    'type': 'meaning',
                    'question': f"单词 '{word['word']}' 的中文意思是？",
                    'correct_answer': word['translation'],
                    'options': self.generate_options(word['translation'], [w['translation'] for w in self.learning_words])
                }
            else:
                # 测试拼写
                question = {
                    'type': 'word',
                    'question': f"中文释义 '{word['translation']}' 对应的英文单词是？",
                    'correct_answer': word['word'],
                    'options': self.generate_options(word['word'], [w['word'] for w in self.learning_words])
                }
                
            self.test_questions.append(question)
            
    def generate_options(self, correct_answer, all_answers):
        """生成选项"""
        # 确保选项数量为4
        options = [correct_answer]
        
        # 随机选择3个错误选项
        wrong_answers = [ans for ans in all_answers if ans != correct_answer]
        if len(wrong_answers) >= 3:
            options.extend(random.sample(wrong_answers, 3))
        else:
            options.extend(wrong_answers)
            # 如果不够，用占位符补足
            while len(options) < 4:
                options.append("未知")
                
        # 随机打乱选项顺序
        random.shuffle(options)
        return options
        
    def show_test_question(self):
        """显示测试题目"""
        if self.current_test_index >= len(self.test_questions):
            self.end_test()
            return
            
        question = self.test_questions[self.current_test_index]
        
        # 更新问题显示
        self.test_question_label.config(text=question['question'])
        
        # 更新选项
        for i, option in enumerate(question['options']):
            self.test_option_buttons[i].config(text=option)
            self.test_option_vars[i].set('')
            
        # 更新进度显示
        self.test_progress_label.config(
            text=f"进度: {self.current_test_index + 1}/{len(self.test_questions)}"
        )
        self.test_score_label.config(
            text=f"得分: {self.correct_count}/{self.correct_count + self.incorrect_count}"
        )
        
    def submit_test_answer(self):
        """提交测试答案"""
        # 获取选择的答案
        selected_option = None
        for i, var in enumerate(self.test_option_vars):
            if var.get():
                selected_option = i
                break
                
        if selected_option is None:
            messagebox.showwarning("提示", "请选择一个答案")
            return
            
        # 检查答案
        question = self.test_questions[self.current_test_index]
        is_correct = (question['options'][selected_option] == question['correct_answer'])
        
        # 记录结果
        self.test_results.append({
            'question': question['question'],
            'correct_answer': question['correct_answer'],
            'user_answer': question['options'][selected_option],
            'is_correct': is_correct
        })
        
        # 更新计数
        if is_correct:
            self.correct_count += 1
        else:
            self.incorrect_count += 1
            
        # 下一个问题
        self.current_test_index += 1
        self.show_test_question()
        
    def end_test(self):
        """结束测试"""
        # 显示测试结果
        total = len(self.test_questions)
        score = self.correct_count
        accuracy = (score / total * 100) if total > 0 else 0
        
        result_text = f"测试完成！\n\n"
        result_text += f"总分: {score}/{total}\n"
        result_text += f"正确率: {accuracy:.1f}%\n\n"
        result_text += f"详细结果:\n"
        
        for i, result in enumerate(self.test_results, 1):
            result_text += f"\n{i}. {result['question']}\n"
            result_text += f"   正确答案: {result['correct_answer']}\n"
            result_text += f"   你的答案: {result['user_answer']} "
            result_text += "✅" if result['is_correct'] else "❌"
            
        # 保存学习记录
        self.save_study_record('test', self.correct_count, self.incorrect_count, 0)
        
        # 显示结果
        messagebox.showinfo("测试结果", result_text)
        
        # 重置测试状态
        self.test_questions = []
        self.current_test_index = 0
        
    def update_test_display(self):
        """更新测试显示"""
        if not hasattr(self, 'test_questions') or not self.test_questions:
            self.test_question_label.config(text="点击'开始测试'按钮开始测试")
            for btn in self.test_option_buttons:
                btn.config(text="")
            self.test_progress_label.config(text="")
            self.test_score_label.config(text="")
            
    def refresh_review_list(self):
        """刷新复习列表"""
        # 清空Treeview
        for item in self.review_tree.get_children():
            self.review_tree.delete(item)
            
        # 从数据库获取需要复习的单词
        today = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.cursor.execute('''
            SELECT word, translation, next_review, mastery_level 
            FROM user_progress 
            WHERE next_review <= ? AND mastery_level < 3
            ORDER BY next_review
        ''', (today,))
        
        review_words = self.cursor.fetchall()
        
        # 添加到Treeview
        for word_data in review_words:
            word, translation, next_review, mastery = word_data
            mastery_text = "⭐⭐⭐" if mastery == 3 else "⭐⭐" if mastery == 2 else "⭐"
            self.review_tree.insert('', 'end', values=(word, translation, next_review, mastery_text))
            
    def start_review(self):
        """开始复习"""
        selection = self.review_tree.selection()
        if not selection:
            messagebox.showwarning("提示", "请选择要复习的单词")
            return
            
        item = self.review_tree.item(selection[0])
        word_text = item['values'][0]
        
        # 查找单词详情
        for word_list in self.word_lists.values():
            for word in word_list:
                if word['word'] == word_text:
                    self.current_word = word
                    self.mode_var.set('learn')
                    self.change_mode()
                    self.show_translation()
                    break
                    
    def mark_as_mastered(self):
        """标记为已掌握"""
        selection = self.review_tree.selection()
        if not selection:
            return
            
        item = self.review_tree.item(selection[0])
        word_text = item['values'][0]
        
        # 更新数据库
        self.cursor.execute('''
            UPDATE user_progress 
            SET mastery_level = 3, next_review = ?
            WHERE word = ?
        ''', (datetime.now().strftime('%Y-%m-%d %H:%M:%S'), word_text))
        self.conn.commit()
        
        # 刷新列表
        self.refresh_review_list()
        
    def update_stats(self):
        """更新统计信息"""
        # 获取统计信息
        self.cursor.execute('SELECT COUNT(*) FROM user_progress')
        total_words = self.cursor.fetchone()[0]
        
        self.cursor.execute('SELECT COUNT(*) FROM user_progress WHERE mastery_level = 3')
        mastered_words = self.cursor.fetchone()[0]
        
        self.cursor.execute('SELECT COUNT(*) FROM user_progress WHERE mastery_level < 3')
        review_words_count = self.cursor.fetchone()[0]
        
        self.cursor.execute('SELECT SUM(correct_count), SUM(incorrect_count) FROM user_progress')
        result = self.cursor.fetchone()
        total_correct = result[0] or 0
        total_incorrect = result[1] or 0
        total_attempts = total_correct + total_incorrect
        accuracy_rate = (total_correct / total_attempts * 100) if total_attempts > 0 else 0
        
        # 获取学习记录
        self.cursor.execute('SELECT * FROM study_records ORDER BY date DESC LIMIT 10')
        study_records = self.cursor.fetchall()
        
        # 更新显示
        self.total_words_label.config(text=str(total_words))
        self.mastered_words_label.config(text=str(mastered_words))
        self.review_words_count_label.config(text=str(review_words_count))
        self.accuracy_rate_label.config(text=f"{accuracy_rate:.1f}%")
        
        # 清空并更新学习记录表格
        for item in self.stats_tree.get_children():
            self.stats_tree.delete(item)
            
        for record in study_records:
            self.stats_tree.insert('', 'end', values=record[1:])
            
    def open_settings(self):
        """打开设置窗口"""
        settings_win = tk.Toplevel(self.root)
        settings_win.title("设置")
        settings_win.geometry("400x500")
        
        # 每节学习单词数
        ttk.Label(settings_win, text="每节学习单词数:").pack(anchor='w', padx=20, pady=(20, 5))
        words_var = tk.IntVar(value=self.settings['words_per_session'])
        words_spin = ttk.Spinbox(settings_win, from_=5, to=100, textvariable=words_var, width=10)
        words_spin.pack(anchor='w', padx=20, pady=(0, 10))
        
        # 测试题目数
        ttk.Label(settings_win, text="测试题目数:").pack(anchor='w', padx=20, pady=(10, 5))
        test_var = tk.IntVar(value=self.settings['test_questions'])
        test_spin = ttk.Spinbox(settings_win, from_=5, to=50, textvariable=test_var, width=10)
        test_spin.pack(anchor='w', padx=20, pady=(0, 10))
        
        # 复习间隔
        ttk.Label(settings_win, text="复习间隔(天):").pack(anchor='w', padx=20, pady=(10, 5))
        review_var = tk.IntVar(value=self.settings['review_interval'])
        review_spin = ttk.Spinbox(settings_win, from_=1, to=30, textvariable=review_var, width=10)
        review_spin.pack(anchor='w', padx=20, pady=(0, 10))
        
        # 显示音标
        show_pron_var = tk.BooleanVar(value=self.settings['show_pronunciation'])
        show_pron_cb = ttk.Checkbutton(settings_win, text="显示音标", variable=show_pron_var)
        show_pron_cb.pack(anchor='w', padx=20, pady=(10, 5))
        
        def save_settings():
            """保存设置"""
            self.settings['words_per_session'] = words_var.get()
            self.settings['test_questions'] = test_var.get()
            self.settings['review_interval'] = review_var.get()
            self.settings['show_pronunciation'] = show_pron_var.get()
            
            self.save_settings()
            settings_win.destroy()
            messagebox.showinfo("成功", "设置已保存")
            
        # 按钮
        btn_frame = ttk.Frame(settings_win)
        btn_frame.pack(fill=tk.X, padx=20, pady=20)
        
        ttk.Button(btn_frame, text="保存", command=save_settings).pack(side=tk.RIGHT, padx=5)
        ttk.Button(btn_frame, text="取消", command=settings_win.destroy).pack(side=tk.RIGHT, padx=5)
        
    def export_progress(self):
        """导出学习进度"""
        filetypes = [
            ('JSON文件', '*.json'),
            ('文本文件', '*.txt'),
            ('所有文件', '*.*')
        ]
        
        filepath = filedialog.asksaveasfilename(
            defaultextension='.json',
            filetypes=filetypes
        )
        
        if filepath:
            try:
                # 获取所有进度数据
                self.cursor.execute('SELECT * FROM user_progress')
                progress_data = self.cursor.fetchall()
                
                # 获取列名
                columns = [desc[0] for desc in self.cursor.description]
                
                # 转换为字典列表
                data = []
                for row in progress_data:
                    data.append(dict(zip(columns, row)))
                    
                # 保存到文件
                with open(filepath, 'w', encoding='utf-8') as f:
                    json.dump(data, f, ensure_ascii=False, indent=2)
                    
                messagebox.showinfo("成功", f"学习进度已导出到: {os.path.basename(filepath)}")
            except Exception as e:
                messagebox.showerror("错误", f"导出失败: {e}")
                
    def show_help(self):
        """显示帮助"""
        help_text = """英语单词背诵小程序 使用说明

学习模式：
1. 选择单词列表
2. 点击"显示中文释义"查看翻译
3. 根据掌握程度点击相应按钮
4. 使用导航按钮浏览单词

测试模式：
1. 点击"开始测试"生成测试题目
2. 选择正确答案
3. 点击"提交答案"检查
4. 查看最终测试结果

复习模式：
1. 查看需要复习的单词列表
2. 选择单词开始复习
3. 标记已掌握的单词

统计模式：
1. 查看学习进度统计
2. 查看学习记录
3. 了解学习情况

快捷键：
- 上下箭头：切换单词
- 空格键：显示/隐藏释义
- Enter键：标记为认识

设置说明：
- 可调整每节学习单词数
- 可设置测试题目数
- 可调整复习间隔
- 可控制显示选项
"""
        messagebox.showinfo("使用说明", help_text)
        
    def load_settings(self):
        """加载设置"""
        try:
            if os.path.exists('vocabulary_settings.json'):
                with open('vocabulary_settings.json', 'r', encoding='utf-8') as f:
                    self.settings.update(json.load(f))
        except Exception as e:
            print(f"加载设置失败: {e}")
            
    def save_settings(self):
        """保存设置"""
        try:
            with open('vocabulary_settings.json', 'w', encoding='utf-8') as f:
                json.dump(self.settings, f, ensure_ascii=False, indent=2)
        except Exception as e:
            print(f"保存设置失败: {e}")
            
    def load_progress(self):
        """加载学习进度"""
        # 从数据库加载，已在init_database中初始化
        pass
        
    def save_study_record(self, mode, correct, incorrect, duration):
        """保存学习记录"""
        self.cursor.execute('''
            INSERT INTO study_records (date, mode, correct, incorrect, duration)
            VALUES (?, ?, ?, ?, ?)
        ''', (
            datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
            mode,
            correct,
            incorrect,
            duration
        ))
        self.conn.commit()
        
    def on_closing(self):
        """关闭程序"""
        self.save_settings()
        if hasattr(self, 'conn'):
            self.conn.close()
        self.root.destroy()
        
    def run(self):
        """运行程序"""
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
        self.root.mainloop()

# 主程序入口
if __name__ == "__main__":
    root = tk.Tk()
    app = EnglishVocabularyApp(root)
    app.run()