# -*- coding: utf-8 -*-
"""计算小能手 v2.0 — 数学题练习器（重写修复版）"""
import tkinter as tk
from tkinter import ttk, messagebox
import random, time, json, os, datetime

DATA_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "math_scores.json")

FT_TITLE = ("Microsoft YaHei", 18, "bold")
FT_BTN   = ("Microsoft YaHei", 11)
FT_BIG   = ("Microsoft YaHei", 28, "bold")
FT_MID   = ("Microsoft YaHei", 14)
FT_SMALL = ("Microsoft YaHei", 10)

# ============ 数据 ============
def load_scores():
    try:
        if os.path.exists(DATA_FILE):
            return json.load(open(DATA_FILE, encoding="utf-8"))
    except: pass
    return []

def save_score(score):
    scores = load_scores()
    scores.append(score)
    scores = scores[-50:]
    json.dump(scores, open(DATA_FILE, "w", encoding="utf-8"), ensure_ascii=False, indent=2)

# ============ 主窗口 ============
class MathApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("计算小能手 v2.0")
        self.geometry("600x500")
        self.config(bg="#1a1a2e")
        self.resizable(False, False)

        # 练习状态
        self.mode = None
        self.questions = []      # [{"a":int,"b":int,"op":str,"answer":int}, ...]
        self.idx = 0
        self.correct = 0
        self.wrong = 0
        self.start_t = 0
        self.time_limit = 0
        self._locked = False     # 防止重复提交

        self._menu()

    def _clear(self):
        for w in self.winfo_children():
            w.destroy()

    # ==================== 主菜单 ====================
    def _menu(self):
        self._clear()
        tk.Label(self, text="计算小能手", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=50, anchor="center")

        cards = [
            ("📊 四则运算", "加减乘除随机出题", self._page_arithmetic),
            ("✖ 乘法表", "九九乘法表背诵", self._page_multiplication),
            ("📝 竖式练习", "加减法竖式填空", self._page_vertical),
        ]
        for i, (title, desc, cmd) in enumerate(cards):
            f = tk.Frame(self, bg="#16213e", relief=tk.RAISED, bd=1)
            f.place(relx=0.5, y=140+i*90, anchor="center", width=400, height=75)
            tk.Label(f, text=title, bg="#16213e", fg="white", font=FT_MID).pack(pady=(8,2))
            tk.Label(f, text=desc, bg="#16213e", fg="#aaa", font=FT_SMALL).pack()
            f.bind("<Button-1>", lambda e, c=cmd: c())
            for w in f.winfo_children():
                w.bind("<Button-1>", lambda e, c=cmd: c())

        tk.Button(self, text="📈 历史记录", bg="#4CAF50", fg="white", font=FT_BTN,
                  command=self._page_history, width=12).place(relx=0.5, y=430, anchor="center")

    # ==================== 设置页：四则 ====================
    def _page_arithmetic(self):
        self._clear()
        tk.Label(self, text="四则运算设置", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=40, anchor="center")

        tk.Label(self, text="数字位数:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=110)
        self.ar_arity = tk.IntVar(value=1)
        ttk.Combobox(self, textvariable=self.ar_arity, values=[1,2,3], width=6, font=FT_BTN, state="readonly").place(x=330, y=110)

        tk.Label(self, text="运算类型:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=155)
        self.ar_op = tk.StringVar(value="混合")
        ttk.Combobox(self, textvariable=self.ar_op, values=["混合","只加","只减","只乘","只除"], width=8, font=FT_BTN, state="readonly").place(x=330, y=155)

        tk.Label(self, text="题目数量:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=200)
        self.ar_count = tk.IntVar(value=10)
        ttk.Spinbox(self, from_=5, to=100, textvariable=self.ar_count, width=8, font=FT_BTN).place(x=330, y=200)

        tk.Label(self, text="限时(分钟):", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=245)
        self.ar_time = tk.IntVar(value=0)
        ttk.Spinbox(self, from_=0, to=60, textvariable=self.ar_time, width=8, font=FT_BTN).place(x=330, y=245)

        tk.Button(self, text="开始", bg="#4CAF50", fg="white", font=FT_BTN, command=self._start_arithmetic, width=12).place(relx=0.35, y=330, anchor="center")
        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=12).place(relx=0.65, y=330, anchor="center")

    # ==================== 设置页：乘法表 ====================
    def _page_multiplication(self):
        self._clear()
        tk.Label(self, text="乘法表练习", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=40, anchor="center")

        tk.Label(self, text="起始:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=120)
        self.mu_start = tk.IntVar(value=1)
        ttk.Spinbox(self, from_=1, to=9, textvariable=self.mu_start, width=8, font=FT_BTN).place(x=330, y=120)

        tk.Label(self, text="结束:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=165)
        self.mu_end = tk.IntVar(value=9)
        ttk.Spinbox(self, from_=1, to=9, textvariable=self.mu_end, width=8, font=FT_BTN).place(x=330, y=165)

        tk.Label(self, text="题数:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=210)
        self.mu_count = tk.IntVar(value=20)
        ttk.Spinbox(self, from_=5, to=81, textvariable=self.mu_count, width=8, font=FT_BTN).place(x=330, y=210)

        tk.Button(self, text="开始", bg="#4CAF50", fg="white", font=FT_BTN, command=self._start_multiplication, width=12).place(relx=0.35, y=310, anchor="center")
        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=12).place(relx=0.65, y=310, anchor="center")

    # ==================== 设置页：竖式 ====================
    def _page_vertical(self):
        self._clear()
        tk.Label(self, text="竖式练习", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=40, anchor="center")

        tk.Label(self, text="类型:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=120)
        self.vt_type = tk.StringVar(value="加法")
        ttk.Combobox(self, textvariable=self.vt_type, values=["加法","减法"], width=8, font=FT_BTN, state="readonly").place(x=330, y=120)

        tk.Label(self, text="位数:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=165)
        self.vt_digits = tk.IntVar(value=2)
        ttk.Spinbox(self, from_=1, to=4, textvariable=self.vt_digits, width=8, font=FT_BTN).place(x=330, y=165)

        tk.Label(self, text="题数:", bg="#1a1a2e", fg="white", font=FT_BTN).place(x=130, y=210)
        self.vt_count = tk.IntVar(value=10)
        ttk.Spinbox(self, from_=5, to=50, textvariable=self.vt_count, width=8, font=FT_BTN).place(x=330, y=210)

        tk.Button(self, text="开始", bg="#4CAF50", fg="white", font=FT_BTN, command=self._start_vertical, width=12).place(relx=0.35, y=310, anchor="center")
        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN, command=self._menu, width=12).place(relx=0.65, y=310, anchor="center")

    # ==================== 出题 ====================
    def _gen_arithmetic(self):
        """四则运算出题 — 每个题存 a, b, op, answer 四个字段"""
        arity = self.ar_arity.get()
        op_sel = self.ar_op.get()
        mx = 10 ** arity - 1
        mn = 1 if arity == 1 else 10 ** (arity - 1)

        op_map = {"只加":"+","只减":"-","只乘":"×","只除":"÷"}
        if op_sel == "混合":
            ops = ["+", "-", "×", "÷"]
        else:
            ops = [op_map[op_sel]]

        qs = []
        for _ in range(self.ar_count.get()):
            op = random.choice(ops)
            if op == "+":
                a = random.randint(mn, mx)
                b = random.randint(mn, mx)
                ans = a + b
            elif op == "-":
                a = random.randint(mn, mx)
                b = random.randint(mn, a)
                ans = a - b
            elif op == "×":
                a = random.randint(mn, mx)
                b = random.randint(mn, mx)
                ans = a * b
            elif op == "÷":
                # 先定除数和商，再算被除数，保证整除
                b = random.randint(mn, mx)
                ans = random.randint(mn, mx)
                a = b * ans
                # 若超范围就缩小商
                while a > mx:
                    ans -= 1
                    if ans < mn:
                        ans = mn
                        break
                    a = b * ans
            qs.append({"a": a, "b": b, "op": op, "answer": ans})
        return qs

    def _gen_multiplication(self):
        s, e = self.mu_start.get(), self.mu_end.get()
        if s > e: s, e = e, s
        pairs = [(i, j) for i in range(s, e+1) for j in range(1, 10)]
        random.shuffle(pairs)
        n = min(self.mu_count.get(), len(pairs))
        return [{"a": x, "b": y, "op": "×", "answer": x*y} for x, y in pairs[:n]]

    def _gen_vertical(self):
        digits = self.vt_digits.get()
        vtype = self.vt_type.get()
        mx = 10 ** digits - 1
        mn = 1 if digits == 1 else 10 ** (digits - 1)
        qs = []
        for _ in range(self.vt_count.get()):
            if vtype == "加法":
                a = random.randint(mn, mx)
                b = random.randint(mn, mx)
                ans = a + b
                op = "+"
            else:
                a = random.randint(mn, mx)
                b = random.randint(mn, a)
                ans = a - b
                op = "-"
            qs.append({"a": a, "b": b, "op": op, "answer": ans, "vertical": True})
        return qs

    # ==================== 启动 ====================
    def _start_arithmetic(self):
        self.mode = "四则运算"
        self.questions = self._gen_arithmetic()
        self._begin()

    def _start_multiplication(self):
        self.mode = "乘法表"
        self.questions = self._gen_multiplication()
        self._begin()

    def _start_vertical(self):
        self.mode = "竖式练习"
        self.questions = self._gen_vertical()
        self._begin()

    def _begin(self):
        self.idx = 0
        self.correct = 0
        self.wrong = 0
        self.start_t = time.time()
        self.time_limit = self.ar_time.get() * 60 if self.mode == "四则运算" else 0
        self._locked = False
        self._show_question()

    # ==================== 练习界面 ====================
    def _show_question(self):
        self._clear()

        # 顶部信息
        tk.Label(self, text="第 {}/{} 题".format(self.idx+1, len(self.questions)),
                 bg="#1a1a2e", fg="#aaa", font=FT_SMALL).place(relx=0.5, y=20, anchor="center")
        self._timer_lbl = tk.Label(self, text="⏱ 00:00", bg="#1a1a2e", fg="#FFD700", font=FT_BTN)
        self._timer_lbl.place(x=480, y=15)
        self._tick_timer()

        q = self.questions[self.idx]

        # 竖式 or 普通
        if q.get("vertical"):
            # 竖式显示
            f = tk.Frame(self, bg="#1a1a2e")
            f.place(relx=0.5, y=180, anchor="center")
            tk.Label(f, text="  {}".format(q["a"]), bg="#1a1a2e", fg="white", font=("Courier", 24)).pack()
            tk.Label(f, text="{} {}".format(q["op"], q["b"]), bg="#1a1a2e", fg="white", font=("Courier", 24)).pack()
            tk.Label(f, text="─" * 10, bg="#1a1a2e", fg="white", font=("Courier", 16)).pack()
            display = ""
        else:
            display = "{} {} {} = ?".format(q["a"], q["op"], q["b"])
            tk.Label(self, text=display, bg="#1a1a2e", fg="white", font=FT_BIG).place(relx=0.5, y=170, anchor="center")

        # 答案输入
        self._ans_var = tk.StringVar()
        entry = tk.Entry(self, textvariable=self._ans_var, bg="#16213e", fg="white",
                         font=FT_BIG, width=6, justify="center", relief=tk.FLAT, insertbackground="white")
        entry.place(relx=0.5, y=310, anchor="center")
        entry.focus_set()

        # 绑定回车
        entry.bind("<Return>", lambda e: self._judge())
        self.bind("<Return>", lambda e: self._judge())

        # 反馈标签
        self._fb_lbl = tk.Label(self, text="", bg="#1a1a2e", font=FT_MID)
        self._fb_lbl.place(relx=0.5, y=380, anchor="center")

        # 按钮
        tk.Button(self, text="提交", bg="#4CAF50", fg="white", font=FT_BTN,
                  command=self._judge, width=10).place(relx=0.35, y=440, anchor="center")
        tk.Button(self, text="菜单", bg="#666", fg="white", font=FT_BTN,
                  command=self._menu, width=10).place(relx=0.65, y=440, anchor="center")

    def _tick_timer(self):
        if not self.questions or self.idx >= len(self.questions):
            return
        elapsed = int(time.time() - self.start_t)
        m, s = divmod(elapsed, 60)
        self._timer_lbl.config(text="⏱ {:02d}:{:02d}".format(m, s))
        # 限时到
        if self.time_limit > 0 and elapsed >= self.time_limit:
            self._finish()
            return
        self._timer_id = self.after(1000, self._tick_timer)

    def _judge(self):
        if self._locked:
            return
        try:
            user = int(self._ans_var.get().strip())
        except ValueError:
            self._fb_lbl.config(text="⚠ 请输入数字", fg="#FF9800")
            return

        q = self.questions[self.idx]
        if user == q["answer"]:
            self.correct += 1
            self._fb_lbl.config(text="✓ 正确！", fg="#4CAF50")
        else:
            self.wrong += 1
            self._fb_lbl.config(text="✗ 错，答案：{}".format(q["answer"]), fg="#FF4444")

        self._locked = True
        self.after(900, self._next)

    def _next(self):
        self.idx += 1
        self._locked = False
        if self.idx >= len(self.questions):
            self._finish()
        else:
            self._show_question()

    # ==================== 成绩单 ====================
    def _finish(self):
        if hasattr(self, '_timer_id'):
            self.after_cancel(self._timer_id)

        elapsed = int(time.time() - self.start_t)
        m, s = divmod(elapsed, 60)
        total = self.correct + self.wrong
        acc = round(self.correct / total * 100, 1) if total > 0 else 0

        save_score({
            "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
            "mode": self.mode, "total": total,
            "correct": self.correct, "wrong": self.wrong,
            "accuracy": acc, "time": elapsed
        })

        self._clear()
        tk.Label(self, text="完成！", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=60, anchor="center")

        lines = ["总题: {}  正确: {}  错误: {}".format(total, self.correct, self.wrong),
                 "正确率: {}%".format(acc), "用时: {:02d}:{:02d}".format(m, s)]
        colors = ["white", "#4CAF50" if acc >= 70 else "#FF4444", "#aaa"]
        for i, (t, c) in enumerate(zip(lines, colors)):
            tk.Label(self, text=t, bg="#1a1a2e", fg=c, font=FT_MID).place(relx=0.5, y=150+i*45, anchor="center")

        # 评级
        if acc >= 90:   grade, gc = "🌟🌟🌟 太棒了！", "#FFD700"
        elif acc >= 70: grade, gc = "🌟🌟 不错哦！", "#4CAF50"
        elif acc >= 60: grade, gc = "🌟 继续加油", "#FF9800"
        else:           grade, gc = "💪 多加练习！", "#FF4444"
        tk.Label(self, text=grade, bg="#1a1a2e", fg=gc, font=("Microsoft YaHei", 22, "bold")).place(relx=0.5, y=330, anchor="center")

        tk.Button(self, text="再来", bg="#4CAF50", fg="white", font=FT_BTN,
                  command=lambda: self._restart(), width=10).place(relx=0.35, y=420, anchor="center")
        tk.Button(self, text="菜单", bg="#666", fg="white", font=FT_BTN,
                  command=self._menu, width=10).place(relx=0.65, y=420, anchor="center")

    def _restart(self):
        if self.mode == "四则运算":   self._start_arithmetic()
        elif self.mode == "乘法表":   self._start_multiplication()
        elif self.mode == "竖式练习": self._start_vertical()

    # ==================== 历史 ====================
    def _page_history(self):
        self._clear()
        tk.Label(self, text="历史记录", bg="#1a1a2e", fg="#FFD700", font=FT_TITLE).place(relx=0.5, y=30, anchor="center")

        scores = load_scores()
        if not scores:
            tk.Label(self, text="暂无记录", bg="#1a1a2e", fg="#aaa", font=FT_MID).place(relx=0.5, y=200, anchor="center")
        else:
            canvas = tk.Canvas(self, bg="#1a1a2e", highlightthickness=0)
            sb = ttk.Scrollbar(self, orient="vertical", command=canvas.yview)
            f = tk.Frame(canvas, bg="#1a1a2e")
            f.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
            canvas.create_window((0,0), window=f, anchor="nw")
            canvas.configure(yscrollcommand=sb.set)
            canvas.place(x=50, y=80, width=500, height=350)
            sb.place(x=550, y=80, height=350)

            # 表头
            h = tk.Frame(f, bg="#0f3460")
            h.pack(fill=tk.X, pady=2)
            for i, t in enumerate(["时间","模式","正确率","用时"]):
                tk.Label(h, text=t, bg="#0f3460", fg="#FFD700", font=FT_SMALL, width=12).grid(row=0, column=i)

            for sc in reversed(scores[-20:]):
                row = tk.Frame(f, bg="#16213e")
                row.pack(fill=tk.X, pady=1)
                m, s = divmod(sc.get("time",0), 60)
                ac = sc.get("accuracy", 0)
                for i, v in enumerate([sc.get("date","")[-5:], sc.get("mode",""), "{}%".format(ac), "{:02d}:{:02d}".format(m,s)]):
                    c = "#4CAF50" if (i==2 and ac>=70) else ("#FF4444" if i==2 else "white")
                    tk.Label(row, text=v, bg="#16213e", fg=c, font=FT_SMALL, width=12).grid(row=0, column=i)

        tk.Button(self, text="返回", bg="#666", fg="white", font=FT_BTN,
                  command=self._menu, width=10).place(relx=0.5, y=460, anchor="center")

# ============ 入口 ============
if __name__ == "__main__":
    app = MathApp()
    app.mainloop()