import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext

class TangPoetryApp:
    def __init__(self, root):
        self.root = root
        self.root.title("唐诗三百首")
        self.root.geometry("800x600")
        self.root.minsize(700, 500)
        
        # 当前选中的诗歌
        self.current_poem = None
        self.favorites = set()
        
        # 唐诗数据
        self.poems = self.get_tang_poems()
        
        # 创建界面
        self.create_widgets()
        
    def get_tang_poems(self):
        """获取唐诗数据"""
        poems = [
            {
                "id": 1,
                "title": "静夜思",
                "author": "李白",
                "dynasty": "唐",
                "category": "思乡",
                "content": "床前明月光，疑是地上霜。\n举头望明月，低头思故乡。"
            },
            {
                "id": 2,
                "title": "春晓",
                "author": "孟浩然",
                "dynasty": "唐",
                "category": "山水",
                "content": "春眠不觉晓，处处闻啼鸟。\n夜来风雨声，花落知多少。"
            },
            {
                "id": 3,
                "title": "登鹳雀楼",
                "author": "王之涣",
                "dynasty": "唐",
                "category": "登高",
                "content": "白日依山尽，黄河入海流。\n欲穷千里目，更上一层楼。"
            },
            {
                "id": 4,
                "title": "相思",
                "author": "王维",
                "dynasty": "唐",
                "category": "爱情",
                "content": "红豆生南国，春来发几枝。\n愿君多采撷，此物最相思。"
            },
            {
                "id": 5,
                "title": "望庐山瀑布",
                "author": "李白",
                "dynasty": "唐",
                "category": "山水",
                "content": "日照香炉生紫烟，遥看瀑布挂前川。\n飞流直下三千尺，疑是银河落九天。"
            },
            {
                "id": 6,
                "title": "江雪",
                "author": "柳宗元",
                "dynasty": "唐",
                "category": "山水",
                "content": "千山鸟飞绝，万径人踪灭。\n孤舟蓑笠翁，独钓寒江雪。"
            },
            {
                "id": 7,
                "title": "悯农",
                "author": "李绅",
                "dynasty": "唐",
                "category": "咏物",
                "content": "锄禾日当午，汗滴禾下土。\n谁知盘中餐，粒粒皆辛苦。"
            },
            {
                "id": 8,
                "title": "咏鹅",
                "author": "骆宾王",
                "dynasty": "唐",
                "category": "咏物",
                "content": "鹅，鹅，鹅，曲项向天歌。\n白毛浮绿水，红掌拨清波。"
            },
            {
                "id": 9,
                "title": "枫桥夜泊",
                "author": "张继",
                "dynasty": "唐",
                "category": "羁旅",
                "content": "月落乌啼霜满天，江枫渔火对愁眠。\n姑苏城外寒山寺，夜半钟声到客船。"
            },
            {
                "id": 10,
                "title": "送元二使安西",
                "author": "王维",
                "dynasty": "唐",
                "category": "送别",
                "content": "渭城朝雨浥轻尘，客舍青青柳色新。\n劝君更尽一杯酒，西出阳关无故人。"
            },
            {
                "id": 11,
                "title": "黄鹤楼送孟浩然之广陵",
                "author": "李白",
                "dynasty": "唐",
                "category": "送别",
                "content": "故人西辞黄鹤楼，烟花三月下扬州。\n孤帆远影碧空尽，唯见长江天际流。"
            },
            {
                "id": 12,
                "title": "早发白帝城",
                "author": "李白",
                "dynasty": "唐",
                "category": "山水",
                "content": "朝辞白帝彩云间，千里江陵一日还。\n两岸猿声啼不住，轻舟已过万重山。"
            },
            {
                "id": 13,
                "title": "凉州词",
                "author": "王翰",
                "dynasty": "唐",
                "category": "边塞",
                "content": "葡萄美酒夜光杯，欲饮琵琶马上催。\n醉卧沙场君莫笑，古来征战几人回。"
            },
            {
                "id": 14,
                "title": "出塞",
                "author": "王昌龄",
                "dynasty": "唐",
                "category": "边塞",
                "content": "秦时明月汉时关，万里长征人未还。\n但使龙城飞将在，不教胡马度阴山。"
            },
            {
                "id": 15,
                "title": "芙蓉楼送辛渐",
                "author": "王昌龄",
                "dynasty": "唐",
                "category": "送别",
                "content": "寒雨连江夜入吴，平明送客楚山孤。\n洛阳亲友如相问，一片冰心在玉壶。"
            },
            {
                "id": 16,
                "title": "九月九日忆山东兄弟",
                "author": "王维",
                "dynasty": "唐",
                "category": "思乡",
                "content": "独在异乡为异客，每逢佳节倍思亲。\n遥知兄弟登高处，遍插茱萸少一人。"
            },
            {
                "id": 17,
                "title": "滁州西涧",
                "author": "韦应物",
                "dynasty": "唐",
                "category": "山水",
                "content": "独怜幽草涧边生，上有黄鹂深树鸣。\n春潮带雨晚来急，野渡无人舟自横。"
            },
            {
                "id": 18,
                "title": "游子吟",
                "author": "孟郊",
                "dynasty": "唐",
                "category": "亲情",
                "content": "慈母手中线，游子身上衣。\n临行密密缝，意恐迟迟归。\n谁言寸草心，报得三春晖。"
            },
            {
                "id": 19,
                "title": "望天门山",
                "author": "李白",
                "dynasty": "唐",
                "category": "山水",
                "content": "天门中断楚江开，碧水东流至此回。\n两岸青山相对出，孤帆一片日边来。"
            },
            {
                "id": 20,
                "title": "绝句",
                "author": "杜甫",
                "dynasty": "唐",
                "category": "写景",
                "content": "两个黄鹂鸣翠柳，一行白鹭上青天。\n窗含西岭千秋雪，门泊东吴万里船。"
            }
        ]
        return poems
    
    def create_widgets(self):
        """创建界面组件"""
        # 主框架
        main_frame = ttk.Frame(self.root, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 顶部搜索栏
        search_frame = ttk.Frame(main_frame)
        search_frame.pack(fill=tk.X, pady=(0, 10))
        
        ttk.Label(search_frame, text="搜索:").pack(side=tk.LEFT, padx=(0, 5))
        
        self.search_var = tk.StringVar()
        self.search_var.trace("w", self.on_search_change)
        search_entry = ttk.Entry(search_frame, textvariable=self.search_var, width=30)
        search_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
        
        # 分类筛选
        ttk.Label(search_frame, text="分类:").pack(side=tk.LEFT, padx=(0, 5))
        
        categories = ["全部"] + list(set(p["category"] for p in self.poems))
        self.category_var = tk.StringVar(value="全部")
        category_combo = ttk.Combobox(
            search_frame, 
            textvariable=self.category_var, 
            values=categories,
            state="readonly",
            width=12
        )
        category_combo.pack(side=tk.LEFT, padx=(0, 10))
        category_combo.bind("<<ComboboxSelected>>", self.filter_by_category)
        
        # 收藏按钮
        self.favorite_btn = ttk.Button(
            search_frame, 
            text="❤ 收藏", 
            command=self.toggle_favorite,
            state=tk.DISABLED
        )
        self.favorite_btn.pack(side=tk.RIGHT)
        
        # 主内容区
        content_frame = ttk.Frame(main_frame)
        content_frame.pack(fill=tk.BOTH, expand=True)
        
        # 左侧诗歌列表
        list_frame = ttk.LabelFrame(content_frame, text="诗歌列表", padding="5")
        list_frame.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))
        
        # 创建Treeview
        columns = ("id", "title", "author")
        self.poem_tree = ttk.Treeview(
            list_frame, 
            columns=columns, 
            show="headings",
            selectmode="browse"
        )
        
        self.poem_tree.heading("id", text="编号")
        self.poem_tree.heading("title", text="诗名")
        self.poem_tree.heading("author", text="作者")
        
        self.poem_tree.column("id", width=50, anchor=tk.CENTER)
        self.poem_tree.column("title", width=120, anchor=tk.W)
        self.poem_tree.column("author", width=80, anchor=tk.CENTER)
        
        # 滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.poem_tree.yview)
        self.poem_tree.configure(yscrollcommand=scrollbar.set)
        
        self.poem_tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # 绑定选择事件
        self.poem_tree.bind("<<TreeviewSelect>>", self.on_poem_select)
        
        # 右侧诗歌详情
        detail_frame = ttk.LabelFrame(content_frame, text="诗歌详情", padding="10")
        detail_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
        
        # 诗歌标题
        self.title_var = tk.StringVar()
        title_label = ttk.Label(
            detail_frame, 
            textvariable=self.title_var,
            font=("SimHei", 20, "bold")
        )
        title_label.pack(anchor=tk.W, pady=(0, 5))
        
        # 作者和朝代
        self.author_var = tk.StringVar()
        author_label = ttk.Label(
            detail_frame, 
            textvariable=self.author_var,
            font=("SimHei", 14)
        )
        author_label.pack(anchor=tk.W, pady=(0, 10))
        
        # 诗歌内容
        self.content_text = scrolledtext.ScrolledText(
            detail_frame,
            wrap=tk.WORD,
            font=("SimHei", 16),
            bg="#f9f9f9",
            relief=tk.FLAT,
            padx=10,
            pady=10
        )
        self.content_text.pack(fill=tk.BOTH, expand=True)
        self.content_text.config(state=tk.DISABLED)
        
        # 底部状态栏
        status_frame = ttk.Frame(main_frame)
        status_frame.pack(fill=tk.X, pady=(10, 0))
        
        self.status_var = tk.StringVar(value=f"共收录 {len(self.poems)} 首唐诗")
        status_label = ttk.Label(status_frame, textvariable=self.status_var, relief=tk.SUNKEN)
        status_label.pack(fill=tk.X)
        
        # 加载诗歌列表
        self.load_poem_list()
    
    def load_poem_list(self, poems=None):
        """加载诗歌列表到Treeview"""
        if poems is None:
            poems = self.poems
        
        # 清空现有项
        for item in self.poem_tree.get_children():
            self.poem_tree.delete(item)
        
        # 添加诗歌
        for poem in poems:
            is_fav = "★" if poem["id"] in self.favorites else ""
            # 始终将tag存储为字符串，避免类型问题
            self.poem_tree.insert(
                "", 
                tk.END, 
                values=(f"{is_fav}{poem['id']}", poem["title"], poem["author"]),
                tags=(str(poem["id"]),)
            )
        
        self.status_var.set(f"共收录 {len(poems)} 首唐诗")
    
    def on_poem_select(self, event):
        """处理诗歌选择事件 - 最终修复版本"""
        selection = self.poem_tree.selection()
        if not selection:
            return
        
        item = self.poem_tree.item(selection[0])
        tags = item["tags"]
        
        # 最终修复：确保tag是字符串，然后提取数字ID
        if tags and len(tags) > 0:
            tag_str = str(tags[0])  # 强制转换为字符串
            # 移除可能存在的★符号，只保留数字
            clean_tag = tag_str.replace("★", "")
            poem_id = int(clean_tag)
        else:
            return
        
        # 查找诗歌
        for poem in self.poems:
            if poem["id"] == poem_id:
                self.current_poem = poem
                break
        
        if self.current_poem:
            self.display_poem(self.current_poem)
            
            # 更新收藏按钮状态
            if self.current_poem["id"] in self.favorites:
                self.favorite_btn.config(text="💔 取消收藏")
            else:
                self.favorite_btn.config(text="❤ 收藏")
            self.favorite_btn.config(state=tk.NORMAL)
    
    def display_poem(self, poem):
        """显示诗歌详情"""
        self.title_var.set(poem["title"])
        self.author_var.set(f"{poem['dynasty']} · {poem['author']}")
        
        self.content_text.config(state=tk.NORMAL)
        self.content_text.delete(1.0, tk.END)
        self.content_text.insert(tk.END, poem["content"])
        self.content_text.config(state=tk.DISABLED)
    
    def on_search_change(self, *args):
        """搜索文本变化时触发"""
        keyword = self.search_var.get().strip().lower()
        
        if not keyword:
            filtered = self.poems
        else:
            filtered = [
                p for p in self.poems 
                if keyword in p["title"].lower() 
                or keyword in p["author"].lower()
                or keyword in p["content"].lower()
            ]
        
        self.load_poem_list(filtered)
    
    def filter_by_category(self, event=None):
        """按分类筛选"""
        category = self.category_var.get()
        
        if category == "全部":
            filtered = self.poems
        else:
            filtered = [p for p in self.poems if p["category"] == category]
        
        self.load_poem_list(filtered)
    
    def toggle_favorite(self):
        """切换收藏状态"""
        if not self.current_poem:
            return
        
        poem_id = self.current_poem["id"]
        
        if poem_id in self.favorites:
            self.favorites.remove(poem_id)
            self.favorite_btn.config(text="❤ 收藏")
            messagebox.showinfo("提示", "已从收藏中移除")
        else:
            self.favorites.add(poem_id)
            self.favorite_btn.config(text="💔 取消收藏")
            messagebox.showinfo("提示", "已添加到收藏")
        
        # 刷新列表显示
        self.load_poem_list()


def main():
    root = tk.Tk()
    app = TangPoetryApp(root)
    root.mainloop()


if __name__ == "__main__":
    main()