  -- =============================
-- 泰豪电源AI数智化平台 - 完整数据库初始化脚本
-- 包含所有业务模块的表结构
-- =============================

-- 安装必要的扩展
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";      -- UUID生成
CREATE EXTENSION IF NOT EXISTS "pg_trgm";        -- 全文搜索
CREATE EXTENSION IF NOT EXISTS "btree_gin";      -- GIN索引支持
-- CREATE EXTENSION IF NOT EXISTS "vector";      -- pgvector向量检索（需要单独安装）

-- =============================
-- 1. 系统基础模块（权限、用户、部门、角色）
-- =============================
\i createTablePermission.sql
\i createTableUser.sql

-- =============================
-- 2. 文件管理模块
-- =============================
\i createTableFile.sql

-- =============================
-- 3. 消息通知模块
-- =============================
\i createTableMessage.sql

-- =============================
-- 4. 日志模块
-- =============================
\i createTableLog.sql

-- =============================
-- 5. 配置管理模块
-- =============================
\i createTableConfig.sql

-- =============================
-- 6. 知识库管理模块
-- =============================
\i createTableKnowledge.sql

-- =============================
-- 7. 招投标智能体业务模块
-- =============================
\i createTableBidding.sql

-- =============================
-- 8. 智能客服系统业务模块
-- =============================
\i createTableCustomerService.sql

-- =============================
-- 9. 智能体管理和平台基础设施模块
-- =============================
\i createTableAgent.sql

-- =============================
-- 创建视图
-- =============================

-- 用户完整信息视图
CREATE OR REPLACE VIEW sys.v_user_full_info AS
SELECT 
    u.user_id,
    u.email,
    u.phone,
    u.wechat_id,
    u.status,
    ui.avatar,
    ui.full_name,
    ui.gender,
    ui.level,
    u.create_time,
    u.update_time
FROM sys.tb_sys_user u
LEFT JOIN sys.tb_sys_user_info ui ON u.user_id = ui.user_id
WHERE u.deleted = false AND (ui.deleted = false OR ui.deleted IS NULL);

-- 用户角色权限视图
CREATE OR REPLACE VIEW sys.v_user_role_permission AS
SELECT DISTINCT
    ur.user_id,
    r.role_id,
    r.name AS role_name,
    p.permission_id,
    p.code AS permission_code,
    p.name AS permission_name,
    m.module_id,
    m.name AS module_name
FROM sys.tb_sys_user_role ur
JOIN sys.tb_sys_role r ON ur.role_id = r.role_id
JOIN sys.tb_sys_role_permission rp ON r.role_id = rp.role_id
JOIN sys.tb_sys_permission p ON rp.permission_id = p.permission_id
LEFT JOIN sys.tb_sys_module m ON p.module_id = m.module_id
WHERE ur.deleted = false 
  AND r.deleted = false 
  AND rp.deleted = false 
  AND p.deleted = false;

-- 智能体使用统计视图
CREATE OR REPLACE VIEW agent.v_agent_usage_stats AS
SELECT 
    a.agent_id,
    a.agent_name,
    a.agent_type,
    COUNT(DISTINCT s.session_id) AS total_sessions,
    COUNT(DISTINCT s.user_id) AS unique_users,
    SUM(s.message_count) AS total_messages,
    AVG(s.token_usage) AS avg_token_usage,
    AVG(r.rating) AS avg_rating,
    COUNT(r.rating_id) AS rating_count,
    MAX(s.start_time) AS last_used_time
FROM agent.tb_agent a
LEFT JOIN agent.tb_agent_session s ON a.agent_id = s.agent_id AND s.deleted = false
LEFT JOIN agent.tb_agent_rating r ON a.agent_id = r.agent_id AND r.deleted = false
WHERE a.deleted = false
GROUP BY a.agent_id, a.agent_name, a.agent_type;

-- 客服工单统计视图
CREATE OR REPLACE VIEW customer_service.v_ticket_stats AS
SELECT 
    t.ticket_status,
    t.priority,
    t.ticket_type,
    COUNT(*) AS ticket_count,
    AVG(EXTRACT(EPOCH FROM (t.resolution_time - t.create_time))/3600) AS avg_resolution_hours,
    AVG(t.customer_rating) AS avg_rating,
    COUNT(CASE WHEN t.is_overdue THEN 1 END) AS overdue_count
FROM customer_service.tb_ticket t
WHERE t.deleted = false
GROUP BY t.ticket_status, t.priority, t.ticket_type;

-- 招投标项目统计视图
CREATE OR REPLACE VIEW bidding.v_project_stats AS
SELECT 
    p.project_status,
    p.project_type,
    COUNT(*) AS project_count,
    SUM(p.budget_amount) AS total_budget,
    SUM(CASE WHEN p.winning_status = 'won' THEN 1 ELSE 0 END) AS won_count,
    SUM(CASE WHEN p.winning_status = 'won' THEN p.winning_amount ELSE 0 END) AS total_won_amount,
    AVG(CASE WHEN p.winning_status = 'won' THEN p.winning_amount / NULLIF(p.budget_amount, 0) ELSE NULL END) AS avg_win_rate
FROM bidding.tb_bidding_project p
WHERE p.deleted = false
GROUP BY p.project_status, p.project_type;

COMMENT ON VIEW sys.v_user_full_info IS '用户完整信息视图';
COMMENT ON VIEW sys.v_user_role_permission IS '用户角色权限视图';
COMMENT ON VIEW agent.v_agent_usage_stats IS '智能体使用统计视图';
COMMENT ON VIEW customer_service.v_ticket_stats IS '客服工单统计视图';
COMMENT ON VIEW bidding.v_project_stats IS '招投标项目统计视图';

-- =============================
-- 数据库初始化完成
-- =============================
