CREATE TABLE IF NOT EXISTS template_blocks (
    id INT AUTO_INCREMENT PRIMARY KEY,
    template_id INT NOT NULL,
    source_paragraph_id INT DEFAULT NULL COMMENT '来源段落 ID',
    parent_block_id INT DEFAULT NULL COMMENT '父块 ID',
    sort_index INT DEFAULT 0 COMMENT '排序',
    block_type VARCHAR(30) DEFAULT 'text' COMMENT 'heading/text/table/ai_slot/variable',
    anchor_ref VARCHAR(500) DEFAULT '' COMMENT '原始锚点引用',
    title VARCHAR(500) DEFAULT '' COMMENT '块标题',
    content_json TEXT DEFAULT '{}' COMMENT '块内容 JSON',
    style_json TEXT DEFAULT '{}' COMMENT '块样式 JSON',
    edit_mode VARCHAR(20) DEFAULT 'manual' COMMENT 'manual/ai',
    placeholder_key VARCHAR(120) DEFAULT '' COMMENT 'AI 占位键',
    variable_key VARCHAR(120) DEFAULT '' COMMENT '变量键',
    default_value TEXT DEFAULT '' COMMENT '默认值',
    model_id INT DEFAULT NULL COMMENT '指定模型',
    need_prompt TINYINT(1) DEFAULT 1 COMMENT '是否需要提示词',
    prompt_text TEXT DEFAULT '' COMMENT '预设提示词',
    need_file TINYINT(1) DEFAULT 0 COMMENT '是否需要参考文件',
    file_note TEXT DEFAULT '' COMMENT '备注说明',
    output_format VARCHAR(20) DEFAULT 'text' COMMENT 'text/table/mixed/chart',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    CONSTRAINT fk_template_blocks_template FOREIGN KEY (template_id) REFERENCES templates(id) ON DELETE CASCADE,
    CONSTRAINT fk_template_blocks_paragraph FOREIGN KEY (source_paragraph_id) REFERENCES paragraphs(id) ON DELETE SET NULL,
    CONSTRAINT fk_template_blocks_parent FOREIGN KEY (parent_block_id) REFERENCES template_blocks(id) ON DELETE SET NULL,
    CONSTRAINT fk_template_blocks_model FOREIGN KEY (model_id) REFERENCES ai_models(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
