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

# ====================== 古风配色设置 ======================
BG_MAIN = "#F8EAD8"        # 宣纸米黄色背景
FRAME_COLOR = "#E9D2C0"    # 浅檀木色面板
BUTTON_BG = "#B85450"      # 胭脂红按钮
BUTTON_HOVER = "#943633"
FONT_COLOR = "#5C2E2E"     # 深褐色文字
INPUT_BG = "#FFF7EC"
SAVE_FILE = "古风生辰录.json"

# 读写生辰数据
def load_data():
    if os.path.exists(SAVE_FILE):
        with open(SAVE_FILE, "r", encoding="utf‑8") as f:
            return json.load(f)
    return []

def save_data(data_list):
    with open(SAVE_FILE,"w",encoding="utf‑8") as f:
        json.dump(data_list,f,ensure_ascii=False,indent=2)

birth_list = load_data()

# ====================== 主窗口 ======================
win = tk.Tk()
win.title("🏮 古风生辰备忘录")
win.geometry("540x640")
win.configure(bg=BG_MAIN)
win.resizable(False,False)

# 按钮悬浮效果
def mouse_enter(event):
    event.widget.config(bg=BUTTON_HOVER)
def mouse_leave(event):
    event.widget.config(bg=BUTTON_BG)

# 顶部标题
title_label = tk.Label(win,text="🏮 良辰生辰录 🏮",
                        font=("楷体",22,"bold"),bg=BG_MAIN,fg=FONT_COLOR)
title_label.pack(pady=18)

# 输入面板
input_frame = tk.Frame(win,bg=FRAME_COLOR,bd=4,relief="groove")
input_frame.pack(padx=22,pady=8,fill="x")

tk.Label(input_frame,text="佳人姓名",font=("楷体",13),bg=FRAME_COLOR,fg=FONT_COLOR).grid(row=0,column=0,padx=10,pady=9)
name_input = tk.Entry(input_frame,font=("楷体",12),bg=INPUT_BG,width=24)
name_input.grid(row=0,column=1,pady=9)

tk.Label(input_frame,text="生辰(月‑日)",font=("楷体",13),bg=FRAME_COLOR,fg=FONT_COLOR).grid(row=1,column=0,padx=10,pady=9)
date_input = tk.Entry(input_frame,font=("楷体",12),bg=INPUT_BG,width=24)
date_input.grid(row=1,column=1,pady=9)

tk.Label(input_frame,text="笺中备注",font=("楷体",13),bg=FRAME_COLOR,fg=FONT_COLOR).grid(row=2,column=0,padx=10,pady=9)
remark_input = tk.Entry(input_frame,font=("楷体",12),bg=INPUT_BG,width=24)
remark_input.grid(row=2,column=1,pady=9)

# 功能按钮区
btn_frame = tk.Frame(win,bg=BG_MAIN)
btn_frame.pack(pady=8)

def add_birth():
    name = name_input.get().strip()
    bday = date_input.get().strip()
    note = remark_input.get().strip()
    if not name or not bday:
        messagebox.showerror("提示","姓名以及生辰不可空缺！格式示例：08‑07")
        return
    birth_list.append({"name":name,"date":bday,"remark":note})
    save_data(birth_list)
    refresh_treeview()
    name_input.delete(0,tk.END)
    date_input.delete(0,tk.END)
    remark_input.delete(0,tk.END)
    check_today_birthday()

add_btn = tk.Button(btn_frame,text="✨录入生辰",bg=BUTTON_BG,fg="#ffffff",
                      font=("楷体",12,"bold"),width=13,command=add_birth)
add_btn.grid(row=0,column=0,padx=7)
add_btn.bind("<Enter>",mouse_enter)
add_btn.bind("<Leave>",mouse_leave)

def del_selected():
    select_item = tree.selection()
    if not select_item:
        messagebox.showinfo("告知","请先择取一条生辰记录")
        return
    index = tree.index(select_item[0])
    birth_list.pop(index)
    save_data(birth_list)
    refresh_treeview()

del_btn = tk.Button(btn_frame,text="🗑 删除笺录",bg=BUTTON_BG,fg="#ffffff",
                     font=("楷体",12,"bold"),width=13,command=del_selected)
del_btn.grid(row=0,column=1,padx=7)
del_btn.bind("<Enter>",mouse_enter)
del_btn.bind("<Leave>",mouse_leave)

# 生辰列表表格
table_frame = tk.Frame(win,bg=FRAME_COLOR,bd=4,relief="groove")
table_frame.pack(padx=22,pady=10,fill="both",expand=True)
cols = ("name","bdate","remark")
tree = ttk.Treeview(table_frame,columns=cols,show="headings",height=13)
tree.heading("name",text="👤 姓名")
tree.heading("bdate",text="🎐 生辰月日")
tree.heading("remark",text="📜 备注笺言")
tree.column("name",width=145)
tree.column("bdate",width=125)
tree.column("remark",width=210)

def refresh_treeview():
    for item in tree.get_children():
        tree.delete(item)
    for info in birth_list:
        tree.insert("",tk.END,values=(info["name"],info["date"],info["remark"]))
refresh_treeview()

# 检测今日生辰
def check_today_birthday():
    now_time = datetime.now()
    today_str = now_time.strftime("%m-%d")
    today_people = []
    for one in birth_list:
        if one["date"] == today_str:
            today_people.append(one["name"])
    if today_people:
        tip_text = "🏮 今日乃是贵人生辰\n" + "\n".join(today_people)
        messagebox.showinfo("生辰吉时提醒",tip_text)

# 倒计时区域
down_frame = tk.Frame(win,bg=FRAME_COLOR,bd=3,relief="groove")
down_frame.pack(padx=22,pady=10,fill="x")
tk.Label(down_frame,text="⏳ 将近生辰倒计时",font=("楷体",14,"bold"),bg=FRAME_COLOR,fg=FONT_COLOR).pack(pady=6)
count_label = tk.Label(down_frame,text="",font=("楷体",11),bg=FRAME_COLOR,fg=FONT_COLOR,wraplength=470)
count_label.pack(pady=5)

def update_count_down():
    now = datetime.now()
    year = now.year
    data_arr = []
    for item in birth_list:
        try:
            m, d = map(int,item["date"].split("-"))
            aim_day = datetime(year,m,d)
            days_gap = (aim_day - now).days
            if days_gap < 0:
                aim_day = datetime(year+1,m,d)
                days_gap = (aim_day - now).days
            data_arr.append((days_gap,item["name"],item["date"]))
        except Exception:
            continue
    data_arr.sort(key=lambda x:x[0])
    text_out = ""
    for t,name,bd in data_arr[:6]:
        text_out += f"▪ {name} 生辰{bd}，尚有{t}天\n"
    if text_out == "":
        text_out = "笺录暂无生辰，请录入亲友生辰"
    count_label.config(text=text_out)

def auto_refresh():
    update_count_down()
    win.after(60000,auto_refresh)

# 程序启动执行
check_today_birthday()
update_count_down()
auto_refresh()

win.mainloop()