# -*- coding: utf-8 -*-
"""🎂 生日提醒器 v3.0 —— 20功能满配版"""
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog, colorchooser, filedialog
import json, os, csv, base64, io, webbrowser, subprocess, sys, platform
from datetime import date, timedelta
from urllib import request, parse

DATA_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "birthdays.json")
AVATAR_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "avatars")

try:
    from PIL import Image, ImageTk, ImageDraw
    _PIL = True
except Exception:
    _PIL = False

def _b(root, seq, cb):
    try: root.bind_all(seq, cb)
    except tk.TclError: root.bind(seq, cb)

# ---------- 星座/生肖 ----------
ZODIAC = [("摩羯",(1,1),(1,19)),("水瓶",(1,20),(2,18)),("双鱼",(2,19),(3,20)),
           ("白羊",(3,21),(4,19)),("金牛",(4,20),(5,20)),("双子",(5,21),(6,21)),
           ("巨蟹",(6,22),(7,22)),("狮子",(7,23),(8,22)),("处女",(8,23),(9,22)),
           ("天秤",(9,23),(10,23)),("天蝎",(10,24),(11,21)),("射手",(11,22),(12,21)),
           ("摩羯",(12,22),(12,31))]

def get_zodiac(md):
    m,d = map(int,md.split("-"))
    for name,s,e in ZODIAC:
        if (m,d) >= s and (m,d) <= e: return name
    return ""

def get_shengxiao(year):
    if not year: return "-"
    animals = ["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"]
    return animals[(year-4)%12]

# ---------- 祝福模板 ----------
TEMPLATES = {
    "微信通用": "🎂 生日快乐！{name}~ 新的一岁要开开心心、顺顺利利！🎉",
    "微信亲密": "🎂🎂🎂 亲爱的{name}，生日快乐！！！新的一岁愿你被世界温柔以待，所有愿望都实现 ✨🎁",
    "微信搞笑": "🎂 恭喜{name}又年轻了一岁！（才怪）不过还是要生日快乐！🎈🎈🎈",
    "正式邮件": "尊敬的{name}：\n\n    值此您的生日之际，送上最诚挚的祝福，祝您生日快乐、身体健康、万事如意！\n\n此致\n敬礼",
    "短信简洁": "【生日提醒】{name}，今天是您的生日，祝您生日快乐！",
    "英文": "Happy Birthday {name}! 🎂 Wishing you a wonderful year ahead! 🎉✨",
}

