import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox
import math


class MathFormulaApp:
    def __init__(self, root):
        self.root = root
        self.root.title("数学公式查询工具")
        self.root.geometry("800x600")
        self.root.resizable(True, True)

        # 设置样式
        style = ttk.Style()
        style.configure("TFrame", background="#f0f0f0")
        style.configure("TLabel", background="#f0f0f0", font=("Arial", 10))
        style.configure("TButton", font=("Arial", 10))

        # 创建主框架
        self.create_widgets()
        self.load_formulas()

    def create_widgets(self):
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

        # 配置网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(1, weight=1)

        # 标题
        title_label = ttk.Label(main_frame, text="数学公式查询工具",
                                font=("Arial", 16, "bold"))
        title_label.grid(row=0, column=0, columnspan=2, pady=(0, 10))

        # 左侧分类树
        tree_frame = ttk.LabelFrame(main_frame, text="公式分类", padding="5")
        tree_frame.grid(row=1, column=0, sticky=(
            tk.W, tk.E, tk.N, tk.S), padx=(0, 10))
        tree_frame.rowconfigure(0, weight=1)
        tree_frame.columnconfigure(0, weight=1)

        # 创建树形视图
        self.tree = ttk.Treeview(tree_frame, show="tree")
        self.tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))

        # 滚动条
        tree_scroll = ttk.Scrollbar(
            tree_frame, orient="vertical", command=self.tree.yview)
        tree_scroll.grid(row=0, column=1, sticky=(tk.N, tk.S))
        self.tree.configure(yscrollcommand=tree_scroll.set)

        # 右侧公式显示区域
        formula_frame = ttk.LabelFrame(main_frame, text="公式详情", padding="5")
        formula_frame.grid(row=1, column=1, sticky=(tk.W, tk.E, tk.N, tk.S))
        formula_frame.rowconfigure(0, weight=1)
        formula_frame.columnconfigure(0, weight=1)

        # 公式显示文本框
        self.formula_text = scrolledtext.ScrolledText(
            formula_frame, wrap=tk.WORD, font=("Consolas", 11),
            bg="white", fg="black"
        )
        self.formula_text.grid(
            row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        self.formula_text.config(state=tk.DISABLED)

        # 底部按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.grid(row=2, column=0, columnspan=2,
                          pady=(10, 0), sticky=(tk.W, tk.E))

        clear_btn = ttk.Button(button_frame, text="清空",
                               command=self.clear_formula)
        clear_btn.pack(side=tk.RIGHT, padx=5)

        copy_btn = ttk.Button(button_frame, text="复制公式",
                              command=self.copy_formula)
        copy_btn.pack(side=tk.RIGHT, padx=5)

        # 绑定树形视图选择事件
        self.tree.bind("<<TreeviewSelect>>", self.on_formula_select)

    def load_formulas(self):
        """加载所有数学公式"""
        # 清空现有项目
        for item in self.tree.get_children():
            self.tree.delete(item)

        # 数学公式数据库
        self.formulas_db = {
            # 代数
            "代数": {
                "二次方程求根公式": {
                    "formula": "x = (-b ± √(b² - 4ac)) / (2a)",
                    "description": "用于求解 ax² + bx + c = 0 的根",
                    "example": "例如：x² + 5x + 6 = 0\na=1, b=5, c=6\nx = (-5 ± √(25-24))/2 = (-5±1)/2\n所以 x₁ = -2, x₂ = -3"
                },
                "平方差公式": {
                    "formula": "a² - b² = (a + b)(a - b)",
                    "description": "两个数的平方差等于它们的和与差的乘积",
                    "example": "16 - 9 = 4² - 3² = (4+3)(4-3) = 7×1 = 7"
                },
                "完全平方公式": {
                    "formula": "(a ± b)² = a² ± 2ab + b²",
                    "description": "二项式的完全平方展开",
                    "example": "(x + 3)² = x² + 6x + 9"
                },
                "立方和/差公式": {
                    "formula": "a³ ± b³ = (a ± b)(a² ∓ ab + b²)",
                    "description": "立方和与立方差的因式分解",
                    "example": "8 + 27 = 2³ + 3³ = (2+3)(4-6+9) = 5×7 = 35"
                }
            },

            # 几何
            "几何": {
                "勾股定理": {
                    "formula": "a² + b² = c²",
                    "description": "直角三角形中，两直角边的平方和等于斜边的平方",
                    "example": "直角边为3和4，斜边c = √(9+16) = √25 = 5"
                },
                "圆的面积": {
                    "formula": "S = πr²",
                    "description": "圆的面积等于π乘以半径的平方",
                    "example": "半径r=3，面积S = π×9 ≈ 28.27"
                },
                "圆的周长": {
                    "formula": "C = 2πr = πd",
                    "description": "圆的周长等于2π乘以半径，或π乘以直径",
                    "example": "半径r=5，周长C = 2π×5 = 10π ≈ 31.42"
                },
                "三角形面积": {
                    "formula": "S = (1/2)bh",
                    "description": "三角形面积等于底乘高除以2",
                    "example": "底b=6，高h=4，面积S = (1/2)×6×4 = 12"
                },
                "梯形面积": {
                    "formula": "S = (a + b)h/2",
                    "description": "梯形面积等于上底加下底的和乘高除以2",
                    "example": "上底a=3，下底b=7，高h=4，面积S = (3+7)×4/2 = 20"
                }
            },

            # 三角函数
            "三角函数": {
                "基本关系": {
                    "formula": "sin²θ + cos²θ = 1",
                    "description": "正弦和余弦的基本恒等式",
                    "example": "如果 sinθ = 0.6，则 cosθ = √(1-0.36) = √0.64 = 0.8"
                },
                "和角公式": {
                    "formula": "sin(α±β) = sinαcosβ ± cosαsinβ\n"
                    "cos(α±β) = cosαcosβ ∓ sinαsinβ",
                    "description": "三角函数的和角与差角公式",
                    "example": "sin(45°+30°) = sin45°cos30° + cos45°sin30°\n= (√2/2)(√3/2) + (√2/2)(1/2) = √2(√3+1)/4"
                },
                "倍角公式": {
                    "formula": "sin2θ = 2sinθcosθ\n"
                    "cos2θ = cos²θ - sin²θ = 2cos²θ - 1 = 1 - 2sin²θ",
                    "description": "三角函数的二倍角公式",
                    "example": "如果 sinθ = 0.5，则 sin2θ = 2×0.5×√(1-0.25) = √0.75 ≈ 0.866"
                }
            },

            # 微积分
            "微积分": {
                "导数基本公式": {
                    "formula": "(xⁿ)' = nxⁿ⁻¹\n"
                    "(eˣ)' = eˣ\n"
                    "(ln x)' = 1/x\n"
                    "(sin x)' = cos x\n"
                    "(cos x)' = -sin x",
                    "description": "常见函数的导数公式",
                    "example": "(x³)' = 3x²\n(e²ˣ)' = 2e²ˣ (使用链式法则)"
                },
                "积分基本公式": {
                    "formula": "∫xⁿ dx = xⁿ⁺¹/(n+1) + C (n≠-1)\n"
                    "∫eˣ dx = eˣ + C\n"
                    "∫1/x dx = ln|x| + C\n"
                    "∫sin x dx = -cos x + C\n"
                    "∫cos x dx = sin x + C",
                    "description": "常见函数的不定积分公式",
                    "example": "∫x² dx = x³/3 + C\n∫2x dx = x² + C"
                },
                "牛顿-莱布尼茨公式": {
                    "formula": "∫ₐᵇ f(x)dx = F(b) - F(a)",
                    "description": "定积分的基本定理，其中F是f的原函数",
                    "example": "∫₀¹ x² dx = [x³/3]₀¹ = 1/3 - 0 = 1/3"
                }
            },

            # 概率统计
            "概率统计": {
                "期望值": {
                    "formula": "E(X) = Σxᵢpᵢ (离散)\n"
                    "E(X) = ∫xf(x)dx (连续)",
                    "description": "随机变量的期望值（均值）",
                    "example": "掷骰子的期望值 E(X) = (1+2+3+4+5+6)/6 = 3.5"
                },
                "方差": {
                    "formula": "Var(X) = E[(X-E(X))²] = E(X²) - [E(X)]²",
                    "description": "随机变量的方差，衡量数据的离散程度",
                    "example": "掷骰子的方差 Var(X) = E(X²) - [E(X)]² = 91/6 - (3.5)² ≈ 2.92"
                },
                "正态分布": {
                    "formula": "f(x) = (1/σ√(2π))e^(-(x-μ)²/(2σ²))",
                    "description": "正态分布的概率密度函数，μ为均值，σ为标准差",
                    "example": "标准正态分布：μ=0, σ=1，f(x) = (1/√(2π))e^(-x²/2)"
                }
            }
        }

        # 将公式添加到树形视图
        for category, formulas in self.formulas_db.items():
            category_id = self.tree.insert(
                "", "end", text=category, open=False)
            for formula_name in formulas.keys():
                self.tree.insert(category_id, "end", text=formula_name)

    def on_formula_select(self, event):
        """当选择公式时显示详细信息"""
        selection = self.tree.selection()
        if not selection:
            return

        item = selection[0]
        item_text = self.tree.item(item, "text")

        # 检查是否是叶子节点（具体公式）
        if self.tree.parent(item):  # 有父节点，说明是公式
            parent_id = self.tree.parent(item)
            parent_text = self.tree.item(parent_id, "text")

            if parent_text in self.formulas_db and item_text in self.formulas_db[parent_text]:
                formula_info = self.formulas_db[parent_text][item_text]
                self.display_formula(formula_info, item_text)

    def display_formula(self, formula_info, title):
        """显示公式详细信息"""
        self.formula_text.config(state=tk.NORMAL)
        self.formula_text.delete(1.0, tk.END)

        # 格式化显示
        content = f"【{title}】\n\n"
        content += f"公式：\n{formula_info['formula']}\n\n"
        content += f"说明：\n{formula_info['description']}\n\n"
        content += f"示例：\n{formula_info['example']}"

        self.formula_text.insert(tk.END, content)
        self.formula_text.config(state=tk.DISABLED)

    def clear_formula(self):
        """清空公式显示区域"""
        self.formula_text.config(state=tk.NORMAL)
        self.formula_text.delete(1.0, tk.END)
        self.formula_text.config(state=tk.DISABLED)
        # 清除树形视图的选择
        self.tree.selection_remove(self.tree.selection())

    def copy_formula(self):
        """复制当前显示的公式到剪贴板"""
        try:
            content = self.formula_text.get(1.0, tk.END).strip()
            if content:
                self.root.clipboard_clear()
                self.root.clipboard_append(content)
                messagebox.showinfo("复制成功", "公式已复制到剪贴板！")
            else:
                messagebox.showwarning("警告", "没有可复制的内容")
        except Exception as e:
            messagebox.showerror("错误", f"复制失败：{str(e)}")


def main():
    root = tk.Tk()
    app = MathFormulaApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()
