import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
from tkinter import *
from calendar import monthrange
import json
import os
from datetime import datetime

# 数据文件路径（自动保存在当前目录下）
DATA_FILE = "plan_data.json"

class CalendarApp:
    def __init__(self, root):
        self.root = root
        self.root.title("日历提醒与计划表")
        self.root.geometry("650x500")
        
        # 加载保存的计划数据
        self.plans = self.load_plans()
        
        # 获取当前日期
        self.now = datetime.now()
        self.current_year = self.now.year
        self.current_month = self.now.month
        self.current_day = self.now.day
        
        # 选中的日期
        self.selected_date = f"{self.current_year}-{self.current_month:02d}-{self.current_day:02d}"
        
        # 创建界面
        self.create_widgets()
        # 刷新日历和计划
        self.refresh_calendar()
        self.refresh_plan_list()

    def load_plans(self):
        """加载本地保存的计划数据"""
        if os.path.exists(DATA_FILE):
            with open(DATA_FILE, "r", encoding="utf-8") as f:
                return json.load(f)
        return {}

    def save_plans(self):
        """保存计划到本地文件"""
        with open(DATA_FILE, "w", encoding="utf-8") as f:
            json.dump(self.plans, f, ensure_ascii=False, indent=2)

    def create_widgets(self):
        """创建所有界面组件"""
        # 顶部：年月切换
        top_frame = Frame(self.root)
        top_frame.pack(pady=10)
        
        self.year_label = Label(top_frame, text=f"{self.current_year}年{self.current_month}月", font=("黑体", 14))
        self.year_label.grid(row=0, column=1, padx=20)
        
        Button(top_frame, text="上个月", command=self.last_month).grid(row=0, column=0)
        Button(top_frame, text="下个月", command=self.next_month).grid(row=0, column=2)
        Button(top_frame, text="今天", command=self.go_today).grid(row=0, column=3, padx=10)

        # 日历主体
        self.calendar_frame = Frame(self.root)
        self.calendar_frame.pack(pady=5)

        # 右侧：计划区域
        right_frame = Frame(self.root)
        right_frame.pack(pady=10, fill=BOTH, expand=True)

        # 选中日期显示
        self.date_show = Label(right_frame, text=f"当前选择：{self.selected_date}", font=("黑体", 12))
        self.date_show.pack()

        # 计划列表
        self.plan_list = Listbox(right_frame, width=60, height=8, font=("黑体", 11))
        self.plan_list.pack(pady=5)

        # 按钮组
        btn_frame = Frame(right_frame)
        btn_frame.pack()
        Button(btn_frame, text="添加计划", command=self.add_plan, width=10).grid(row=0, column=0, padx=5)
        Button(btn_frame, text="删除选中", command=self.delete_plan, width=10).grid(row=0, column=1, padx=5)
        Button(btn_frame, text="查看提醒", command=self.check_remind, width=10).grid(row=0, column=2, padx=5)

    def refresh_calendar(self):
        """刷新日历显示"""
        # 清空旧日历
        for widget in self.calendar_frame.winfo_children():
            widget.destroy()

        # 头部星期
        weeks = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
        for col, week in enumerate(weeks):
            Label(self.calendar_frame, text=week, width=8, fg="blue").grid(row=0, column=col)

        # 获取当月第一天是周几 & 当月天数
        first_weekday, days = monthrange(self.current_year, self.current_month)
        
        # 修正周一为一周第一天
        first_weekday = first_weekday - 1 if first_weekday > 0 else 6

        row = 1
        col = first_weekday

        # 绘制日期
        for day in range(1, days + 1):
            date_str = f"{self.current_year}-{self.current_month:02d}-{day:02d}"
            is_today = (day == self.current_day and self.current_month == self.now.month and self.current_year == self.now.year)
            
            btn = Button(
                self.calendar_frame, text=str(day), width=6,
                command=lambda d=day: self.select_date(d)
            )
            
            if is_today:
                btn.config(bg="#90EE90")  # 今天绿色
            
            if date_str == self.selected_date:
                btn.config(bg="#87CEEB")  # 选中蓝色
                
            btn.grid(row=row, column=col)

            col += 1
            if col > 6:
                col = 0
                row += 1

        self.year_label.config(text=f"{self.current_year}年{self.current_month}月")

    def select_date(self, day):
        """选择日期"""
        self.selected_date = f"{self.current_year}-{self.current_month:02d}-{day:02d}"
        self.date_show.config(text=f"当前选择：{self.selected_date}")
        self.refresh_calendar()
        self.refresh_plan_list()

    def last_month(self):
        """上个月"""
        self.current_month -= 1
        if self.current_month < 1:
            self.current_month = 12
            self.current_year -= 1
        self.refresh_calendar()

    def next_month(self):
        """下个月"""
        self.current_month += 1
        if self.current_month > 12:
            self.current_month = 1
            self.current_year += 1
        self.refresh_calendar()

    def go_today(self):
        """回到今天"""
        self.current_year = self.now.year
        self.current_month = self.now.month
        self.selected_date = f"{self.current_year}-{self.current_month:02d}-{self.current_day:02d}"
        self.refresh_calendar()
        self.refresh_plan_list()

    def refresh_plan_list(self):
        """刷新当前日期的计划列表"""
        self.plan_list.delete(0, END)
        if self.selected_date in self.plans:
            for plan in self.plans[self.selected_date]:
                self.plan_list.insert(END, plan)

    def add_plan(self):
        """添加计划"""
        content = simpledialog.askstring("添加计划", "请输入计划内容：")
        if content and content.strip():
            if self.selected_date not in self.plans:
                self.plans[self.selected_date] = []
            self.plans[self.selected_date].append(content.strip())
            self.save_plans()
            self.refresh_plan_list()
            messagebox.showinfo("成功", "计划添加成功！")

    def delete_plan(self):
        """删除选中的计划"""
        index = self.plan_list.curselection()
        if not index:
            messagebox.showwarning("提示", "请先选择要删除的计划")
            return
        del self.plans[self.selected_date][index[0]]
        self.save_plans()
        self.refresh_plan_list()
        messagebox.showinfo("成功", "计划已删除")

    def check_remind(self):
        """查看当天提醒"""
        today = f"{self.now.year}-{self.now.month:02d}-{self.now.day:02d}"
        if today not in self.plans or len(self.plans[today]) == 0:
            messagebox.showinfo("提醒", "今天没有待办计划")
            return
        
        remind_text = "今日待办：\n"
        for i, plan in enumerate(self.plans[today], 1):
            remind_text += f"{i}. {plan}\n"
        messagebox.showinfo("今日提醒", remind_text)

# 运行程序
if __name__ == "__main__":
    root = tk.Tk()
    app = CalendarApp(root)
    root.mainloop()