-- 创建通用的页面块表
-- 这个表用于存储页面的各种内容块，支持多种块类型

CREATE TABLE IF NOT EXISTS page_blocks (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    page_id UUID NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
    block_order INTEGER NOT NULL,
    title VARCHAR(255),
    block_type VARCHAR(50) NOT NULL, -- 'text', 'chart', 'settings', 'table', 'hero', etc.
    content JSONB, -- 块内容，根据类型存储不同的配置
    is_active BOOLEAN NOT NULL DEFAULT true,
    created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
    created_by UUID REFERENCES users(id),
    updated_by UUID REFERENCES users(id),
    UNIQUE(page_id, block_order)
);

-- 创建索引
CREATE INDEX IF NOT EXISTS idx_page_blocks_page_id ON page_blocks(page_id);
CREATE INDEX IF NOT EXISTS idx_page_blocks_block_type ON page_blocks(block_type);
CREATE INDEX IF NOT EXISTS idx_page_blocks_is_active ON page_blocks(is_active);
CREATE INDEX IF NOT EXISTS idx_page_blocks_order ON page_blocks(page_id, block_order);

-- 创建更新时间触发器
CREATE TRIGGER update_page_blocks_updated_at BEFORE UPDATE ON page_blocks
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

-- 插入一些示例页面块数据
INSERT INTO page_blocks (id, page_id, block_order, title, block_type, content, is_active, created_at, updated_at) VALUES
-- 系统设置页面的块
(gen_random_uuid(), (SELECT id FROM pages WHERE slug = 'system-settings'), 1, '系统配置', 'settings', '{"category": "system", "editable": true, "display_mode": "form"}', true, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
(gen_random_uuid(), (SELECT id FROM pages WHERE slug = 'system-settings'), 2, '安全设置', 'settings', '{"category": "security", "editable": true, "display_mode": "form"}', true, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),

-- 数据概览页面的块
(gen_random_uuid(), (SELECT id FROM pages WHERE slug = 'data-overview'), 1, '统计概览', 'chart', '{"chart_type": "dashboard", "config": {"layout": "grid"}}', true, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
(gen_random_uuid(), (SELECT id FROM pages WHERE slug = 'data-overview'), 2, '趋势图表', 'chart', '{"chart_type": "line", "config": {"x_axis": "time", "y_axis": "value"}}', true, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),

-- 用户管理页面的块
(gen_random_uuid(), (SELECT id FROM pages WHERE slug = 'user-management'), 1, '用户列表', 'table', '{"data_source": "users", "data_config": {"columns": ["id", "username", "email", "status"]}}', true, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP),
(gen_random_uuid(), (SELECT id FROM pages WHERE slug = 'user-management'), 2, '用户统计', 'chart', '{"chart_type": "pie", "config": {"title": "用户状态分布"}}', true, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)

ON CONFLICT DO NOTHING; 