import tkinter as tk
from tkinter import ttk, messagebox

class MathFormulaQuery:
    def __init__(self, root):
        self.root = root
        self.root.title("数学公式查询工具")
        self.root.geometry("750x550")

        # 公式数据库：{标题:公式内容}
        self.formula_dict = {
            "一元二次方程求根公式": "x = [-b ± √(b²-4ac)] / 2a",
            "判别式": "Δ = b² - 4ac",
            "韦达定理": "x₁+x₂ = -b/a , x₁*x₂ = c/a",
            "完全平方和": "(a+b)² = a² + 2ab + b²",
            "完全平方差": "(a‑b)² = a² - 2ab + b²",
            "平方差公式": "a² - b² = (a+b)(a‑b)",
            "立方和": "a³+b³=(a+b)(a²‑ab+b²)",
            "立方差": "a³‑b³=(a‑b)(a²+ab+b²)",
            "等差数列通项": "aₙ = a₁ + (n‑1)d",
            "等差数列求和": "Sₙ = n(a₁+aₙ)/2",
            "等比数列通项": "aₙ = a₁·q^(n‑1)",
            "等比数列求和": "Sₙ = a₁(1‑qⁿ)/(1‑q) , q≠1",
            "正弦定理": "a/sinA = b/sinB = c/sinC = 2R",
            "余弦定理": "a² = b² + c² - 2bc·cosA",
            "三角形面积(海伦公式)": "S=√[p(p‑a)(p‑b)(p‑c)] , p=(a+b+c)/2",
            "两点距离公式": "d=√[(x₂‑x₁)²+(y₂‑y₁)²]",
            "中点坐标公式": "x=(x₁+x₂)/2 , y=(y₁+y₂)/2",
            "斜率公式": "k=(y₂‑y₁)/(x₂‑x₁)",
            "直线点斜式": "y‑y₀ = k(x‑x₀)",
            "圆标准方程": "(x‑a)²+(y‑b)²=r²",
            "二次函数顶点式": "y=a(x‑h)²+k 顶点(h,k)"
        }
        self.all_keys = list(self.formula_dict.keys())

        # ===顶部搜索区域===
        top_frame = ttk.Frame(root, padding=10)
        top_frame.pack(fill=tk.X)

        ttk.Label(top_frame, text="搜索公式:").pack(side=tk.LEFT)
        self.search_var = tk.StringVar()
        self.search_entry = ttk.Entry(top_frame, textvariable=self.search_var, width=40)
        self.search_entry.pack(side=tk.LEFT, padx=8)
        self.search_entry.bind("<KeyRelease>", self.on_search)

        ttk.Button(top_frame, text="重置", command=self.reset_list).pack(side=tk.LEFT, padx=5)

        # ===中间 左右分栏===
        mid_frame = ttk.Frame(root)
        mid_frame.pack(fill=tk.BOTH, expand=True, padx=10)

        # 左侧公式列表
        left_frame = ttk.LabelFrame(mid_frame, text="公式列表")
        left_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

        self.listbox = tk.Listbox(left_frame, font=("微软雅黑", 11))
        scrollbar = ttk.Scrollbar(left_frame, orient=tk.VERTICAL, command=self.listbox.yview)
        self.listbox.configure(yscrollcommand=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.listbox.pack(fill=tk.BOTH, expand=True)
        self.listbox.bind("<<ListboxSelect>>", self.show_formula)

        # 右侧显示区
        right_frame = ttk.LabelFrame(mid_frame, text="公式详情")
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=(10, 0))

        self.result_text = tk.Text(right_frame, font=("微软雅黑", 14), height=10)
        self.result_text.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

        # ===底部按钮区===
        bottom_frame = ttk.Frame(root, padding=10)
        bottom_frame.pack(fill=tk.X)
        ttk.Button(bottom_frame, text="复制公式", command=self.copy_formula).pack(side=tk.LEFT, padx=5)
        ttk.Button(bottom_frame, text="添加新公式", command=self.add_new_formula).pack(side=tk.LEFT, padx=5)

        # 初始化列表
        self.reset_list()
        self.current_formula_text = ""

    def reset_list(self):
        """恢复全部公式列表"""
        self.search_var.set("")
        self.listbox.delete(0, tk.END)
        for name in self.all_keys:
            self.listbox.insert(tk.END, name)
        self.result_text.delete(1.0, tk.END)
        self.current_formula_text = ""

    def on_search(self, event):
        """实时关键词搜索"""
        keyword = self.search_var.get().lower()
        self.listbox.delete(0, tk.END)
        for name in self.all_keys:
            if keyword in name.lower():
                self.listbox.insert(tk.END, name)

    def show_formula(self, event):
        """选中后展示公式"""
        sel = self.listbox.curselection()
        if not sel:
            return
        index = sel[0]
        name = self.listbox.get(index)
        content = self.formula_dict[name]
        self.result_text.delete(1.0, tk.END)
        self.result_text.insert(tk.END, f"【{name}】\n\n{content}")
        self.current_formula_text = content

    def copy_formula(self):
        """复制公式到剪贴板"""
        if not self.current_formula_text:
            messagebox.showwarning("提示", "请先选中一条公式！")
            return
        self.root.clipboard_clear()
        self.root.clipboard_append(self.current_formula_text)
        messagebox.showinfo("成功", "公式已复制到剪贴板！")

    def add_new_formula(self):
        """弹窗添加自定义公式"""
        win = tk.Toplevel(self.root)
        win.title("添加新公式")
        win.geometry("400x200")

        ttk.Label(win, text="公式名称：").pack(pady=3)
        name_var = tk.StringVar()
        ttk.Entry(win, textvariable=name_var, width=50).pack()

        ttk.Label(win, text="公式内容：").pack(pady=3)
        content_var = tk.StringVar()
        ttk.Entry(win, textvariable=content_var, width=50).pack()

        def save():
            n = name_var.get().strip()
            c = content_var.get().strip()
            if n and c:
                self.formula_dict[n] = c
                self.all_keys.append(n)
                self.reset_list()
                win.destroy()
                messagebox.showinfo("成功", "新公式已保存")
            else:
                messagebox.showerror("错误", "名称和内容不能为空")

        ttk.Button(win, text="保存", command=save).pack(pady=10)


if __name__ == "__main__":
    window = tk.Tk()
    app = MathFormulaQuery(window)
    window.mainloop()
