import tkinter as tk
from tkinter import ttk
import random
import time

# ======================== 主应用 ========================

class MathTrainer:
    def __init__(self, root):
        self.root = root
        self.root.title("🧮 计算小能手 — 数学题练习器")
        self.root.geometry("560x720")
        self.root.resizable(False, False)
        self.root.configure(bg="#f0f4ff")

        # ---------- 状态变量 ----------
        self.correct_count = 0
        self.total_count = 0
        self.current_answer = None
        self.timer_running = False
        self.time_left = 0
        self.timer_id = None
        self.history = []  # 最近答题记录

        self._build_title()
        self._build_settings()
        self._build_question_area()
        self._build_answer_area()
        self._build_stats()
        self._build_history()
        self._build_footer()

    # ======================== 界面构建 ========================

    def _build_title(self):
        frame = tk.Frame(self.root, bg="#6366f1", height=60)
        frame.pack(fill=tk.X)
        frame.pack_propagate(False)
        tk.Label(frame, text="🧮  计算小能手",
                 font=("微软雅黑", 22, "bold"), fg="white",
                 bg="#6366f1").pack(expand=True)

    def _build_settings(self):
        """运算类型 + 难度 + 模式 选择区"""
        frame = tk.LabelFrame(self.root, text="  ⚙️ 设置  ",
                              font=("微软雅黑", 10, "bold"),
                              bg="#f0f4ff", fg="#6366f1",
                              padx=15, pady=10)
        frame.pack(padx=20, pady=(12, 5), fill=tk.X)

        # 第一行：运算类型
        row1 = tk.Frame(frame, bg="#f0f4ff")
        row1.pack(fill=tk.X, pady=(0, 6))

        tk.Label(row1, text="运算类型:", font=("微软雅黑", 10), bg="#f0f4ff").pack(side=tk.LEFT)
        self.op_var = tk.StringVar(value="混合随机")
        ops = ["加法 ＋", "减法 −", "乘法 ×", "除法 ÷", "混合随机"]
        for op in ops:
            tk.Radiobutton(row1, text=op, variable=self.op_var, value=op,
                           font=("微软雅黑", 10), bg="#f0f4ff",
                           activebackground="#f0f4ff", selectcolor="white").pack(side=tk.LEFT, padx=5)

        # 第二行：难度 + 限时
        row2 = tk.Frame(frame, bg="#f0f4ff")
        row2.pack(fill=tk.X)

        tk.Label(row2, text="难  度:", font=("微软雅黑", 10), bg="#f0f4ff").pack(side=tk.LEFT)
        self.diff_var = tk.StringVar(value="简单")
        for d in ["简单", "中等", "困难"]:
            tk.Radiobutton(row2, text=d, variable=self.diff_var, value=d,
                           font=("微软雅黑", 10), bg="#f0f4ff",
                           activebackground="#f0f4ff", selectcolor="white").pack(side=tk.LEFT, padx=8)

        # 限时模式
        self.timer_var = tk.BooleanVar(value=False)
        tk.Checkbutton(row2, text="⏱ 限时60秒", variable=self.timer_var,
                       font=("微软雅黑", 10), bg="#f0f4ff",
                       activebackground="#f0f4ff", selectcolor="white").pack(side=tk.RIGHT, padx=5)

    def _build_question_area(self):
        """题目显示区"""
        self.q_frame = tk.Frame(self.root, bg="#eef2ff", height=120)
        self.q_frame.pack(padx=20, pady=10, fill=tk.X)
        self.q_frame.pack_propagate(False)

        self.q_label = tk.Label(self.q_frame, text="点击「开始练习」出题吧！",
                                font=("微软雅黑", 32, "bold"), fg="#6366f1",
                                bg="#eef2ff")
        self.q_label.pack(expand=True)

    def _build_answer_area(self):
        """答题输入区"""
        frame = tk.Frame(self.root, bg="#f0f4ff")
        frame.pack(padx=20, pady=5, fill=tk.X)

        self.answer_var = tk.StringVar()
        self.answer_entry = tk.Entry(frame, textvariable=self.answer_var,
                                     font=("微软雅黑", 22), width=12,
                                     justify="center", relief="solid", bd=2)
        self.answer_entry.pack(side=tk.LEFT, expand=True, ipady=6)
        self.answer_entry.bind("<Return>", lambda e: self._check_answer())

        self.submit_btn = tk.Button(frame, text="✅ 提交", font=("微软雅黑", 14, "bold"),
                                    bg="#6366f1", fg="white", activebackground="#4f46e5",
                                    relief="flat", cursor="hand2", padx=20,
                                    command=self._check_answer)
        self.submit_btn.pack(side=tk.LEFT, padx=(10, 0))

        # 反馈标签
        self.feedback_label = tk.Label(self.root, text="",
                                       font=("微软雅黑", 14, "bold"),
                                       bg="#f0f4ff", fg="#6366f1")
        self.feedback_label.pack(pady=2)

    def _build_stats(self):
        """统计区"""
        frame = tk.Frame(self.root, bg="#f0f4ff")
        frame.pack(padx=20, pady=5, fill=tk.X)

        self.stats_label = tk.Label(frame, text="📊 总题: 0  |  ✅ 正确: 0  |  🎯 正确率: --",
                                    font=("微软雅黑", 12), bg="#f0f4ff", fg="#333")
        self.stats_label.pack(side=tk.LEFT)

        self.timer_label = tk.Label(frame, text="", font=("微软雅黑", 12, "bold"),
                                    bg="#f0f4ff", fg="#ef4444")
        self.timer_label.pack(side=tk.RIGHT)

    def _build_history(self):
        """历史记录区"""
        frame = tk.LabelFrame(self.root, text="  📝 最近答题记录  ",
                              font=("微软雅黑", 10, "bold"),
                              bg="#f0f4ff", fg="#6366f1", padx=10, pady=5)
        frame.pack(padx=20, pady=(8, 5), fill=tk.BOTH, expand=True)

        self.history_text = tk.Text(frame, font=("微软雅黑", 10), height=6,
                                    bg="white", fg="#333", relief="flat",
                                    wrap="word", state="disabled")
        self.history_text.pack(fill=tk.BOTH, expand=True)

    def _build_footer(self):
        btn_frame = tk.Frame(self.root, bg="#f0f4ff")
        btn_frame.pack(pady=8)

        self.start_btn = tk.Button(btn_frame, text="🚀 开始练习", font=("微软雅黑", 12, "bold"),
                                   bg="#10b981", fg="white", activebackground="#059669",
                                   relief="flat", cursor="hand2", padx=25, pady=5,
                                   command=self._start)
        self.start_btn.pack(side=tk.LEFT, padx=8)

        tk.Button(btn_frame, text="🔄 重置统计", font=("微软雅黑", 12),
                  bg="#f59e0b", fg="white", activebackground="#d97706",
                  relief="flat", cursor="hand2", padx=25, pady=5,
                  command=self._reset_stats).pack(side=tk.LEFT, padx=8)

        tk.Label(self.root, text="💡 输入答案后按 Enter 快速提交  |  支持加减乘除四则运算",
                 font=("微软雅黑", 9), fg="#999", bg="#f0f4ff").pack(side="bottom", pady=3)

    # ======================== 核心逻辑 ========================

    def _get_range(self):
        """根据难度返回随机数范围"""
        diff = self.diff_var.get()
        if diff == "简单":
            return 1, 20
        elif diff == "中等":
            return 1, 100
        else:
            return 1, 1000

    def _generate_question(self):
        """生成一道题目，返回 (题目字符串, 正确答案)"""
        low, high = self._get_range()
        op_choice = self.op_var.get()

        # 确定运算符
        if op_choice == "混合随机":
            op = random.choice(["+", "−", "×", "÷"])
        elif "加" in op_choice:
            op = "+"
        elif "减" in op_choice:
            op = "−"
        elif "乘" in op_choice:
            op = "×"
        else:
            op = "÷"

        a = random.randint(low, high)
        b = random.randint(low, high)

        # 确保减法结果不为负数
        if op == "−" and a < b:
            a, b = b, a

        # 确保除法能整除
        if op == "÷":
            if b == 0:
                b = 1
            answer = a * b  # 让 a*b ÷ b = a，保证整除
            a = a * b
            # 重新计算
            answer = a // b
            return f"{a} ÷ {b} = ?", answer

        if op == "+":
            answer = a + b
        elif op == "−":
            answer = a - b
        elif op == "×":
            answer = a * b
        else:
            answer = a // b

        return f"{a} {op} {b} = ?", answer

    def _start(self):
        """开始新一轮出题"""
        if self.current_answer is None and self.total_count == 0:
            # 首次开始，启动计时器（如果勾选了限时）
            if self.timer_var.get():
                self._start_timer()

        self._next_question()
        self.answer_entry.focus_set()

    def _next_question(self):
        """出下一题"""
        question, answer = self._generate_question()
        self.current_answer = answer
        self.q_label.config(text=question)
        self.answer_var.set("")
        self.feedback_label.config(text="", fg="#6366f1")

    def _check_answer(self):
        """检查答案"""
        if self.current_answer is None:
            self._next_question()
            return

        user_input = self.answer_var.get().strip()
        if not user_input:
            self.feedback_label.config(text="⚠️ 请先输入答案！", fg="#f59e0b")
            return

        try:
            user_answer = int(user_input)
        except ValueError:
            try:
                user_answer = float(user_input)
            except ValueError:
                self.feedback_label.config(text="⚠️ 请输入有效数字！", fg="#f59e0b")
                return

        self.total_count += 1
        question_text = self.q_label.cget("text").replace(" = ?", "")

        if user_answer == self.current_answer:
            self.correct_count += 1
            self.feedback_label.config(text="✅ 回答正确！太棒了！", fg="#10b981")
            record = f"✅ {question_text} = {user_answer}  （正确）"
        else:
            self.feedback_label.config(
                text=f"❌ 答错了！正确答案是 {self.current_answer}", fg="#ef4444")
            record = f"❌ {question_text} = {user_answer}  （正确答案: {self.current_answer}）"

        # 添加历史记录
        self.history.append(record)
        self._update_history()
        self._update_stats()

        # 检查限时是否结束
        if self.timer_running and self.time_left <= 0:
            self._end_timer()
            return

        # 自动出下一题
        self.root.after(600, self._next_question)
        self.answer_entry.focus_set()

    def _update_stats(self):
        """更新统计显示"""
        rate = f"{self.correct_count / self.total_count * 100:.1f}%" if self.total_count > 0 else "--"
        self.stats_label.config(
            text=f"📊 总题: {self.total_count}  |  ✅ 正确: {self.correct_count}  |  🎯 正确率: {rate}"
        )

    def _update_history(self):
        """更新历史记录显示（最多保留最近 50 条）"""
        self.history_text.config(state="normal")
        self.history_text.delete("1.0", "end")
        recent = self.history[-50:]
        for record in recent:
            self.history_text.insert("end", record + "\n")
        self.history_text.config(state="disabled")
        # 滚动到底部
        self.history_text.see("end")

    def _reset_stats(self):
        """重置统计数据"""
        self.correct_count = 0
        self.total_count = 0
        self.history = []
        self.current_answer = None
        self.q_label.config(text="点击「开始练习」出题吧！", fg="#6366f1")
        self.answer_var.set("")
        self.feedback_label.config(text="", fg="#6366f1")
        self._update_stats()
        self._update_history()
        if self.timer_running:
            self._stop_timer()
        self.timer_label.config(text="")

    # ======================== 计时器 ========================

    def _start_timer(self):
        self.time_left = 60
        self.timer_running = True
        self.timer_label.config(text=f"⏱ 剩余: {self.time_left}s")
        self._tick()

    def _tick(self):
        if not self.timer_running:
            return
        self.time_left -= 1
        if self.time_left <= 0:
            self.timer_label.config(text="⏱ 时间到！")
            self.timer_running = False
            # 弹出结算
            rate = f"{self.correct_count / self.total_count * 100:.1f}%" if self.total_count > 0 else "--"
            self.feedback_label.config(
                text=f"⏱ 时间到！本轮共答 {self.total_count} 题，正确 {self.correct_count} 题，正确率 {rate}",
                fg="#ef4444"
            )
            self.q_label.config(text="🏁 本轮结束！", fg="#ef4444")
            return
        self.timer_label.config(text=f"⏱ 剩余: {self.time_left}s")
        self.timer_id = self.root.after(1000, self._tick)

    def _stop_timer(self):
        self.timer_running = False
        if self.timer_id:
            self.root.after_cancel(self.timer_id)
            self.timer_id = None

    def _end_timer(self):
        self._stop_timer()


# ======================== 启动 ========================
if __name__ == "__main__":
    root = tk.Tk()
    app = MathTrainer(root)
    root.mainloop()