import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import os
from datetime import datetime


class HeroDeedsRecorder:
    def __init__(self, root):
        self.root = root
        self.root.title("⚔️ 英雄事迹记录册")
        self.root.geometry("1180x720")
        self.root.configure(bg="#14141f")
        self.root.minsize(1000, 620)

        self.data_file = "hero_deeds.json"
        self.heroes = []
        self.current_index = None

        self.setup_styles()
        self.build_ui()
        self.load_data()
        self.refresh_list()
        self.update_stats()

    # ---------------- 样式 ----------------
    def setup_styles(self):
        style = ttk.Style()
        style.theme_use("clam")

        style.configure("TFrame", background="#14141f")
        style.configure("Panel.TFrame", background="#1f1f2e")

        style.configure("Title.TLabel", font=("Microsoft YaHei", 16, "bold"),
                        background="#14141f", foreground="#ffd700")
        style.configure("CardTitle.TLabel", font=("Microsoft YaHei", 15, "bold"),
                        background="#1f1f2e", foreground="#ffd700")
        style.configure("Sub.TLabel", font=("Microsoft YaHei", 10),
                        background="#14141f", foreground="#8a8aa0")
        style.configure("Stat.TLabel", font=("Microsoft YaHei", 11),
                        background="#252536", foreground="#e0e0e0")
        style.configure("StatNum.TLabel", font=("Microsoft YaHei", 20, "bold"),
                        background="#252536", foreground="#8b5cf6")

        style.configure("Accent.TButton", font=("Microsoft YaHei", 10, "bold"),
                        background="#8b5cf6", foreground="white", borderwidth=0)
        style.map("Accent.TButton",
                  background=[("active", "#7c3aed"), ("pressed", "#6d28d9")])
        style.configure("Gold.TButton", font=("Microsoft YaHei", 10, "bold"),
                        background="#d4af37", foreground="#1e1e2e", borderwidth=0)
        style.map("Gold.TButton",
                  background=[("active", "#c9a227"), ("pressed", "#b8960c")])
        style.configure("Danger.TButton", font=("Microsoft YaHei", 10, "bold"),
                        background="#dc2626", foreground="white", borderwidth=0)
        style.map("Danger.TButton",
                  background=[("active", "#b91c1c"), ("pressed", "#991b1b")])
        style.configure("Ghost.TButton", font=("Microsoft YaHei", 10),
                        background="#2a2a3e", foreground="#c0c0d0", borderwidth=0)
        style.map("Ghost.TButton",
                  background=[("active", "#35354a")])

        style.configure("Treeview", font=("Microsoft YaHei", 10), rowheight=34,
                        background="#1f1f2e", fieldbackground="#1f1f2e",
                        foreground="#d0d0e0", borderwidth=0)
        style.configure("Treeview.Heading", font=("Microsoft YaHei", 10, "bold"),
                        background="#2a2a3e", foreground="#ffd700", borderwidth=0)
        style.map("Treeview",
                  background=[("selected", "#8b5cf6")],
                  foreground=[("selected", "white")])

    # ---------------- 界面 ----------------
    def build_ui(self):
        # 顶部标题栏
        header = tk.Frame(self.root, bg="#1f1f2e", height=76)
        header.pack(fill="x")
        header.pack_propagate(False)

        title_box = tk.Frame(header, bg="#1f1f2e")
        title_box.pack(side="left", padx=24, pady=12)
        tk.Label(title_box, text="⚔️ 英雄事迹记录册", font=("Microsoft YaHei", 20, "bold"),
                 bg="#1f1f2e", fg="#ffd700").pack(anchor="w")
        tk.Label(title_box, text="铭记每一位英雄的传奇", font=("Microsoft YaHei", 10),
                 bg="#1f1f2e", fg="#8a8aa0").pack(anchor="w")

        # 顶部统计
        stats = tk.Frame(header, bg="#1f1f2e")
        stats.pack(side="right", padx=24)
        self.stat_total = tk.StringVar(value="0")
        self.stat_faction = tk.StringVar(value="0")
        for label, var in [("英雄总数", self.stat_total), ("阵营数", self.stat_faction)]:
            box = tk.Frame(stats, bg="#252536", padx=16, pady=6)
            box.pack(side="left", padx=6)
            tk.Label(box, text=label, font=("Microsoft YaHei", 9),
                     bg="#252536", fg="#8a8aa0").pack()
            tk.Label(box, textvariable=var, font=("Microsoft YaHei", 16, "bold"),
                     bg="#252536", fg="#ffd700").pack()

        # 主体分栏
        main = tk.Frame(self.root, bg="#14141f")
        main.pack(fill="both", expand=True, padx=18, pady=18)

        # ======== 左侧列表 ========
        left = tk.Frame(main, bg="#14141f", width=420)
        left.pack(side="left", fill="y", padx=(0, 16))
        left.pack_propagate(False)

        # 搜索 + 新建
        top_bar = tk.Frame(left, bg="#14141f")
        top_bar.pack(fill="x", pady=(0, 10))

        search_box = tk.Frame(top_bar, bg="#252536", highlightthickness=1,
                              highlightbackground="#35354a")
        search_box.pack(side="left", fill="x", expand=True, ipady=3)
        tk.Label(search_box, text="🔍", bg="#252536", fg="#8a8aa0",
                 font=("Microsoft YaHei", 11)).pack(side="left", padx=(8, 4))
        self.search_var = tk.StringVar()
        self.search_var.trace("w", lambda *a: self.refresh_list())
        entry = tk.Entry(search_box, textvariable=self.search_var,
                         font=("Microsoft YaHei", 10), bg="#252536", fg="#e0e0e0",
                         insertbackground="#e0e0e0", relief="flat")
        entry.pack(side="left", fill="x", expand=True, padx=(0, 8), pady=4)

        ttk.Button(top_bar, text="➕ 新建", style="Accent.TButton",
                   command=self.new_hero).pack(side="left", padx=(8, 0))

        # 列表
        tree_frame = tk.Frame(left, bg="#1f1f2e")
        tree_frame.pack(fill="both", expand=True)

        columns = ("name", "title", "faction")
        self.tree = ttk.Treeview(tree_frame, columns=columns, show="headings",
                                 selectmode="browse")
        self.tree.heading("name", text="英雄姓名")
        self.tree.heading("title", text="称号")
        self.tree.heading("faction", text="阵营")
        self.tree.column("name", width=130, anchor="w")
        self.tree.column("title", width=150, anchor="w")
        self.tree.column("faction", width=110, anchor="w")

        vsb = ttk.Scrollbar(tree_frame, orient="vertical", command=self.tree.yview)
        self.tree.configure(yscrollcommand=vsb.set)
        self.tree.pack(side="left", fill="both", expand=True)
        vsb.pack(side="right", fill="y")
        self.tree.bind("<<TreeviewSelect>>", self.on_select)

        # 列表底部
        list_bottom = tk.Frame(left, bg="#14141f")
        list_bottom.pack(fill="x", pady=(8, 0))
        self.count_var = tk.StringVar(value="共 0 位英雄")
        tk.Label(list_bottom, textvariable=self.count_var, font=("Microsoft YaHei", 9),
                 bg="#14141f", fg="#8a8aa0").pack(side="left")
        ttk.Button(list_bottom, text="🗑 删除", style="Danger.TButton",
                   command=self.delete_hero).pack(side="right")

        # ======== 右侧详情 ========
        right = tk.Frame(main, bg="#1f1f2e", highlightthickness=1,
                         highlightbackground="#2a2a3e")
        right.pack(side="left", fill="both", expand=True)

        inner = tk.Frame(right, bg="#1f1f2e", padx=26, pady=20)
        inner.pack(fill="both", expand=True)

        # 详情标题栏
        title_row = tk.Frame(inner, bg="#1f1f2e")
        title_row.pack(fill="x", pady=(0, 16))
        ttk.Label(title_row, text="✏️ 英雄详情", style="CardTitle.TLabel",
                  background="#1f1f2e").pack(side="left")

        # 表单区（两列）
        form = tk.Frame(inner, bg="#1f1f2e")
        form.pack(fill="x")

        self.fields = {}
        field_defs = [
            ("name", "姓名 *", "例如：亚瑟"),
            ("title", "称号", "例如：王者之剑"),
            ("faction", "阵营", "例如：圆桌骑士"),
            ("weapon", "武器", "例如：圣剑 Excalibur"),
            ("deed_date", "事迹时间", "YYYY-MM-DD"),
        ]

        for i, (key, label, hint) in enumerate(field_defs):
            row = i // 2
            col = i % 2
            cell = tk.Frame(form, bg="#1f1f2e")
            cell.grid(row=row, column=col, sticky="ew", padx=(0, 16) if col == 0 else (0, 0),
                      pady=6)
            form.grid_columnconfigure(col, weight=1)

            tk.Label(cell, text=label, font=("Microsoft YaHei", 10),
                     bg="#1f1f2e", fg="#c0c0d0", anchor="w").pack(fill="x")
            var = tk.StringVar()
            entry = tk.Entry(cell, textvariable=var, font=("Microsoft YaHei", 10),
                             bg="#14141f", fg="#e0e0e0", insertbackground="#e0e0e0",
                             relief="flat", highlightthickness=1,
                             highlightbackground="#35354a", highlightcolor="#8b5cf6")
            entry.pack(fill="x", ipady=6, pady=(3, 0))
            self.fields[key] = var

        # 事迹描述
        tk.Label(inner, text="📜 英雄事迹", font=("Microsoft YaHei", 10),
                 bg="#1f1f2e", fg="#c0c0d0", anchor="w").pack(fill="x", pady=(16, 4))
        deed_box = tk.Frame(inner, bg="#14141f", highlightthickness=1,
                            highlightbackground="#35354a")
        deed_box.pack(fill="both", expand=True)
        self.deed_text = tk.Text(deed_box, font=("Microsoft YaHei", 10),
                                 bg="#14141f", fg="#e0e0e0", insertbackground="#e0e0e0",
                                 relief="flat", wrap="word", padx=10, pady=8)
        self.deed_text.pack(fill="both", expand=True)

        # 底部按钮
        btn_frame = tk.Frame(inner, bg="#1f1f2e")
        btn_frame.pack(fill="x", pady=(16, 0))
        ttk.Button(btn_frame, text="💾 保存", style="Gold.TButton",
                   command=self.save_hero).pack(side="left", padx=(0, 8))
        ttk.Button(btn_frame, text="🔄 清空", style="Ghost.TButton",
                   command=self.clear_form).pack(side="left", padx=(0, 8))
        ttk.Button(btn_frame, text="📤 导出 JSON", style="Ghost.TButton",
                   command=self.export_json).pack(side="right")

        # 状态栏
        self.status_var = tk.StringVar(value="就绪")
        status_bar = tk.Frame(self.root, bg="#1f1f2e", height=32)
        status_bar.pack(fill="x", side="bottom")
        status_bar.pack_propagate(False)
        tk.Label(status_bar, textvariable=self.status_var, anchor="w",
                 bg="#1f1f2e", fg="#8a8aa0", font=("Microsoft YaHei", 9),
                 padx=18).pack(side="left", fill="y")

    # ---------------- 数据 ----------------
    def load_data(self):
        if os.path.exists(self.data_file):
            try:
                with open(self.data_file, "r", encoding="utf-8") as f:
                    self.heroes = json.load(f)
                self.status_var.set(f"已加载 {len(self.heroes)} 位英雄")
            except Exception as e:
                self.heroes = []
                self.status_var.set(f"加载失败: {e}")

    def save_data(self):
        try:
            with open(self.data_file, "w", encoding="utf-8") as f:
                json.dump(self.heroes, f, ensure_ascii=False, indent=2)
        except Exception as e:
            messagebox.showerror("保存失败", str(e))

    # ---------------- 列表 ----------------
    def refresh_list(self):
        keyword = self.search_var.get().strip().lower()
        for item in self.tree.get_children():
            self.tree.delete(item)
        for i, h in enumerate(self.heroes):
            text = " ".join([h.get("name", ""), h.get("title", ""),
                             h.get("faction", ""), h.get("weapon", ""),
                             h.get("deed", "")]).lower()
            if keyword and keyword not in text:
                continue
            self.tree.insert("", "end", iid=str(i), values=(
                h.get("name", ""), h.get("title", ""), h.get("faction", "")
            ))
        self.count_var.set(f"共 {len(self.tree.get_children())} 位英雄")

    def update_stats(self):
        self.stat_total.set(str(len(self.heroes)))
        factions = set(h.get("faction", "").strip() for h in self.heroes
                       if h.get("faction", "").strip())
        self.stat_faction.set(str(len(factions)))

    def on_select(self, event):
        sel = self.tree.selection()
        if not sel:
            return
        idx = int(sel[0])
        self.current_index = idx
        h = self.heroes[idx]
        for key in self.fields:
            self.fields[key].set(h.get(key, ""))
        self.deed_text.delete("1.0", "end")
        self.deed_text.insert("1.0", h.get("deed", ""))
        self.status_var.set(f"正在查看：{h.get('name', '')} - {h.get('title', '')}")

    # ---------------- 操作 ----------------
    def new_hero(self):
        self.current_index = None
        self.clear_form()
        self.tree.selection_remove(self.tree.selection())
        self.status_var.set("新建英雄，填写后点击保存")

    def clear_form(self):
        for var in self.fields.values():
            var.set("")
        self.deed_text.delete("1.0", "end")

    def validate(self):
        if not self.fields["name"].get().strip():
            messagebox.showwarning("提示", "请填写英雄姓名")
            return False
        date = self.fields["deed_date"].get().strip()
        if date:
            try:
                datetime.strptime(date, "%Y-%m-%d")
            except ValueError:
                messagebox.showwarning("提示", "事迹时间格式应为 YYYY-MM-DD")
                return False
        return True

    def save_hero(self):
        if not self.validate():
            return
        hero = {k: v.get().strip() for k, v in self.fields.items()}
        hero["deed"] = self.deed_text.get("1.0", "end").strip()
        hero["updated"] = datetime.now().strftime("%Y-%m-%d %H:%M")

        if self.current_index is None:
            self.heroes.append(hero)
            self.current_index = len(self.heroes) - 1
            self.status_var.set(f"✅ 已记录新英雄：{hero['name']}")
        else:
            self.heroes[self.current_index] = hero
            self.status_var.set(f"✅ 已更新：{hero['name']}")

        self.save_data()
        self.refresh_list()
        self.update_stats()

    def delete_hero(self):
        sel = self.tree.selection()
        if not sel:
            messagebox.showinfo("提示", "请先选择要删除的英雄")
            return
        idx = int(sel[0])
        name = self.heroes[idx].get("name", "")
        if messagebox.askyesno("确认删除", f"确定将「{name}」从英雄名录中移除吗？"):
            del self.heroes[idx]
            self.current_index = None
            self.clear_form()
            self.save_data()
            self.refresh_list()
            self.update_stats()
            self.status_var.set(f"🗑 已移除：{name}")

    def export_json(self):
        if not self.heroes:
            messagebox.showinfo("提示", "暂无可导出的英雄事迹")
            return
        path = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON 文件", "*.json")],
            initialfile="hero_deeds_export.json")
        if path:
            try:
                with open(path, "w", encoding="utf-8") as f:
                    json.dump(self.heroes, f, ensure_ascii=False, indent=2)
                messagebox.showinfo("导出成功", f"已导出到：\n{path}")
                self.status_var.set(f"📤 已导出到 {path}")
            except Exception as e:
                messagebox.showerror("导出失败", str(e))


if __name__ == "__main__":
    root = tk.Tk()
    app = HeroDeedsRecorder(root)
    root.mainloop()