# ---------- 主程序 ----------
class BirthdayApp(tk.Frame):
    def __init__(self, master):
        super().__init__(master, bg="#1c1c1c"); self.pack(fill=tk.BOTH, expand=True)
        self.m = master
        self._dark = True
        self.C = self._colors()
        self.data = []
        self._sort_mode = "days"
        self._warn_days = tk.IntVar(value=7)
        self._search_var = tk.StringVar()
        self._theme_var = tk.StringVar(value="暗色")
        self._avatars = {}       # uid -> PhotoImage
        self._countdown_win = None
        self._notified_today = False
        self._load()
        os.makedirs(AVATAR_DIR, exist_ok=True)
        self._build(); self._wire(); self.refresh()
        self.m.after(800, self._auto_check)
        self.m.after(2000, self._desktop_notify)

    def _colors(self):
        if self._dark:
            return dict(bg="#1c1c1c", pan="#252525", fg="#eeeeee", ac="#FF8FA3",
                        item="#3a3a3a", warn="#FFD93D", soon="#6BCB77", lunar="#5B8DB8")
        return dict(bg="#f5f5f5", pan="#e0e0e0", fg="#222222", ac="#FF6B8A",
                    item="#ffffff", warn="#E8A020", soon="#4CAF50", lunar="#1976D2")

    # ---------------- UI ----------------
    def _build(self):
        self._build_top()
        body = tk.Frame(self, bg=self.C["bg"]); body.pack(fill=tk.BOTH, expand=True)
        self._build_left(body)
        self._build_mid(body)
        self._build_right(body)
        self._st = tk.Label(self, text="🎂 生日提醒器 v3.0 | 就绪",
                            bg=self.C["pan"], fg="#aaa", anchor=tk.W)
        self._st.pack(side=tk.BOTTOM, fill=tk.X)

    def _build_top(self):
        top = tk.Frame(self, bg=self.C["pan"], height=48); top.pack(fill=tk.X)
        # 左按钮组
        btns = [("➕添加", self.add), ("✏️编辑", self.edit), ("🗑删除", self.delete),
                ("🎨颜色", self.pick_color), ("📝备注/礼物", self.show_detail),
                ("🔔检查", self.check_all), ("📤导出", self.export_txt),
                ("💬群发祝福", self.batch_greet), ("🖼头像", self.set_avatar)]
        for txt, cmd in btns:
            tk.Button(top, text=txt, bg="#3d3d3d", fg="white", relief=tk.FLAT,
                      command=cmd, padx=6, font=("Arial",9)).pack(side=tk.LEFT, padx=1, pady=8)
        # 搜索
        sf = tk.Frame(top, bg=self.C["pan"]); sf.pack(side=tk.LEFT, padx=(12,4))
        tk.Label(sf, text="🔍", bg=self.C["pan"], fg="white").pack(side=tk.LEFT)
        sv = tk.Entry(sf, textvariable=self._search_var, width=14, bg=self.C["item"], fg=self.C["fg"])
        sv.pack(side=tk.LEFT); sv.bind("<KeyRelease>", lambda e: self.refresh())
        # 提醒天数
        nf = tk.Frame(top, bg=self.C["pan"]); nf.pack(side=tk.LEFT, padx=4)
        tk.Label(nf, text="提醒:", bg=self.C["pan"], fg="#aaa", font=("Arial",9)).pack(side=tk.LEFT)
        tk.Spinbox(nf, from_=1, to=30, textvariable=self._warn_days, width=3,
                   command=self.refresh).pack(side=tk.LEFT)
        # 月份筛选
        mf = tk.Frame(top, bg=self.C["pan"]); mf.pack(side=tk.LEFT, padx=4)
        tk.Label(mf, text="月:", bg=self.C["pan"], fg="#aaa", font=("Arial",9)).pack(side=tk.LEFT)
        self._month_var = tk.StringVar(value="全部")
        ttk.Combobox(mf, textvariable=self._month_var, width=5, state="readonly",
                     values=["全部"]+[f"{i:02d}月" for i in range(1,13)]).pack(side=tk.LEFT)
        self._month_var.trace("w", lambda *a: self.refresh())
        # 排序
        of = tk.Frame(top, bg=self.C["pan"]); of.pack(side=tk.LEFT, padx=4)
        tk.Label(of, text="排序:", bg=self.C["pan"], fg="#aaa", font=("Arial",9)).pack(side=tk.LEFT)
        self._sort_var = tk.StringVar(value="剩余天数")
        ttk.Combobox(of, textvariable=self._sort_var, width=8, state="readonly",
                     values=["剩余天数","姓名","月份"]).pack(side=tk.LEFT)
        self._sort_var.trace("w", lambda *a: self.refresh())
        # 主题切换
        tf = tk.Frame(top, bg=self.C["pan"]); tf.pack(side=tk.RIGHT, padx=6)
        tk.Button(tf, text="🌓主题", bg="#555", fg="white", relief=tk.FLAT,
                  command=self.toggle_theme).pack(side=tk.RIGHT)
        tk.Button(tf, text="⏱倒计时", bg="#555", fg="white", relief=tk.FLAT,
                  command=self.show_countdown).pack(side=tk.RIGHT, padx=2)
        tk.Button(tf, text="📊统计", bg="#555", fg="white", relief=tk.FLAT,
                  command=self.show_stats).pack(side=tk.RIGHT, padx=2)
        tk.Button(tf, text="📋批量导入", bg="#555", fg="white", relief=tk.FLAT,
                  command=self.batch_import).pack(side=tk.RIGHT, padx=2)

    def _build_left(self, body):
        left = tk.Frame(body, bg=self.C["pan"], width=420)
        left.pack(side=tk.LEFT, fill=tk.BOTH, expand=True); left.pack_propagate(False)
        tk.Label(left, text="📋 联系人", bg=self.C["pan"], fg="white",
                 font=("Arial",11,"bold")).pack(pady=4)
        cols = ("avatar","name","date","left","age","zodiac","type")
        self.tree = ttk.Treeview(left, columns=cols, show="headings", height=16)
        for c,t,w in [("avatar","","30"),("name","姓名",80),("date","生日",70),
                       ("left","还有",50),("age","年龄",45),("zodiac","星座",45),("type","类型",45)]:
            self.tree.heading(c, text=t); self.tree.column(c, width=int(w), anchor=tk.CENTER)
        self.tree.tag_configure("soon", background="#5a4a00")
        self.tree.tag_configure("today", background="#7a2a2a")
        self.tree.tag_configure("lunar", background="#2a3a5a")
        sb = tk.Scrollbar(left, command=self.tree.yview); self.tree.config(yscrollcommand=sb.set)
        self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=4, pady=4)
        sb.pack(side=tk.LEFT, fill=tk.Y)

    def _build_mid(self, body):
        mid = tk.Frame(body, bg=self.C["bg"], width=280)
        mid.pack(side=tk.LEFT, fill=tk.BOTH, padx=4); mid.pack_propagate(False)
        tk.Label(mid, text="📝 详情", bg=self.C["bg"], fg="white",
                 font=("Arial",11,"bold")).pack(pady=4)
        self._avatar_label = tk.Label(mid, bg=self.C["bg"], text="(无头像)")
        self._avatar_label.pack(pady=4)
        self._detail = tk.Text(mid, bg=self.C["item"], fg=self.C["fg"],
                               wrap=tk.WORD, font=("Arial",9))
        self._detail.pack(fill=tk.BOTH, expand=True, padx=4, pady=4)
        self._detail.config(state=tk.DISABLED)
        # 快捷祝福
        tk.Label(mid, text="💬 快捷祝福", bg=self.C["bg"], fg="#aaa", font=("Arial",9)).pack(pady=2)
        self._tpl_var = tk.StringVar(value=list(TEMPLATES.keys())[0])
        ttk.Combobox(mid, textvariable=self._tpl_var, width=16, state="readonly",
                     values=list(TEMPLATES.keys())).pack(padx=4)
        tk.Button(mid, text="📋 复制祝福语", bg="#3d3d3d", fg="white",
                  command=self.copy_greeting).pack(pady=2)

    def _build_right(self, body):
        right = tk.Frame(body, bg=self.C["pan"], width=260)
        right.pack(side=tk.LEFT, fill=tk.BOTH); right.pack_propagate(False)
        tk.Label(right, text="🔔 今日 · 即将", bg=self.C["pan"], fg="white",
                 font=("Arial",11,"bold")).pack(pady=4)
        self.today_var = tk.StringVar(value="今日寿星：无")
        tk.Label(right, textvariable=self.today_var, bg=self.C["pan"], fg=self.C["ac"],
                 font=("Arial",11,"bold"), wraplength=240).pack(pady=3)
        self._upcoming = tk.Listbox(right, bg=self.C["item"], fg=self.C["fg"], height=14)
        self._upcoming.pack(fill=tk.BOTH, expand=True, padx=6, pady=4)

    # ---------------- 绑定 ----------------
    def _wire(self):
        self.tree.bind("<Double-1>", lambda e: self.show_detail())
        self.tree.bind("<<TreeviewSelect>>", lambda e: self._on_select())
        _b(self.m, "<Control-n>", lambda e: self.add())
        _b(self.m, "<Delete>", lambda e: self.delete())

    def _on_select(self):
        sel = self.tree.selection()
        if sel: self._show_selected_detail()

    # ---------------- 数据 ----------------
    def _load(self):
        if os.path.exists(DATA_FILE):
            try: self.data = json.load(open(DATA_FILE, encoding="utf-8"))
            except Exception: self.data = []

    def _save(self):
        json.dump(self.data, open(DATA_FILE,"w",encoding="utf-8"), ensure_ascii=False, indent=2)

    def _days_left(self, md):
        m,d = map(int, md.split("-"))
        today = date.today(); this_year = date(today.year, m, d)
        if this_year >= today: return (this_year - today).days, this_year.year
        next_year = date(today.year+1, m, d); return (next_year - today).days, next_year.year

    # ---------------- 操作 ----------------
    def add(self):
        dlg = tk.Toplevel(self); dlg.title("添加生日"); dlg.geometry("320x280")
        dlg.config(bg=self.C["pan"])
        tk.Label(dlg, text="姓名：", bg=self.C["pan"], fg="white").pack(pady=2)
        nv = tk.Entry(dlg, bg=self.C["item"], fg=self.C["fg"]); nv.pack(fill=tk.X, padx=20)
        tk.Label(dlg, text="生日 (MM-DD)：", bg=self.C["pan"], fg="white").pack(pady=2)
        dv = tk.Entry(dlg, bg=self.C["item"], fg=self.C["fg"]); dv.insert(0,"01-01"); dv.pack(fill=tk.X, padx=20)
        tk.Label(dlg, text="出生年（可选）：", bg=self.C["pan"], fg="white").pack(pady=2)
        yv = tk.Entry(dlg, bg=self.C["item"], fg=self.C["fg"]); yv.pack(fill=tk.X, padx=20)
        lunar_var = tk.BooleanVar()
        tk.Checkbutton(dlg, text="农历生日", variable=lunar_var,
                       bg=self.C["pan"], fg="white", selectcolor=self.C["pan"]).pack(pady=4)
        def ok():
            name,md,y = nv.get().strip(),dv.get().strip(),yv.get().strip()
            if not name or len(md)!=5 or md[2]!="-":
                messagebox.showerror("错误","格式 MM-DD"); return
            try: int(md[:2]),int(md[3:])
            except: messagebox.showerror("错误","数字无效"); return
            rec = {"name":name,"date":md,"year":int(y) if y.isdigit() else None,
                   "note":"","gift":"","color":"#FF8FA3","lunar":lunar_var.get(),
                   "avatar":"","email":"","phone":""}
            self.data.append(rec); self._save(); self.refresh(); dlg.destroy()
        tk.Button(dlg, text="确定", command=ok, bg=self.C["ac"], fg="white").pack(pady=8)

    def edit(self):
        sel = self.tree.selection()
        if not sel: return
        i = int(sel[0][1:], 16)
        if i >= len(self.data): return
        rec = self.data[i]
        new = simpledialog.askstring("编辑生日", "MM-DD:", initialvalue=rec["date"])
        if new and len(new)==5 and new[2]=="-":
            rec["date"] = new; self._save(); self.refresh()

    def delete(self):
        sel = self.tree.selection()
        if not sel: return
        i = int(sel[0][1:], 16)
        if i < len(self.data) and messagebox.askyesno("确认","删除？"):
            self.data.pop(i); self._save(); self.refresh()

    def pick_color(self):
        sel = self.tree.selection()
        if not sel: return
        i = int(sel[0][1:], 16)
        _,h = colorchooser.askcolor(initialcolor=self.data[i]["color"])
        if h: self.data[i]["color"]=h; self._save(); self.refresh()

    # ---------- 头像 ----------
    def set_avatar(self):
        sel = self.tree.selection()
        if not sel: return
        i = int(sel[0][1:], 16)
        p = filedialog.askopenfilename(filetypes=[("图片","*.png *.jpg *.jpeg *.gif *.bmp")])
        if not p: return
        self.data[i]["avatar"] = p; self._save(); self.refresh()

    def _load_avatar(self, path, size=(30,30)):
        if not path or not os.path.exists(path): return None
        if not _PIL: return None
        try:
            img = Image.open(path).convert("RGBA")
            img = img.resize(size, Image.LANCZOS)
            return ImageTk.PhotoImage(img)
        except Exception: return None

    # ---------- 详情 ----------
    def _show_selected_detail(self):
        sel = self.tree.selection()
        if not sel: return
        i = int(sel[0][1:], 16)
        if i >= len(self.data): return
        rec = self.data[i]
        self._detail.config(state=tk.NORMAL); self._detail.delete("1.0",tk.END)
        left,yr = self._days_left(rec["date"])
        age = (yr - rec["year"]) if rec.get("year") else "-"
        zodiac = get_zodiac(rec["date"])
        shengxiao = get_shengxiao(rec.get("year"))
        txt = f"👤 {rec['name']}\n"
        txt += f"📅 {rec['date']} ({'农历' if rec.get('lunar') else '公历'})\n"
        txt += f"⏳ 还有 {left} 天\n🎂 年龄: {age}\n"
        txt += f"♈ 星座: {zodiac}\n🐾 生肖: {shengxiao}\n"
        if rec.get("note"): txt += f"\n📝 {rec['note']}"
        if rec.get("gift"): txt += f"\n🎁 {rec['gift']}"
        self._detail.insert("1.0", txt); self._detail.config(state=tk.DISABLED)
        # 头像
        if rec.get("avatar") and os.path.exists(rec["avatar"]):
            ph = self._load_avatar(rec["avatar"], (80,80))
            if ph: self._avatar_label.config(image=ph,text=""); self._avatar_label.image=ph
        else:
            self._avatar_label.config(image="",text="(无头像)")

    def show_detail(self):
        sel = self.tree.selection()
        if not sel: return
        i = int(sel[0][1:], 16)
        if i >= len(self.data): return
        rec = self.data[i]
        dlg = tk.Toplevel(self); dlg.title(f"{rec['name']} 详情"); dlg.geometry("380x420")
        dlg.config(bg=self.C["pan"])
        # 头像
        if rec.get("avatar") and os.path.exists(rec["avatar"]):
            ph = self._load_avatar(rec["avatar"], (100,100))
            if ph: tk.Label(dlg, image=ph, bg=self.C["pan"]).pack(pady=4); dlg._ph=ph
        tk.Label(dlg, text=f"{rec['name']}  {rec['date']}",
                 bg=self.C["pan"], fg="white", font=("Arial",12,"bold")).pack(pady=4)
        tk.Label(dlg, text="备注:", bg=self.C["pan"], fg="#aaa").pack(anchor=tk.W, padx=12)
        nv = tk.Text(dlg, height=3, bg=self.C["item"], fg=self.C["fg"]); nv.insert("1.0",rec.get("note","")); nv.pack(fill=tk.X, padx=12)
        tk.Label(dlg, text="🎁 礼物:", bg=self.C["pan"], fg="#aaa").pack(anchor=tk.W, padx=12,pady=(6,0))
        gv = tk.Text(dlg, height=3, bg=self.C["item"], fg=self.C["fg"]); gv.insert("1.0",rec.get("gift","")); gv.pack(fill=tk.X, padx=12)
        tk.Label(dlg, text="邮箱:", bg=self.C["pan"], fg="#aaa").pack(anchor=tk.W, padx=12,pady=(6,0))
        ev = tk.Entry(dlg, bg=self.C["item"], fg=self.C["fg"]); ev.insert(0,rec.get("email","")); ev.pack(fill=tk.X, padx=12)
        tk.Label(dlg, text="电话:", bg=self.C["pan"], fg="#aaa").pack(anchor=tk.W, padx=12)
        pv = tk.Entry(dlg, bg=self.C["item"], fg=self.C["fg"]); pv.insert(0,rec.get("phone","")); pv.pack(fill=tk.X, padx=12)
        def save():
            rec["note"]=nv.get("1.0",tk.END).strip(); rec["gift"]=gv.get("1.0",tk.END).strip()
            rec["email"]=ev.get().strip(); rec["phone"]=pv.get().strip()
            self._save(); self.refresh(); dlg.destroy()
        tk.Button(dlg, text="保存", command=save, bg=self.C["ac"], fg="white").pack(pady=8)

    # ---------- 祝福 ----------
    def copy_greeting(self):
        sel = self.tree.selection()
        if not sel: return
        i = int(sel[0][1:], 16)
        rec = self.data[i]; tpl = TEMPLATES.get(self._tpl_var.get(),"")
        msg = tpl.replace("{name}", rec["name"])
        self.m.clipboard_clear(); self.m.clipboard_append(msg)
        self._st.config(text=f"✓ 祝福语已复制（{self._tpl_var.get()}）")

    def batch_greet(self):
        dlg = tk.Toplevel(self); dlg.title("群发祝福"); dlg.geometry("420x380")
        dlg.config(bg=self.C["pan"])
        tk.Label(dlg, text="选择模板：", bg=self.C["pan"], fg="white").pack(pady=2)
        tv = tk.StringVar(value=list(TEMPLATES.keys())[0])
        ttk.Combobox(dlg, textvariable=tv, width=20, state="readonly",
                     values=list(TEMPLATES.keys())).pack(pady=2)
        tk.Label(dlg, text="选择联系人（可Ctrl多选）：", bg=self.C["pan"], fg="#aaa").pack(pady=2)
        lb = tk.Listbox(dlg, selectmode=tk.MULTIPLE, bg=self.C["item"], fg=self.C["fg"])
        for rec in self.data: lb.insert(tk.END, f"{rec['name']} ({rec['date']})")
        lb.pack(fill=tk.BOTH, expand=True, padx=12, pady=2)
        out = tk.Text(dlg, height=6, bg=self.C["item"], fg=self.C["fg"])
        out.pack(fill=tk.BOTH, expand=True, padx=12, pady=4)
        def gen():
            out.delete("1.0",tk.END)
            tpl = TEMPLATES[tv.get()]
            for i in lb.curselection():
                rec = self.data[i]; msg = tpl.replace("{name}",rec["name"])
                out.insert(tk.END, f"── {rec['name']} ──\n{msg}\n\n")
        def copy_all():
            self.m.clipboard_clear(); self.m.clipboard_append(out.get("1.0",tk.END))
            messagebox.showinfo("✓","全部祝福已复制到剪贴板")
        bf = tk.Frame(dlg, bg=self.C["pan"]); bf.pack(pady=4)
        tk.Button(bf, text="生成", command=gen, bg="#3d3d3d", fg="white").pack(side=tk.LEFT, padx=4)
        tk.Button(bf, text="📋 全部复制", command=copy_all, bg=self.C["ac"], fg="white").pack(side=tk.LEFT, padx=4)

    # ---------- 批量导入 ----------
    def batch_import(self):
        dlg = tk.Toplevel(self); dlg.title("批量导入（CSV/文本）"); dlg.geometry("460x320")
        dlg.config(bg=self.C["pan"])
        tk.Label(dlg, text="格式：姓名,MM-DD,出生年(可选)\n一行一个，或从CSV粘贴：",
                 bg=self.C["pan"], fg="#aaa", justify=tk.LEFT).pack(pady=4)
        txt = tk.Text(dlg, bg=self.C["item"], fg=self.C["fg"], height=12)
        txt.pack(fill=tk.BOTH, expand=True, padx=12, pady=4)
        def doit():
            lines = txt.get("1.0",tk.END).strip().split("\n")
            cnt = 0
            for line in lines:
                parts = [p.strip() for p in line.replace(",","\t").split("\t")]
                if len(parts) < 2: continue
                name,md = parts[0],parts[1]
                if len(md)!=5 or md[2]!="-": continue
                y = int(parts[2]) if len(parts)>2 and parts[2].isdigit() else None
                self.data.append({"name":name,"date":md,"year":y,"note":"","gift":"",
                                  "color":"#FF8FA3","lunar":False,"avatar":"","email":"","phone":""})
                cnt += 1
            self._save(); self.refresh(); dlg.destroy()
            messagebox.showinfo("✓",f"导入了 {cnt} 条")
        tk.Button(dlg, text="导入", command=doit, bg=self.C["ac"], fg="white").pack(pady=6)

    # ---------- 导出 ----------
    def export_txt(self):
        p = filedialog.asksaveasfilename(defaultextension=".txt")
        if not p: return
        today_md = date.today().strftime("%m-%d")
        lines = [f"生日清单 - {date.today()}\n{'='*30}"]
        for rec in sorted(self.data, key=lambda r: self._days_left(r["date"])[0]):
            left,_ = self._days_left(rec["date"])
            tag = "🎂今天!" if rec["date"]==today_md else f"{left}天后"
            lines.append(f"{rec['name']}  {rec['date']}  {tag}")
        with open(p,"w",encoding="utf-8") as f: f.write("\n".join(lines))
        messagebox.showinfo("✓",f"已导出 {os.path.basename(p)}")

    # ---------- 统计 ----------
    def show_stats(self):
        today = date.today()
        this_month = today.strftime("%m")
        bm = sum(1 for r in self.data if r["date"].startswith(this_month))
        this_year = sum(1 for r in self.data if self._days_left(r["date"])[0] <= 365)
        ages = [today.year - r["year"] for r in self.data if r.get("year")]
        avg_age = sum(ages)//len(ages) if ages else 0
        zodiacs = {}
        for r in self.data:
            z = get_zodiac(r["date"])
            zodiacs[z] = zodiacs.get(z,0)+1
        top_z = max(zodiacs, key=zodiacs.get) if zodiacs else "-"
        msg = f"📊 统计面板\n{'-'*20}\n"
        msg += f"总人数: {len(self.data)}\n本月生日: {bm}\n今年生日: {this_year}\n平均年龄: {avg_age}\n最多星座: {top_z}"
        messagebox.showinfo("📊 统计", msg)

    # ---------- 倒计时 ----------
    def show_countdown(self):
        if self._countdown_win and self._countdown_win.winfo_exists():
            self._countdown_win.lift(); return
        w = tk.Toplevel(self); w.title("⏱ 倒计时"); w.geometry("240x180")
        w.config(bg="#2b2b2b"); self._countdown_win = w
        lbl = tk.Label(w, text="", bg="#2b2b2b", fg="#FF8FA3", font=("Arial",14,"bold"))
        lbl.pack(expand=True)
        def tick():
            if not w.winfo_exists(): return
            nxt = min(self.data, key=lambda r: self._days_left(r["date"])[0]) if self.data else None
            if nxt:
                left,_ = self._days_left(nxt["date"])
                lbl.config(text=f"{nxt['name']}\n还有 {left} 天\n{nxt['date']}")
            w.after(1000, tick)
        tick()

    # ---------- 主题 ----------
    def toggle_theme(self):
        self._dark = not self._dark
        self.C = self._colors()
        messagebox.showinfo("主题","重启程序生效（数据不丢）")

    # ---------- 桌面通知 ----------
    def _desktop_notify(self):
        if self._notified_today: return
        today_md = date.today().strftime("%m-%d")
        todays = [r for r in self.data if r["date"]==today_md]
        if todays:
            title = f"🎂 今天 {len(todays)} 人过生日"
            msg = "、".join(r["name"] for r in todays)
            if platform.system()=="Windows":
                try:
                    from win10toast import ToastNotifier
                    ToastNotifier().show_toast(title, msg, duration=5)
                except ImportError:
                    pass
            self._notified_today = True

    # ---------- 自动检查 ----------
    def _auto_check(self):
        warn = self._warn_days.get()
        today_md = date.today().strftime("%m-%d")
        todays = [r for r in self.data if r["date"]==today_md]
        soon = [r for r in self.data if 0<self._days_left(r["date"])[0]<=warn]
        msg = ""
        if todays: msg += "🎂 今天过生日：\n"+"\n".join(f"  {r['name']}" for r in todays)+"\n"
        if soon: msg += f"🔔 {warn}天内：\n"+"\n".join(f"  {r['name']} ({r['date']}, {self._days_left(r['date'])[0]}天)" for r in soon)
        if msg: messagebox.showinfo("🎂 生日提醒", msg)

    def check_all(self):
        self._auto_check(); self.refresh()

    # ---------- 刷新 ----------
    def refresh(self):
        self.tree.delete(*self.tree.get_children())
        self._upcoming.delete(0,tk.END)
        today_md = date.today().strftime("%m-%d")
        todays=[]; upcoming=[]
        warn = self._warn_days.get()
        # 搜索过滤
        q = self._search_var.get().lower()
        data = [r for r in self.data if q in r["name"].lower()] if q else list(self.data)
        # 月份过滤
        if self._month_var.get()!="全部":
            mm = self._month_var.get().replace("月","")
            data = [r for r in data if r["date"].startswith(mm)]
        for i,rec in enumerate(data):
            left,yr = self._days_left(rec["date"])
            tag=""
            if rec["date"]==today_md: tag="today"; todays.append(rec)
            elif left<=warn: tag="soon"
            if rec.get("lunar"): tag="lunar"
            upcoming.append((left,rec))
            age = (yr-rec["year"]) if rec.get("year") else "-"
            zodiac = get_zodiac(rec["date"])
            btype = "农历" if rec.get("lunar") else "公历"
            # 头像列
            av = "" if not rec.get("avatar") else "🖼"
            self.tree.insert("",tk.END,iid=f"I{i}",values=(av,rec["name"],rec["date"],f"{left}天",age,zodiac,btype),tags=(tag,))
        # 排序
        sm = self._sort_var.get()
        if sm=="姓名": upcoming.sort(key=lambda x:x[1]["name"])
        elif sm=="月份": upcoming.sort(key=lambda x:x[1]["date"])
        else: upcoming.sort(key=lambda x:x[0])
        for left,rec in upcoming:
            if left<=warn:
                self._upcoming.insert(tk.END,f"{left:>3}天 → {rec['name']} ({rec['date']})")
        if todays:
            self.today_var.set("🎉 今日寿星："+"、".join(r["name"] for r in todays))
        else:
            self.today_var.set("今日寿星：无")
        sel = self.tree.selection()
        if sel: self._show_selected_detail()

# ---------- 启动 ----------
def main():
    root = tk.Tk(); root.title("🎂 生日提醒器 v3.0"); root.geometry("960x620")
    root.config(bg="#1c1c1c")
    s=ttk.Style(); s.theme_use("clam")
    s.configure("Treeview",background="#3a3a3a",foreground="#eeeeee",fieldbackground="#3a3a3a",rowheight=26)
    s.configure("Treeview.Heading",background="#252525",foreground="white")
    BirthdayApp(root); root.mainloop()

if __name__=="__main__":
    main()