import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, filedialog, font
import json
import os
from datetime import datetime
import webbrowser
from PIL import Image, ImageTk
import random

class TangPoetryApp:
    def __init__(self, root):
        self.root = root
        self.root.title("唐诗三百首 - 电子书阅读器")
        self.root.geometry("1000x700")
        self.root.configure(bg='#f5f5f0')
        
        # 设置图标
        try:
            self.root.iconbitmap(default='poetry_icon.ico')
        except:
            pass
        
        # 加载唐诗数据
        self.poems = self.load_poems()
        self.authors = self.get_authors()
        self.dynasties = ["全部", "初唐", "盛唐", "中唐", "晚唐"]
        self.themes = ["全部", "山水田园", "送别怀人", "边塞战争", "爱情闺怨", "咏史怀古", "咏物言志"]
        
        # 当前显示的诗歌
        self.current_poem_index = 0
        self.filtered_poems = self.poems.copy()
        
        # 创建GUI
        self.setup_gui()
        
        # 显示第一首诗
        self.show_poem(0)
        
    def load_poems(self):
        """加载唐诗数据"""
        # 这里使用内置的示例数据，实际可以连接数据库或API
        poems = [
            {
                "id": 1,
                "title": "静夜思",
                "author": "李白",
                "dynasty": "盛唐",
                "content": "床前明月光，疑是地上霜。\n举头望明月，低头思故乡。",
                "annotation": "此诗描写了秋日夜晚，旅居在外的诗人于屋内抬头望月的所感。诗中运用比喻、衬托等手法，表达客居思乡之情。",
                "theme": "思乡怀人"
            },
            {
                "id": 2,
                "title": "春晓",
                "author": "孟浩然",
                "dynasty": "盛唐",
                "content": "春眠不觉晓，处处闻啼鸟。\n夜来风雨声，花落知多少。",
                "annotation": "诗人抓住春天的早晨刚刚醒来时的一瞬间展开描写和联想，生动地表达了诗人对春天的热爱和怜惜之情。",
                "theme": "山水田园"
            },
            {
                "id": 3,
                "title": "登鹳雀楼",
                "author": "王之涣",
                "dynasty": "盛唐",
                "content": "白日依山尽，黄河入海流。\n欲穷千里目，更上一层楼。",
                "annotation": "此诗前两句写的是自然景色，后两句写意，把哲理与景物、情势溶化得天衣无缝。",
                "theme": "登高望远"
            },
            {
                "id": 4,
                "title": "相思",
                "author": "王维",
                "dynasty": "盛唐",
                "content": "红豆生南国，春来发几枝。\n愿君多采撷，此物最相思。",
                "annotation": "此诗借咏物而寄相思，全诗情调健美高雅，怀思饱满奔放，语言朴素无华，韵律和谐柔美。",
                "theme": "爱情闺怨"
            },
            {
                "id": 5,
                "title": "望庐山瀑布",
                "author": "李白",
                "dynasty": "盛唐",
                "content": "日照香炉生紫烟，遥看瀑布挂前川。\n飞流直下三千尺，疑是银河落九天。",
                "annotation": "这首诗形象地描绘了庐山瀑布雄奇壮丽的景色，反映了诗人对祖国大好河山的无限热爱。",
                "theme": "山水田园"
            },
            {
                "id": 6,
                "title": "凉州词",
                "author": "王翰",
                "dynasty": "盛唐",
                "content": "葡萄美酒夜光杯，欲饮琵琶马上催。\n醉卧沙场君莫笑，古来征战几人回。",
                "annotation": "此诗是咏边塞情景之名篇，全诗写艰苦荒凉的边塞的一次盛宴，描摹了征人们开怀痛饮、尽情酣醉的场面。",
                "theme": "边塞战争"
            },
            {
                "id": 7,
                "title": "江雪",
                "author": "柳宗元",
                "dynasty": "中唐",
                "content": "千山鸟飞绝，万径人踪灭。\n孤舟蓑笠翁，独钓寒江雪。",
                "annotation": "诗人用具体而细致的手法来摹写背景，用远距离画面来描写主要形象，精雕细琢和极度的夸张概括，错综地统一在一首诗里。",
                "theme": "山水田园"
            },
            {
                "id": 8,
                "title": "黄鹤楼送孟浩然之广陵",
                "author": "李白",
                "dynasty": "盛唐",
                "content": "故人西辞黄鹤楼，烟花三月下扬州。\n孤帆远影碧空尽，唯见长江天际流。",
                "annotation": "这首诗不同于王勃《送杜少府之任蜀州》那种少年刚肠的离别，也不同于王维《渭城曲》那种深情体贴的离别。",
                "theme": "送别怀人"
            },
            {
                "id": 9,
                "title": "出塞",
                "author": "王昌龄",
                "dynasty": "盛唐",
                "content": "秦时明月汉时关，万里长征人未还。\n但使龙城飞将在，不教胡马度阴山。",
                "annotation": "诗人从写景入手，首句勾勒出一幅冷月照边关的苍凉景象，表达了诗人希望起任良将，早日平息边塞战事，使人民过上安定的生活的愿望。",
                "theme": "边塞战争"
            },
            {
                "id": 10,
                "title": "枫桥夜泊",
                "author": "张继",
                "dynasty": "中唐",
                "content": "月落乌啼霜满天，江枫渔火对愁眠。\n姑苏城外寒山寺，夜半钟声到客船。",
                "annotation": "此诗精确而细腻地描述了一个客船夜泊者对江南深秋夜景的观察和感受，勾画了月落乌啼、霜天寒夜、江枫渔火、孤舟客子等景象。",
                "theme": "羁旅愁思"
            }
        ]
        return poems
    
    def get_authors(self):
        """获取所有作者"""
        authors_set = set()
        for poem in self.poems:
            authors_set.add(poem["author"])
        return ["全部"] + sorted(list(authors_set))
    
    def setup_gui(self):
        """设置图形用户界面"""
        # 设置字体
        self.title_font = font.Font(family="楷体", size=16, weight="bold")
        self.content_font = font.Font(family="宋体", size=12)
        self.annotation_font = font.Font(family="宋体", size=10, slant="italic")
        
        # 创建主框架
        main_frame = tk.Frame(self.root, bg='#f5f5f0')
        main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 顶部标题栏
        title_frame = tk.Frame(main_frame, bg='#8B4513')
        title_frame.pack(fill=tk.X, pady=(0, 10))
        
        title_label = tk.Label(title_frame, 
                              text="唐诗三百首电子书", 
                              font=("楷体", 20, "bold"),
                              fg='white',
                              bg='#8B4513',
                              pady=10)
        title_label.pack()
        
        # 副标题
        subtitle_label = tk.Label(title_frame,
                                 text="丙午马年制作",
                                 font=("宋体", 10),
                                 fg='#F5DEB3',
                                 bg='#8B4513')
        subtitle_label.pack()
        
        # 主内容区域
        content_frame = tk.Frame(main_frame, bg='#f5f5f0')
        content_frame.pack(fill=tk.BOTH, expand=True)
        
        # 左侧控制面板
        control_panel = tk.Frame(content_frame, bg='#F5DEB3', relief=tk.RAISED, bd=2)
        control_panel.pack(side=tk.LEFT, fill=tk.Y, padx=(0, 10))
        
        # 搜索和筛选区域
        filter_frame = tk.LabelFrame(control_panel, text="搜索和筛选", 
                                    font=("宋体", 10, "bold"),
                                    bg='#F5DEB3',
                                    padx=10, pady=10)
        filter_frame.pack(fill=tk.X, padx=10, pady=10)
        
        # 搜索框
        tk.Label(filter_frame, text="搜索:", bg='#F5DEB3').pack(anchor=tk.W)
        self.search_var = tk.StringVar()
        self.search_var.trace("w", self.on_search_change)
        search_entry = tk.Entry(filter_frame, textvariable=self.search_var, width=20)
        search_entry.pack(fill=tk.X, pady=(0, 10))
        
        # 作者筛选
        tk.Label(filter_frame, text="选择作者:", bg='#F5DEB3').pack(anchor=tk.W)
        self.author_var = tk.StringVar(value="全部")
        author_combo = ttk.Combobox(filter_frame, textvariable=self.author_var, 
                                   values=self.authors, state="readonly", width=18)
        author_combo.pack(fill=tk.X, pady=(0, 10))
        author_combo.bind("<<ComboboxSelected>>", self.on_filter_change)
        
        # 朝代筛选
        tk.Label(filter_frame, text="选择朝代:", bg='#F5DEB3').pack(anchor=tk.W)
        self.dynasty_var = tk.StringVar(value="全部")
        dynasty_combo = ttk.Combobox(filter_frame, textvariable=self.dynasty_var,
                                    values=self.dynasties, state="readonly", width=18)
        dynasty_combo.pack(fill=tk.X, pady=(0, 10))
        dynasty_combo.bind("<<ComboboxSelected>>", self.on_filter_change)
        
        # 主题筛选
        tk.Label(filter_frame, text="选择主题:", bg='#F5DEB3').pack(anchor=tk.W)
        self.theme_var = tk.StringVar(value="全部")
        theme_combo = ttk.Combobox(filter_frame, textvariable=self.theme_var,
                                  values=self.themes, state="readonly", width=18)
        theme_combo.pack(fill=tk.X, pady=(0, 10))
        theme_combo.bind("<<ComboboxSelected>>", self.on_filter_change)
        
        # 功能按钮区域
        button_frame = tk.Frame(control_panel, bg='#F5DEB3')
        button_frame.pack(fill=tk.X, padx=10, pady=10)
        
        # 创建功能按钮
        buttons = [
            ("随机一首", self.random_poem, "#8B4513"),
            ("导出文本", self.export_text, "#2E8B57"),
            ("导出HTML", self.export_html, "#4682B4"),
            ("关于", self.show_about, "#708090"),
            ("退出", self.root.quit, "#8B0000")
        ]
        
        for text, command, color in buttons:
            btn = tk.Button(button_frame, text=text, command=command,
                           bg=color, fg='white', font=("宋体", 10),
                           width=15, height=1, relief=tk.RAISED)
            btn.pack(pady=5)
        
        # 右侧诗歌显示区域
        display_frame = tk.Frame(content_frame, bg='white', relief=tk.SUNKEN, bd=2)
        display_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        # 诗歌标题
        self.title_label = tk.Label(display_frame, 
                                   font=self.title_font,
                                   fg='#8B4513',
                                   bg='white',
                                   pady=10)
        self.title_label.pack()
        
        # 作者和朝代信息
        info_frame = tk.Frame(display_frame, bg='white')
        info_frame.pack()
        
        self.author_label = tk.Label(info_frame, 
                                    font=("宋体", 12),
                                    fg='#2F4F4F',
                                    bg='white')
        self.author_label.pack(side=tk.LEFT, padx=20)
        
        self.dynasty_label = tk.Label(info_frame,
                                     font=("宋体", 12),
                                     fg='#2F4F4F',
                                     bg='white')
        self.dynasty_label.pack(side=tk.LEFT, padx=20)
        
        self.theme_label = tk.Label(info_frame,
                                   font=("宋体", 12),
                                   fg='#2F4F4F',
                                   bg='white')
        self.theme_label.pack(side=tk.LEFT, padx=20)
        
        # 分隔线
        separator = ttk.Separator(display_frame, orient='horizontal')
        separator.pack(fill=tk.X, padx=20, pady=10)
        
        # 诗歌内容显示区域
        content_label_frame = tk.Frame(display_frame, bg='white')
        content_label_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 使用Text控件显示诗歌内容，以便更好的格式化
        self.content_text = tk.Text(content_label_frame,
                                   font=self.content_font,
                                   fg='#2F4F4F',
                                   bg='white',
                                   wrap=tk.WORD,
                                   height=8,
                                   relief=tk.FLAT)
        self.content_text.pack(fill=tk.BOTH, expand=True)
        
        # 禁用编辑
        self.content_text.config(state=tk.DISABLED)
        
        # 分隔线
        separator2 = ttk.Separator(display_frame, orient='horizontal')
        separator2.pack(fill=tk.X, padx=20, pady=10)
        
        # 诗歌注释区域
        annotation_label = tk.Label(display_frame, 
                                   text="诗歌赏析：",
                                   font=("宋体", 11, "bold"),
                                   fg='#8B4513',
                                   bg='white',
                                   anchor=tk.W)
        annotation_label.pack(anchor=tk.W, padx=20)
        
        self.annotation_text = tk.Text(display_frame,
                                      font=self.annotation_font,
                                      fg='#696969',
                                      bg='#FAF0E6',
                                      wrap=tk.WORD,
                                      height=4,
                                      relief=tk.SUNKEN,
                                      bd=1)
        self.annotation_text.pack(fill=tk.X, padx=20, pady=(5, 20))
        self.annotation_text.config(state=tk.DISABLED)
        
        # 底部导航栏
        nav_frame = tk.Frame(display_frame, bg='white')
        nav_frame.pack(fill=tk.X, padx=20, pady=10)
        
        # 导航按钮
        nav_buttons = [
            ("首页", self.first_poem),
            ("上一首", self.prev_poem),
            ("下一首", self.next_poem),
            ("末页", self.last_poem)
        ]
        
        for text, command in nav_buttons:
            btn = tk.Button(nav_frame, text=text, command=command,
                          bg='#8B4513', fg='white',
                          font=("宋体", 10),
                          width=8, height=1)
            btn.pack(side=tk.LEFT, padx=5)
        
        # 状态信息
        self.status_label = tk.Label(nav_frame,
                                    text="",
                                    font=("宋体", 9),
                                    fg='#696969',
                                    bg='white')
        self.status_label.pack(side=tk.RIGHT)
        
        # 状态栏
        self.status_bar = tk.Label(main_frame,
                                  text=f"唐诗三百首电子书 | 当前诗歌: 1/{len(self.poems)} | 丙午马年",
                                  bd=1,
                                  relief=tk.SUNKEN,
                                  anchor=tk.W,
                                  font=("宋体", 9),
                                  bg='#F5DEB3',
                                  fg='#8B4513')
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
    def on_search_change(self, *args):
        """搜索内容变化时的处理"""
        self.filter_poems()
        
    def on_filter_change(self, *args):
        """筛选条件变化时的处理"""
        self.filter_poems()
        
    def filter_poems(self):
        """根据筛选条件过滤诗歌"""
        search_text = self.search_var.get().lower()
        selected_author = self.author_var.get()
        selected_dynasty = self.dynasty_var.get()
        selected_theme = self.theme_var.get()
        
        self.filtered_poems = []
        for poem in self.poems:
            # 搜索条件
            matches_search = (not search_text or 
                            search_text in poem['title'].lower() or 
                            search_text in poem['author'].lower() or
                            search_text in poem['content'].lower() or
                            search_text in poem.get('annotation', '').lower())
            
            # 作者条件
            matches_author = (selected_author == "全部" or poem['author'] == selected_author)
            
            # 朝代条件
            matches_dynasty = (selected_dynasty == "全部" or poem['dynasty'] == selected_dynasty)
            
            # 主题条件
            matches_theme = (selected_theme == "全部" or selected_theme in poem.get('theme', ''))
            
            if matches_search and matches_author and matches_dynasty and matches_theme:
                self.filtered_poems.append(poem)
        
        # 重置当前索引
        self.current_poem_index = 0
        
        # 更新状态
        if self.filtered_poems:
            self.show_poem(0)
        else:
            self.show_no_results()
    
    def show_no_results(self):
        """显示无结果"""
        self.title_label.config(text="未找到诗歌")
        self.author_label.config(text="")
        self.dynasty_label.config(text="")
        self.theme_label.config(text="")
        
        # 清空内容
        self.content_text.config(state=tk.NORMAL)
        self.content_text.delete(1.0, tk.END)
        self.content_text.config(state=tk.DISABLED)
        
        # 清空注释
        self.annotation_text.config(state=tk.NORMAL)
        self.annotation_text.delete(1.0, tk.END)
        self.annotation_text.config(state=tk.DISABLED)
        
        # 更新状态
        self.status_label.config(text="无结果")
        self.status_bar.config(text=f"唐诗三百首电子书 | 搜索结果: 0 | 丙午马年")
    
    def show_poem(self, index):
        """显示指定索引的诗歌"""
        if not self.filtered_poems:
            self.show_no_results()
            return
            
        if index < 0:
            index = 0
        elif index >= len(self.filtered_poems):
            index = len(self.filtered_poems) - 1
            
        poem = self.filtered_poems[index]
        self.current_poem_index = index
        
        # 更新标题
        self.title_label.config(text=f"《{poem['title']}》")
        
        # 更新作者和朝代
        self.author_label.config(text=f"作者: {poem['author']}")
        self.dynasty_label.config(text=f"朝代: {poem['dynasty']}")
        self.theme_label.config(text=f"主题: {poem.get('theme', '无')}")
        
        # 更新诗歌内容
        self.content_text.config(state=tk.NORMAL)
        self.content_text.delete(1.0, tk.END)
        
        # 居中对齐诗歌内容
        lines = poem['content'].split('\n')
        for line in lines:
            # 在Text控件中居中显示
            self.content_text.insert(tk.END, line.center(30) + '\n')
        
        # 设置居中对齐
        self.content_text.tag_add("center", "1.0", "end")
        self.content_text.tag_configure("center", justify='center')
        
        self.content_text.config(state=tk.DISABLED)
        
        # 更新注释
        self.annotation_text.config(state=tk.NORMAL)
        self.annotation_text.delete(1.0, tk.END)
        self.annotation_text.insert(tk.END, poem.get('annotation', '暂无注释'))
        self.annotation_text.config(state=tk.DISABLED)
        
        # 更新状态
        self.status_label.config(text=f"第 {index + 1}/{len(self.filtered_poems)} 首")
        self.status_bar.config(text=f"唐诗三百首电子书 | 当前诗歌: {index + 1}/{len(self.filtered_poems)} | 丙午马年")
    
    def first_poem(self):
        """显示第一首诗歌"""
        self.show_poem(0)
    
    def prev_poem(self):
        """显示上一首诗歌"""
        self.show_poem(self.current_poem_index - 1)
    
    def next_poem(self):
        """显示下一首诗歌"""
        self.show_poem(self.current_poem_index + 1)
    
    def last_poem(self):
        """显示最后一首诗歌"""
        self.show_poem(len(self.filtered_poems) - 1)
    
    def random_poem(self):
        """随机选择一首诗歌"""
        if self.filtered_poems:
            random_index = random.randint(0, len(self.filtered_poems) - 1)
            self.show_poem(random_index)
    
    def export_text(self):
        """导出当前诗歌列表为文本文件"""
        if not self.filtered_poems:
            messagebox.showwarning("警告", "没有诗歌可导出！")
            return
            
        filename = filedialog.asksaveasfilename(
            defaultextension=".txt",
            filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")],
            initialfile="唐诗三百首.txt"
        )
        
        if filename:
            try:
                with open(filename, 'w', encoding='utf-8') as f:
                    f.write("="*50 + "\n")
                    f.write("            唐诗三百首\n")
                    f.write("="*50 + "\n\n")
                    f.write(f"生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                    f.write(f"农历: 丙午马年\n")
                    f.write(f"筛选条件: ")
                    
                    # 写入筛选条件
                    conditions = []
                    if self.author_var.get() != "全部":
                        conditions.append(f"作者: {self.author_var.get()}")
                    if self.dynasty_var.get() != "全部":
                        conditions.append(f"朝代: {self.dynasty_var.get()}")
                    if self.theme_var.get() != "全部":
                        conditions.append(f"主题: {self.theme_var.get()}")
                    if self.search_var.get():
                        conditions.append(f"搜索: {self.search_var.get()}")
                    
                    if conditions:
                        f.write(" | ".join(conditions) + "\n")
                    else:
                        f.write("全部诗歌\n")
                    
                    f.write(f"诗歌数量: {len(self.filtered_poems)} 首\n\n")
                    
                    # 写入诗歌
                    for i, poem in enumerate(self.filtered_poems, 1):
                        f.write(f"{i}. 《{poem['title']}》\n")
                        f.write(f"   作者: {poem['author']} | 朝代: {poem['dynasty']} | 主题: {poem.get('theme', '无')}\n")
                        f.write("   " + "-"*40 + "\n")
                        f.write(f"   {poem['content'].replace(chr(10), chr(10) + '   ')}\n")
                        f.write("\n   赏析:\n")
                        f.write(f"   {poem.get('annotation', '暂无注释')}\n")
                        f.write("\n" + "="*50 + "\n\n")
                
                messagebox.showinfo("导出成功", f"诗歌已成功导出到:\n{filename}")
                
            except Exception as e:
                messagebox.showerror("导出失败", f"导出失败: {str(e)}")
    
    def export_html(self):
        """导出当前诗歌列表为HTML文件"""
        if not self.filtered_poems:
            messagebox.showwarning("警告", "没有诗歌可导出！")
            return
            
        filename = filedialog.asksaveasfilename(
            defaultextension=".html",
            filetypes=[("HTML文件", "*.html"), ("所有文件", "*.*")],
            initialfile="唐诗三百首.html"
        )
        
        if filename:
            try:
                html_content = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>唐诗三百首</title>
    <style>
        body {{
            font-family: 'SimSun', 'STSong', serif;
            line-height: 1.6;
            background-color: #f5f5f0;
            color: #333;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }}
        
        .header {{
            text-align: center;
            margin-bottom: 40px;
            border-bottom: 3px solid #8B4513;
            padding-bottom: 20px;
        }}
        
        h1 {{
            color: #8B4513;
            font-size: 2.5em;
            margin-bottom: 10px;
        }}
        
        .meta-info {{
            color: #666;
            font-size: 0.9em;
            margin-bottom: 20px;
        }}
        
        .filter-info {{
            background-color: #F5DEB3;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }}
        
        .poem {{
            margin-bottom: 40px;
            padding: 20px;
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }}
        
        .poem-title {{
            color: #8B4513;
            font-size: 1.5em;
            text-align: center;
            margin-bottom: 10px;
        }}
        
        .poem-meta {{
            text-align: center;
            color: #666;
            margin-bottom: 20px;
        }}
        
        .poem-content {{
            font-size: 1.2em;
            line-height: 2;
            text-align: center;
            white-space: pre-wrap;
            margin-bottom: 20px;
            padding: 20px;
            background-color: #FAF0E6;
            border-radius: 5px;
        }}
        
        .annotation {{
            font-style: italic;
            color: #696969;
            padding: 15px;
            background-color: #F8F8F8;
            border-left: 4px solid #8B4513;
        }}
        
        .footer {{
            text-align: center;
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
            color: #666;
            font-size: 0.9em;
        }}
        
        .poem-number {{
            font-size: 0.8em;
            color: #8B4513;
            margin-right: 10px;
        }}
    </style>
</head>
<body>
    <div class="header">
        <h1>唐诗三百首</h1>
        <div class="meta-info">
            生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | 农历: 丙午马年
        </div>
'''
                
                # 添加筛选条件
                conditions = []
                if self.author_var.get() != "全部":
                    conditions.append(f"作者: {self.author_var.get()}")
                if self.dynasty_var.get() != "全部":
                    conditions.append(f"朝代: {self.dynasty_var.get()}")
                if self.theme_var.get() != "全部":
                    conditions.append(f"主题: {self.theme_var.get()}")
                if self.search_var.get():
                    conditions.append(f"搜索: {self.search_var.get()}")
                
                if conditions:
                    html_content += f'''
        <div class="filter-info">
            筛选条件: {" | ".join(conditions)}<br>
            诗歌数量: {len(self.filtered_poems)} 首
        </div>'''
                else:
                    html_content += f'''
        <div class="filter-info">
            全部诗歌 | 诗歌数量: {len(self.filtered_poems)} 首
        </div>'''
                
                html_content += '''
    </div>'''
                
                # 添加诗歌
                for i, poem in enumerate(self.filtered_poems, 1):
                    # 处理换行
                    content_html = poem['content'].replace('\n', '<br>')
                    
                    html_content += f'''
    <div class="poem">
        <div class="poem-title">
            <span class="poem-number">{i}.</span>
            《{poem['title']}》
        </div>
        <div class="poem-meta">
            作者: {poem['author']} | 朝代: {poem['dynasty']} | 主题: {poem.get('theme', '无')}
        </div>
        <div class="poem-content">
            {content_html}
        </div>
        <div class="annotation">
            <strong>赏析：</strong>{poem.get('annotation', '暂无注释')}
        </div>
    </div>'''
                
                # 添加页脚
                html_content += f'''
    <div class="footer">
        唐诗三百首电子书 | 使用Python生成 | 丙午马年制作
    </div>
</body>
</html>'''
                
                with open(filename, 'w', encoding='utf-8') as f:
                    f.write(html_content)
                
                messagebox.showinfo("导出成功", f"HTML文件已成功导出到:\n{filename}")
                
                # 询问是否打开文件
                if messagebox.askyesno("打开文件", "是否要现在打开导出的HTML文件？"):
                    webbrowser.open('file://' + os.path.abspath(filename))
                
            except Exception as e:
                messagebox.showerror("导出失败", f"导出失败: {str(e)}")
    
    def show_about(self):
        """显示关于信息"""
        about_text = f"""唐诗三百首电子书阅读器

版本: 1.0
作者: Python开发团队
日期: {datetime.now().strftime('%Y年%m月%d日')}
农历: 丙午马年

功能说明:
1. 浏览唐诗三百首
2. 按作者、朝代、主题筛选
3. 搜索诗歌内容
4. 导出为文本和HTML格式
5. 随机阅读诗歌

数据说明:
内置了10首经典唐诗作为示例。
如需完整数据，可以连接到唐诗数据库API。

祝您阅读愉快！"""
        
        messagebox.showinfo("关于", about_text)

# 创建主窗口
if __name__ == "__main__":
    root = tk.Tk()
    app = TangPoetryApp(root)
    root.mainloop()