import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import random
import os
import sys
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.units import cm
import json
import math

class MathWorksheetGenerator:
    def __init__(self, root):
        self.root = root
        self.root.title("四年级数学简便运算题生成器")
        self.root.geometry("700x850")
        
        # 题目类型
        self.question_types = {
            "加法结合律(凑整)": "add_associative",
            "乘法交换律和结合律": "mult_commutative_associative", 
            "乘法分配律": "distributive",
            "乘法分配律逆用": "distributive_reverse",
            "连减性质": "subtraction_property",
            "加减混合": "add_sub_mix",
            "特殊乘法(25/125)": "special_multiplication"
        }
        
        # 变量
        self.type_vars = {}
        self.num_questions = tk.IntVar(value=100)
        self.include_answers = tk.BooleanVar(value=True)
        self.shuffle_questions = tk.BooleanVar(value=True)
        self.increase_spacing = tk.BooleanVar(value=False)  # 是否加大间距
        self.show_steps = tk.BooleanVar(value=True)  # 是否显示脱式计算步骤
        self.questions_per_page = 20  # 基础每页题目数，可调整
        
        self.setup_ui()
    
    def setup_ui(self):
        # 标题
        title = tk.Label(self.root, text="四年级数学简便运算题生成器", 
                        font=("微软雅黑", 16, "bold"))
        title.pack(pady=20)
        
        # 框架容器
        main_frame = ttk.Frame(self.root)
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 选择题目数量
        num_frame = ttk.LabelFrame(main_frame, text="题目数量设置", padding=10)
        num_frame.pack(fill=tk.X, pady=10)
        
        ttk.Label(num_frame, text="题目数量 (10-5000):").grid(row=0, column=0, sticky=tk.W, padx=5)
        num_spinbox = ttk.Spinbox(num_frame, from_=10, to=5000, increment=5, 
                                 textvariable=self.num_questions, width=10)
        num_spinbox.grid(row=0, column=1, padx=5)
        
        # 显示页面信息
        ttk.Label(num_frame, text="页面信息:").grid(row=1, column=0, sticky=tk.W, padx=5, pady=5)
        self.pages_label = ttk.Label(num_frame, text="自动计算")
        self.pages_label.grid(row=1, column=1, sticky=tk.W, padx=5, pady=5)
        
        # 绑定事件，实时更新页面信息
        num_spinbox.bind("<KeyRelease>", self.update_page_info)
        num_spinbox.bind("<ButtonRelease>", self.update_page_info)
        
        # 选择题型
        type_frame = ttk.LabelFrame(main_frame, text="选择题型", padding=10)
        type_frame.pack(fill=tk.X, pady=10)
        
        # 全选/全不选按钮
        btn_frame = ttk.Frame(type_frame)
        btn_frame.pack(fill=tk.X, pady=5)
        
        ttk.Button(btn_frame, text="全选", command=self.select_all_types).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="全不选", command=self.deselect_all_types).pack(side=tk.LEFT, padx=5)
        
        # 题型复选框
        type_check_frame = ttk.Frame(type_frame)
        type_check_frame.pack(fill=tk.X, pady=10)
        
        row, col = 0, 0
        for name, value in self.question_types.items():
            var = tk.BooleanVar(value=True)
            self.type_vars[value] = var
            
            cb = ttk.Checkbutton(type_check_frame, text=name, variable=var)
            cb.grid(row=row, column=col, sticky=tk.W, padx=10, pady=5)
            
            col += 1
            if col > 2:
                col = 0
                row += 1
        
        # 选项设置
        option_frame = ttk.LabelFrame(main_frame, text="生成选项", padding=10)
        option_frame.pack(fill=tk.X, pady=10)
        
        ttk.Checkbutton(option_frame, text="包含答案", variable=self.include_answers).pack(anchor=tk.W, pady=5)
        ttk.Checkbutton(option_frame, text="随机排序", variable=self.shuffle_questions).pack(anchor=tk.W, pady=5)
        ttk.Checkbutton(option_frame, text="加大间距", variable=self.increase_spacing).pack(anchor=tk.W, pady=5)
        ttk.Checkbutton(option_frame, text="显示脱式计算步骤", variable=self.show_steps).pack(anchor=tk.W, pady=5)
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        progress_frame = ttk.Frame(main_frame)
        progress_frame.pack(fill=tk.X, pady=10)
        
        self.progress_label = ttk.Label(progress_frame, text="就绪")
        self.progress_label.pack(anchor=tk.W)
        
        self.progress_bar = ttk.Progressbar(progress_frame, variable=self.progress_var, 
                                          maximum=100, mode='determinate')
        self.progress_bar.pack(fill=tk.X, pady=5)
        
        # 按钮
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=tk.X, pady=20)
        
        ttk.Button(button_frame, text="生成题目", command=self.generate_questions, 
                  style="Accent.TButton").pack(side=tk.LEFT, padx=5)
        ttk.Button(button_frame, text="保存配置", command=self.save_config).pack(side=tk.LEFT, padx=5)
        ttk.Button(button_frame, text="加载配置", command=self.load_config).pack(side=tk.LEFT, padx=5)
        ttk.Button(button_frame, text="退出", command=self.root.quit).pack(side=tk.RIGHT, padx=5)
        
        # 状态栏
        self.status_var = tk.StringVar(value="就绪")
        status_bar = ttk.Label(self.root, textvariable=self.status_var, relief=tk.SUNKEN)
        status_bar.pack(side=tk.BOTTOM, fill=tk.X)
        
        # 加载默认配置
        self.load_default_config()
        
        # 初始更新页面信息
        self.update_page_info(None)
    
    def update_page_info(self, event):
        """更新页面信息"""
        try:
            num_questions = self.num_questions.get()
            if 10 <= num_questions <= 5000:
                # 根据选项调整每页题目数
                if self.increase_spacing.get():
                    questions_per_page = 15
                elif self.show_steps.get():
                    questions_per_page = 12
                else:
                    questions_per_page = 20
                
                pages = math.ceil(num_questions / questions_per_page)
                self.pages_label.config(text=f"约{questions_per_page}道/页，共{pages}页")
            else:
                self.pages_label.config(text="自动计算")
        except:
            self.pages_label.config(text="自动计算")
    
    def select_all_types(self):
        """全选所有题型"""
        for var in self.type_vars.values():
            var.set(True)
    
    def deselect_all_types(self):
        """全不选所有题型"""
        for var in self.type_vars.values():
            var.set(False)
    
    def load_default_config(self):
        """加载默认配置"""
        for var in self.type_vars.values():
            var.set(True)
    
    def save_config(self):
        """保存配置到文件"""
        config = {
            "num_questions": self.num_questions.get(),
            "include_answers": self.include_answers.get(),
            "shuffle_questions": self.shuffle_questions.get(),
            "increase_spacing": self.increase_spacing.get(),
            "show_steps": self.show_steps.get(),
            "selected_types": {k: v.get() for k, v in self.type_vars.items()}
        }
        
        filename = filedialog.asksaveasfilename(
            defaultextension=".json",
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if filename:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(config, f, ensure_ascii=False, indent=2)
            self.status_var.set(f"配置已保存到: {filename}")
    
    def load_config(self):
        """从文件加载配置"""
        filename = filedialog.askopenfilename(
            filetypes=[("JSON files", "*.json"), ("All files", "*.*")]
        )
        
        if filename:
            try:
                with open(filename, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                
                self.num_questions.set(config.get("num_questions", 100))
                self.include_answers.set(config.get("include_answers", True))
                self.shuffle_questions.set(config.get("shuffle_questions", True))
                self.increase_spacing.set(config.get("increase_spacing", False))
                self.show_steps.set(config.get("show_steps", True))
                
                selected_types = config.get("selected_types", {})
                for k, v in selected_types.items():
                    if k in self.type_vars:
                        self.type_vars[k].set(v)
                
                self.status_var.set(f"配置已从 {filename} 加载")
                self.update_page_info(None)
            except Exception as e:
                messagebox.showerror("错误", f"加载配置失败: {str(e)}")
    
    def update_progress(self, value, message=""):
        """更新进度条"""
        self.progress_var.set(value)
        if message:
            self.progress_label.config(text=message)
        self.root.update_idletasks()
    
    def generate_questions(self):
        """生成题目"""
        try:
            # 验证输入
            num_questions = self.num_questions.get()
            if not 10 <= num_questions <= 5000:
                messagebox.showerror("错误", "题目数量必须在10到5000之间！")
                return
            
            # 获取选中的题型
            selected_types = []
            for name, var in self.type_vars.items():
                if var.get():
                    selected_types.append(name)
            
            if not selected_types:
                messagebox.showerror("错误", "请至少选择一种题型！")
                return
            
            # 更新状态
            self.status_var.set("正在生成题目...")
            self.update_progress(0, "正在生成题目...")
            
            # 生成题目
            questions = self.generate_all_questions(num_questions, selected_types)
            
            # 随机排序
            if self.shuffle_questions.get():
                random.shuffle(questions)
            
            # 生成PDF
            self.update_progress(50, "正在生成PDF...")
            filename = self.create_pdf(questions, num_questions)
            
            # 完成
            self.update_progress(100, "完成！")
            self.status_var.set(f"已生成 {num_questions} 道题目，保存到: {filename}")
            
            messagebox.showinfo("成功", f"已成功生成 {num_questions} 道题目！\n保存到: {filename}")
            
        except Exception as e:
            messagebox.showerror("错误", f"生成题目时出错: {str(e)}")
            self.status_var.set("错误")
    
    def generate_all_questions(self, num_questions, selected_types):
        """生成所有题目"""
        questions = []
        generated_set = set()  # 用于查重
        
        # 计算每种题型应该生成多少题目
        num_types = len(selected_types)
        base_count = num_questions // num_types
        remainder = num_questions % num_types
        
        # 为每种题型分配题目数量
        type_counts = {}
        for i, q_type in enumerate(selected_types):
            count = base_count
            if i < remainder:  # 分配余数
                count += 1
            type_counts[q_type] = count
        
        # 生成进度
        total_generated = 0
        
        # 生成每种题型的题目
        for q_type, count in type_counts.items():
            self.update_progress(30 + (total_generated / num_questions * 20), 
                               f"正在生成 {q_type} 题目...")
            
            type_questions = self.generate_by_type(q_type, count, generated_set)
            questions.extend(type_questions)
            total_generated += len(type_questions)
        
        return questions[:num_questions]  # 确保数量正确
    
    def generate_by_type(self, q_type, count, generated_set):
        """按类型生成题目"""
        questions = []
        
        if q_type == "add_associative":  # 加法结合律
            questions = self.generate_add_associative(count, generated_set)
        elif q_type == "mult_commutative_associative":  # 乘法交换律和结合律
            questions = self.generate_mult_commutative_associative(count, generated_set)
        elif q_type == "distributive":  # 乘法分配律
            questions = self.generate_distributive(count, generated_set)
        elif q_type == "distributive_reverse":  # 乘法分配律逆用
            questions = self.generate_distributive_reverse(count, generated_set)
        elif q_type == "subtraction_property":  # 连减性质
            questions = self.generate_subtraction_property(count, generated_set)
        elif q_type == "add_sub_mix":  # 加减混合
            questions = self.generate_add_sub_mix(count, generated_set)
        elif q_type == "special_multiplication":  # 特殊乘法
            questions = self.generate_special_multiplication(count, generated_set)
        
        return questions
    
    def generate_add_associative(self, count, generated_set):
        """生成加法结合律题目 - 支持脱式计算"""
        questions = []
        
        while len(questions) < count:
            # 生成可以凑整的数对
            a = random.randint(20, 80)
            b = 100 - a
            c = random.randint(20, 80)
            d = random.randint(20, 80)
            
            # 确保不重复
            nums = sorted([a, b, c, d])
            expression = f"{a} + {b} + {c} + {d}"
            
            if expression not in generated_set:
                generated_set.add(expression)
                answer = a + b + c + d
                
                # 生成脱式计算步骤
                steps = []
                if a + b == 100:
                    steps.append(f"= ({a} + {b}) + {c} + {d}")
                    steps.append(f"= 100 + {c} + {d}")
                    if c + d == 100:
                        steps.append(f"= 100 + 100")
                        steps.append(f"= 200")
                    else:
                        steps.append(f"= 100 + {c+d}")
                        steps.append(f"= {answer}")
                elif c + d == 100:
                    steps.append(f"= {a} + {b} + ({c} + {d})")
                    steps.append(f"= {a} + {b} + 100")
                    if a + b == 100:
                        steps.append(f"= 100 + 100")
                        steps.append(f"= 200")
                    else:
                        steps.append(f"= {a+b} + 100")
                        steps.append(f"= {answer}")
                else:
                    # 重新组合
                    if (a + c) % 10 == 0 and (b + d) % 10 == 0:
                        steps.append(f"= ({a} + {c}) + ({b} + {d})")
                        steps.append(f"= {a+c} + {b+d}")
                        steps.append(f"= {answer}")
                    else:
                        steps.append(f"= 从左到右计算")
                        steps.append(f"= {a+b} + {c} + {d}")
                        steps.append(f"= {a+b+c} + {d}")
                        steps.append(f"= {answer}")
                
                questions.append({
                    "expression": expression,
                    "answer": answer,
                    "method": f"加法结合律: 重新组合凑整计算",
                    "steps": steps
                })
        
        return questions[:count]
    
    def generate_mult_commutative_associative(self, count, generated_set):
        """生成乘法交换律和结合律题目 - 支持脱式计算"""
        questions = []
        special_pairs = [(25, 4), (125, 8), (5, 2), (50, 2), (20, 5)]
        
        while len(questions) < count:
            a, b = random.choice(special_pairs)
            c = random.randint(2, 9)
            
            # 生成典型格式：25×4×7
            expression = f"{a} × {b} × {c}"
            
            if expression not in generated_set:
                generated_set.add(expression)
                answer = a * b * c
                
                # 生成脱式计算步骤
                steps = []
                steps.append(f"= ({a} × {b}) × {c}")
                steps.append(f"= {a*b} × {c}")
                steps.append(f"= {answer}")
                
                questions.append({
                    "expression": expression,
                    "answer": answer,
                    "method": f"乘法交换律结合律: 先算{a}×{b}再乘{c}",
                    "steps": steps
                })
        
        return questions[:count]
    
    def generate_distributive(self, count, generated_set):
        """生成乘法分配律题目 - 支持脱式计算"""
        questions = []
        
        while len(questions) < count:
            c = random.randint(2, 9)
            a = random.randint(10, 30)
            b = random.randint(5, 20)
            
            if random.choice([True, False]):
                # 典型格式：5×(20+4)
                expression = f"{c} × ({a} + {b})"
                answer = c * (a + b)
                
                # 生成脱式计算步骤
                steps = []
                steps.append(f"= {c} × {a} + {c} × {b}")
                steps.append(f"= {c*a} + {c*b}")
                steps.append(f"= {answer}")
            else:
                # 典型格式：8×(30-6)
                expression = f"{c} × ({a} - {b})"
                answer = c * (a - b)
                
                # 生成脱式计算步骤
                steps = []
                steps.append(f"= {c} × {a} - {c} × {b}")
                steps.append(f"= {c*a} - {c*b}")
                steps.append(f"= {answer}")
            
            if expression not in generated_set:
                generated_set.add(expression)
                questions.append({
                    "expression": expression,
                    "answer": answer,
                    "method": f"乘法分配律: 分别相乘再加减",
                    "steps": steps
                })
        
        return questions[:count]
    
    def generate_distributive_reverse(self, count, generated_set):
        """生成乘法分配律逆用题目 - 支持脱式计算"""
        questions = []
        
        while len(questions) < count:
            c = random.randint(2, 9)
            a = random.randint(5, 15)
            b = random.randint(5, 15)
            
            # 典型格式：5×12+5×8
            expression = f"{c}×{a} + {c}×{b}"
            
            if expression not in generated_set:
                generated_set.add(expression)
                answer = c * (a + b)
                
                # 生成脱式计算步骤
                steps = []
                steps.append(f"= {c} × ({a} + {b})")
                steps.append(f"= {c} × {a+b}")
                steps.append(f"= {answer}")
                
                questions.append({
                    "expression": expression,
                    "answer": answer,
                    "method": f"乘法分配律逆用: 提取公因数{c}",
                    "steps": steps
                })
        
        return questions[:count]
    
    def generate_subtraction_property(self, count, generated_set):
        """生成连减性质题目 - 支持脱式计算"""
        questions = []
        
        while len(questions) < count:
            a = random.randint(100, 200)
            b = random.randint(20, 50)
            c = random.randint(20, 50)
            
            if b + c <= 100:
                expression = f"{a} - {b} - {c}"
                
                if expression not in generated_set:
                    generated_set.add(expression)
                    answer = a - (b + c)
                    
                    # 生成脱式计算步骤
                    steps = []
                    steps.append(f"= {a} - ({b} + {c})")
                    steps.append(f"= {a} - {b+c}")
                    steps.append(f"= {answer}")
                    
                    questions.append({
                        "expression": expression,
                        "answer": answer,
                        "method": f"连减性质: 减去两个数的和",
                        "steps": steps
                    })
        
        return questions[:count]
    
    def generate_add_sub_mix(self, count, generated_set):
        """生成加减混合题目 - 支持脱式计算"""
        questions = []
        
        while len(questions) < count:
            a = random.randint(50, 100)
            b = random.randint(10, 49)
            c = random.randint(10, 49)
            
            if random.choice([True, False]):
                expression = f"{a} + {b} - {c}"
                if a - c >= 0:
                    if expression not in generated_set:
                        generated_set.add(expression)
                        answer = a - c + b
                        
                        # 生成脱式计算步骤
                        steps = []
                        steps.append(f"= ({a} - {c}) + {b}")
                        steps.append(f"= {a-c} + {b}")
                        steps.append(f"= {answer}")
                        
                        questions.append({
                            "expression": expression,
                            "answer": answer,
                            "method": f"加减混合: 先减再加",
                            "steps": steps
                        })
            else:
                expression = f"{a} - {b} + {c}"
                if a - b >= 0:
                    if expression not in generated_set:
                        generated_set.add(expression)
                        answer = a - b + c
                        
                        # 生成脱式计算步骤
                        steps = []
                        steps.append(f"= ({a} - {b}) + {c}")
                        steps.append(f"= {a-b} + {c}")
                        steps.append(f"= {answer}")
                        
                        questions.append({
                            "expression": expression,
                            "answer": answer,
                            "method": f"加减混合: 先减再加",
                            "steps": steps
                        })
        
        return questions[:count]
    
    def generate_special_multiplication(self, count, generated_set):
        """生成特殊乘法题目 - 支持脱式计算"""
        questions = []
        
        while len(questions) < count:
            a = random.choice([25, 125])
            b = random.randint(2, 9)
            
            if a == 25:
                # 典型格式：25×36 或 25×4×9
                if random.choice([True, False]):
                    expression = f"25 × {b*4}"
                    # 生成脱式计算步骤
                    steps = []
                    steps.append(f"= 25 × 4 × {b}")
                    steps.append(f"= 100 × {b}")
                    steps.append(f"= {25*4*b}")
                else:
                    expression = f"25 × 4 × {b}"
                    # 生成脱式计算步骤
                    steps = []
                    steps.append(f"= 100 × {b}")
                    steps.append(f"= {25*4*b}")
                answer = 25 * 4 * b
            else:  # 125
                # 典型格式：125×24 或 125×8×3
                if random.choice([True, False]):
                    expression = f"125 × {b*8}"
                    # 生成脱式计算步骤
                    steps = []
                    steps.append(f"= 125 × 8 × {b}")
                    steps.append(f"= 1000 × {b}")
                    steps.append(f"= {125*8*b}")
                else:
                    expression = f"125 × 8 × {b}"
                    # 生成脱式计算步骤
                    steps = []
                    steps.append(f"= 1000 × {b}")
                    steps.append(f"= {125*8*b}")
                answer = 125 * 8 * b
            
            if expression not in generated_set:
                generated_set.add(expression)
                questions.append({
                    "expression": expression,
                    "answer": answer,
                    "method": f"特殊乘法({a}): 利用{a}×特殊数凑整",
                    "steps": steps
                })
        
        return questions[:count]
    
    def register_chinese_font(self):
        """注册中文字体，优先尝试用户提供的路径"""
        font_paths = [
            "C:\\Windows\\Fonts\\msyh.ttc",  # Windows 微软雅黑
            "C:\\Windows\\Fonts\\simhei.ttf",  # Windows 黑体
            "C:\\Windows\\Fonts\\simsun.ttc",  # Windows 宋体
            "/System/Library/Fonts/PingFang.ttc",  # macOS
            "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",  # Linux
            "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",  # Linux
        ]
        
        for font_path in font_paths:
            if os.path.exists(font_path):
                try:
                    pdfmetrics.registerFont(TTFont("ChineseFont", font_path))
                    print(f"成功注册字体: {font_path}")
                    return True
                except Exception as e:
                    print(f"字体注册失败 {font_path}: {e}")
        
        print("警告: 未找到中文字体，将使用默认字体")
        return False
    
    def create_pdf(self, questions, num_questions):
        """生成PDF文件，支持间距调整和脱式计算"""
        # 尝试注册中文字体
        font_registered = self.register_chinese_font()
        
        # 选择保存位置
        filename = filedialog.asksaveasfilename(
            defaultextension=".pdf",
            filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")],
            initialfile=f"四年级简便运算{num_questions}题.pdf"
        )
        
        if not filename:
            return None
        
        # 根据选项调整每页题目数
        if self.increase_spacing.get():
            questions_per_page = 15
            line_spacing = 1.2
        elif self.show_steps.get():
            questions_per_page = 12
            line_spacing = 1.0
        else:
            questions_per_page = 20
            line_spacing = 0.8
        
        total_pages = math.ceil(num_questions / questions_per_page)
        
        # 创建PDF
        c = canvas.Canvas(filename, pagesize=A4)
        width, height = A4
        
        # 设置字体
        if font_registered:
            c.setFont("ChineseFont", 16)
        else:
            c.setFont("Helvetica-Bold", 16)
        
        # 生成题目页面
        for page_num in range(total_pages):
            if page_num > 0:
                c.showPage()
            
            # 计算本页的题目范围
            start_idx = page_num * questions_per_page
            end_idx = min(start_idx + questions_per_page, num_questions)
            page_questions = questions[start_idx:end_idx]
            
            # 标题
            if font_registered:
                c.setFont("ChineseFont", 16)
            else:
                c.setFont("Helvetica-Bold", 16)
            
            c.drawString(4*cm, height-2*cm, f"四年级数学简便运算题 - 第{page_num+1}页/共{total_pages}页")
            
            if font_registered:
                c.setFont("ChineseFont", 10)
            else:
                c.setFont("Helvetica", 10)
            c.drawString(4*cm, height-2.5*cm, f"（用简便方法计算下列各题，共{num_questions}道）")
            
            # 题目部分
            y_position = height - 4*cm
            
            for i, q in enumerate(page_questions, 1):
                question_num = start_idx + i
                
                if font_registered:
                    c.setFont("ChineseFont", 12)
                else:
                    c.setFont("Helvetica", 12)
                
                # 显示题目
                c.drawString(2*cm, y_position, f"{question_num:3d}. {q['expression']}")
                y_position -= 0.8*cm * line_spacing
                
                # 如果显示脱式计算步骤
                if self.show_steps.get():
                    if font_registered:
                        c.setFont("ChineseFont", 11)
                    else:
                        c.setFont("Helvetica", 11)
                    
                    for step in q.get('steps', []):
                        c.drawString(3.5*cm, y_position, step)
                        y_position -= 0.6*cm * line_spacing
                
                # 每道题后增加间距
                y_position -= 0.3*cm * line_spacing
                
                # 每5道题增加更多间距
                if i % 5 == 0 and i < len(page_questions):
                    y_position -= 0.5*cm * line_spacing
        
        # 添加答案部分
        if self.include_answers.get():
            c.showPage()
            
            if font_registered:
                c.setFont("ChineseFont", 16)
            else:
                c.setFont("Helvetica-Bold", 16)
            c.drawString(4*cm, height-2*cm, "答案与解析")
            
            if font_registered:
                c.setFont("ChineseFont", 10)
            else:
                c.setFont("Helvetica", 10)
            c.drawString(4*cm, height-2.5*cm, f"（共{num_questions}道题）")
            
            # 答案部分
            y_position = height - 4*cm
            answers_per_page = 15  # 答案部分每页显示15道题
            
            for page_num in range(math.ceil(num_questions / answers_per_page)):
                if page_num > 0:
                    c.showPage()
                    if font_registered:
                        c.setFont("ChineseFont", 12)
                    else:
                        c.setFont("Helvetica", 12)
                    y_position = height - 2*cm
                
                start_idx = page_num * answers_per_page
                end_idx = min(start_idx + answers_per_page, num_questions)
                page_answers = questions[start_idx:end_idx]
                
                y_position = height - 4*cm
                
                for i, q in enumerate(page_answers, 1):
                    answer_num = start_idx + i
                    
                    if font_registered:
                        c.setFont("ChineseFont", 12)
                    else:
                        c.setFont("Helvetica", 12)
                    
                    # 题目和答案
                    c.drawString(2*cm, y_position, f"{answer_num:3d}. {q['expression']} = {q['answer']}")
                    
                    if font_registered:
                        c.setFont("ChineseFont", 10)
                    else:
                        c.setFont("Helvetica", 10)
                    
                    # 解析
                    c.drawString(2*cm, y_position-0.5*cm, f"    解析: {q['method']}")
                    
                    # 显示脱式计算步骤
                    if self.show_steps.get():
                        step_y = y_position - 0.9*cm
                        for step in q.get('steps', []):
                            c.drawString(3*cm, step_y, step)
                            step_y -= 0.4*cm
                        y_position = step_y
                    else:
                        y_position -= 1.2*cm
                    
                    # 每道题后增加间距
                    y_position -= 0.3*cm
                    
                    # 每5道题增加更多间距
                    if i % 5 == 0 and i < len(page_answers):
                        y_position -= 0.5*cm
        
        c.save()
        return filename

def main():
    root = tk.Tk()
    
    # 设置窗口样式
    style = ttk.Style()
    try:
        style.theme_use('clam')
    except:
        pass
    
    app = MathWorksheetGenerator(root)
    
    # 运行应用程序
    root.mainloop()

if __name__ == "__main__":
    main()
