-- =====================================================
-- AI项目进度与风险管控平台 - 通用版数据库设计 (PostgreSQL + pgvector)
-- 适用于各类项目的管理与追踪分析
-- 支持AI原生特性：向量存储、语义搜索、RAG
-- =====================================================

-- 启用pgvector扩展
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

-- 设置时区
SET timezone = 'Asia/Shanghai';

-- =====================================================
-- 1. 部门与用户相关表 (简化版：单部门，无多租户)
-- =====================================================

-- 部门表 (单部门架构，简化设计)
DROP TABLE IF EXISTS sys_department;
CREATE TABLE sys_department (
                                id BIGSERIAL PRIMARY KEY,
                                dept_code VARCHAR(50) NOT NULL UNIQUE COMMENT '部门编码',
                                dept_name VARCHAR(100) NOT NULL COMMENT '部门名称',
                                parent_id BIGINT DEFAULT NULL COMMENT '父级部门ID',
                                leader_id BIGINT COMMENT '部门负责人ID',
                                description TEXT COMMENT '部门描述',
                                sort_order INT DEFAULT 0 COMMENT '排序',
                                status SMALLINT DEFAULT 1 COMMENT '状态: 1-正常, 0-禁用',
                                create_by BIGINT COMMENT '创建人',
                                create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                update_by BIGINT COMMENT '更新人',
                                update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                                deleted SMALLINT DEFAULT 0 COMMENT '删除标记',

                                CONSTRAINT fk_dept_parent FOREIGN KEY (parent_id) REFERENCES sys_department(id) ON DELETE SET NULL
);

CREATE INDEX idx_dept_parent ON sys_department(parent_id);
CREATE INDEX idx_dept_status ON sys_department(status);

COMMENT ON TABLE sys_department IS '部门表 - 单部门架构';

-- =====================================================
-- 2. 用户与权限相关表
-- =====================================================

-- 用户表
DROP TABLE IF EXISTS sys_user;
CREATE TABLE sys_user (
                          id BIGSERIAL PRIMARY KEY,
                          username VARCHAR(50) NOT NULL UNIQUE COMMENT '用户名',
                          password VARCHAR(200) NOT NULL COMMENT '密码(加密)',
                          real_name VARCHAR(50) COMMENT '真实姓名',
                          nickname VARCHAR(50) COMMENT '昵称',
                          avatar VARCHAR(500) COMMENT '头像URL',
                          gender SMALLINT DEFAULT 0 COMMENT '性别: 0-未知, 1-男, 2-女',
                          phone VARCHAR(20) COMMENT '手机号',
                          email VARCHAR(100) COMMENT '邮箱',
                          dept_id BIGINT COMMENT '所属部门ID',
                          position VARCHAR(50) COMMENT '职位',
                          employee_no VARCHAR(50) COMMENT '工号',
                          entry_date DATE COMMENT '入职日期',
                          status SMALLINT DEFAULT 1 COMMENT '状态: 1-正常, 0-禁用, 2-锁定',
                          last_login_time TIMESTAMP COMMENT '最后登录时间',
                          last_login_ip VARCHAR(50) COMMENT '最后登录IP',
                          preferences JSONB COMMENT '用户偏好设置',
                          extra_data JSONB COMMENT '扩展数据',
                          create_by BIGINT COMMENT '创建人',
                          create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                          update_by BIGINT COMMENT '更新人',
                          update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                          deleted SMALLINT DEFAULT 0 COMMENT '删除标记',

                          CONSTRAINT fk_user_dept FOREIGN KEY (dept_id) REFERENCES sys_department(id) ON DELETE SET NULL
);

CREATE INDEX idx_user_dept ON sys_user(dept_id);
CREATE INDEX idx_user_phone ON sys_user(phone);
CREATE INDEX idx_user_status ON sys_user(status);

COMMENT ON TABLE sys_user IS '用户表';

-- 角色表
DROP TABLE IF EXISTS sys_role;
CREATE TABLE sys_role (
                          id BIGSERIAL PRIMARY KEY,
                          role_code VARCHAR(50) NOT NULL UNIQUE COMMENT '角色编码',
                          role_name VARCHAR(50) NOT NULL COMMENT '角色名称',
                          role_type VARCHAR(20) DEFAULT 'custom' COMMENT '角色类型: system-系统角色, custom-自定义角色',
                          description TEXT COMMENT '角色描述',
                          data_scope SMALLINT DEFAULT 1 COMMENT '数据权限: 1-全部, 2-本部门, 3-本人',
                          sort_order INT DEFAULT 0 COMMENT '排序',
                          status SMALLINT DEFAULT 1 COMMENT '状态: 1-正常, 0-禁用',
                          create_by BIGINT COMMENT '创建人',
                          create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                          update_by BIGINT COMMENT '更新人',
                          update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                          deleted SMALLINT DEFAULT 0 COMMENT '删除标记'
);

COMMENT ON TABLE sys_role IS '角色表';

-- 用户角色关联表
DROP TABLE IF EXISTS sys_user_role;
CREATE TABLE sys_user_role (
                               id BIGSERIAL PRIMARY KEY,
                               user_id BIGINT NOT NULL COMMENT '用户ID',
                               role_id BIGINT NOT NULL COMMENT '角色ID',
                               create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                               UNIQUE(user_id, role_id),
                               CONSTRAINT fk_ur_user FOREIGN KEY (user_id) REFERENCES sys_user(id) ON DELETE CASCADE,
                               CONSTRAINT fk_ur_role FOREIGN KEY (role_id) REFERENCES sys_role(id) ON DELETE CASCADE
);

CREATE INDEX idx_ur_role ON sys_user_role(role_id);

COMMENT ON TABLE sys_user_role IS '用户角色关联表';

-- 权限表(菜单/功能权限)
DROP TABLE IF EXISTS sys_permission;
CREATE TABLE sys_permission (
                                id BIGSERIAL PRIMARY KEY,
                                parent_id BIGINT DEFAULT NULL COMMENT '父级权限ID',
                                permission_code VARCHAR(100) NOT NULL UNIQUE COMMENT '权限编码',
                                permission_name VARCHAR(50) NOT NULL COMMENT '权限名称',
                                permission_type SMALLINT DEFAULT 1 COMMENT '权限类型: 1-菜单, 2-按钮, 3-接口',
                                path VARCHAR(200) COMMENT '路由路径',
                                component VARCHAR(200) COMMENT '组件路径',
                                icon VARCHAR(50) COMMENT '图标',
                                api_url VARCHAR(200) COMMENT '接口URL',
                                api_method VARCHAR(10) COMMENT '接口方法',
                                sort_order INT DEFAULT 0 COMMENT '排序',
                                visible SMALLINT DEFAULT 1 COMMENT '是否可见: 1-是, 0-否',
                                status SMALLINT DEFAULT 1 COMMENT '状态: 1-正常, 0-禁用',
                                create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                                deleted SMALLINT DEFAULT 0 COMMENT '删除标记',

                                CONSTRAINT fk_perm_parent FOREIGN KEY (parent_id) REFERENCES sys_permission(id) ON DELETE SET NULL
);

CREATE INDEX idx_perm_parent ON sys_permission(parent_id);

COMMENT ON TABLE sys_permission IS '权限表';

-- 角色权限关联表
DROP TABLE IF EXISTS sys_role_permission;
CREATE TABLE sys_role_permission (
                                     id BIGSERIAL PRIMARY KEY,
                                     role_id BIGINT NOT NULL COMMENT '角色ID',
                                     permission_id BIGINT NOT NULL COMMENT '权限ID',
                                     create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                     UNIQUE(role_id, permission_id),
                                     CONSTRAINT fk_rp_role FOREIGN KEY (role_id) REFERENCES sys_role(id) ON DELETE CASCADE,
                                     CONSTRAINT fk_rp_perm FOREIGN KEY (permission_id) REFERENCES sys_permission(id) ON DELETE CASCADE
);

COMMENT ON TABLE sys_role_permission IS '角色权限关联表';

-- =====================================================
-- 3. 项目管理核心表
-- =====================================================

-- 项目表
DROP TABLE IF EXISTS project;
CREATE TABLE project (
                         id BIGSERIAL PRIMARY KEY,
                         project_code VARCHAR(50) NOT NULL UNIQUE COMMENT '项目编号',
                         project_name VARCHAR(200) NOT NULL COMMENT '项目名称',
                         project_type VARCHAR(50) COMMENT '项目类型(如: 研发项目, 工程项目, 运营项目)',
                         description TEXT COMMENT '项目描述',
                         objectives TEXT COMMENT '项目目标',
                         manager_id BIGINT COMMENT '项目经理ID',
                         sponsor_id BIGINT COMMENT '项目发起人ID',
                         plan_start_date DATE COMMENT '计划开始日期',
                         plan_end_date DATE COMMENT '计划结束日期',
                         actual_start_date DATE COMMENT '实际开始日期',
                         actual_end_date DATE COMMENT '实际结束日期',
                         budget DECIMAL(18,2) DEFAULT 0 COMMENT '项目预算',
                         cost DECIMAL(18,2) DEFAULT 0 COMMENT '已花费金额',
                         currency VARCHAR(10) DEFAULT 'CNY' COMMENT '币种',
                         progress INT DEFAULT 0 COMMENT '进度百分比',
                         status VARCHAR(20) DEFAULT 'draft' COMMENT '状态: draft-草稿, planning-规划中, ongoing-进行中, paused-暂停, completed-已完成, cancelled-已取消',
                         priority VARCHAR(20) DEFAULT 'medium' COMMENT '优先级: critical-关键, high-高, medium-中, low-低',
                         risk_level VARCHAR(20) DEFAULT 'low' COMMENT '风险等级: high-高, medium-中, low-低',
                         visibility SMALLINT DEFAULT 1 COMMENT '可见性: 1-公开, 2-部门内, 3-项目成员',
                         tags JSONB COMMENT '标签列表',
                         extra_data JSONB COMMENT '扩展数据(用于存储行业特定字段)',
                         create_by BIGINT COMMENT '创建人',
                         create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                         update_by BIGINT COMMENT '更新人',
                         update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                         deleted SMALLINT DEFAULT 0 COMMENT '删除标记',

                         CONSTRAINT fk_project_manager FOREIGN KEY (manager_id) REFERENCES sys_user(id) ON DELETE SET NULL
);

CREATE INDEX idx_project_manager ON project(manager_id);
CREATE INDEX idx_project_status ON project(status);
CREATE INDEX idx_project_risk_level ON project(risk_level);

COMMENT ON TABLE project IS '项目表';

-- 项目成员表
DROP TABLE IF EXISTS `project_member`;
CREATE TABLE `project_member` (
                                  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
                                  `project_id` BIGINT NOT NULL COMMENT '项目ID',
                                  `user_id` BIGINT NOT NULL COMMENT '用户ID',
                                  `role_code` VARCHAR(50) DEFAULT 'member' COMMENT '项目角色: manager-项目经理, leader-负责人, member-成员, observer-观察者',
                                  `join_date` DATE COMMENT '加入日期',
                                  `leave_date` DATE COMMENT '离开日期',
                                  `responsibility` TEXT COMMENT '职责描述',
                                  `weekly_hours` DECIMAL(5,1) COMMENT '每周投入小时数',
                                  `status` TINYINT DEFAULT 1 COMMENT '状态: 1-正常, 0-已移除',
                                  `create_by` BIGINT COMMENT '创建人',
                                  `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                  `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                                  PRIMARY KEY (`id`),
                                  UNIQUE KEY `uk_project_user` (`project_id`, `user_id`),
                                  KEY `idx_user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='项目成员表';

-- 项目阶段/里程碑表
DROP TABLE IF EXISTS `project_milestone`;
CREATE TABLE `project_milestone` (
                                     `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
                                     `project_id` BIGINT NOT NULL COMMENT '项目ID',
                                     `milestone_name` VARCHAR(200) NOT NULL COMMENT '里程碑名称',
                                     `description` TEXT COMMENT '描述',
                                     `plan_date` DATE COMMENT '计划日期',
                                     `actual_date` DATE COMMENT '实际日期',
                                     `status` VARCHAR(20) DEFAULT 'pending' COMMENT '状态: pending-待开始, in_progress-进行中, completed-已完成, delayed-延期',
                                     `progress` INT DEFAULT 0 COMMENT '完成进度',
                                     `sort_order` INT DEFAULT 0 COMMENT '排序',
                                     `is_key` TINYINT DEFAULT 0 COMMENT '是否关键里程碑: 1-是, 0-否',
                                     `deliverables` JSON COMMENT '交付物列表',
                                     `extra_data` JSON COMMENT '扩展数据',
                                     `create_by` BIGINT COMMENT '创建人',
                                     `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                     `update_by` BIGINT COMMENT '更新人',
                                     `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                                     `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
                                     PRIMARY KEY (`id`),
                                     KEY `idx_project_id` (`project_id`),
                                     KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='项目里程碑表';

-- =====================================================
-- 4. 任务管理表
-- =====================================================

-- 任务表
DROP TABLE IF EXISTS `task`;
CREATE TABLE `task` (
                        `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
                        `task_code` VARCHAR(50) COMMENT '任务编号',
                        `project_id` BIGINT NOT NULL COMMENT '项目ID',
                        `milestone_id` BIGINT COMMENT '所属里程碑ID',
                        `parent_id` BIGINT COMMENT '父任务ID',
                        `task_name` VARCHAR(200) NOT NULL COMMENT '任务名称',
                        `description` TEXT COMMENT '任务描述',
                        `task_type` VARCHAR(50) COMMENT '任务类型',
                        `assignee_id` BIGINT COMMENT '执行人ID',
                        `plan_start_date` DATE COMMENT '计划开始日期',
                        `plan_end_date` DATE COMMENT '计划结束日期',
                        `actual_start_date` DATE COMMENT '实际开始日期',
                        `actual_end_date` DATE COMMENT '实际结束日期',
                        `plan_hours` DECIMAL(8,2) COMMENT '计划工时(小时)',
                        `actual_hours` DECIMAL(8,2) COMMENT '实际工时(小时)',
                        `progress` INT DEFAULT 0 COMMENT '进度百分比',
                        `priority` VARCHAR(20) DEFAULT 'medium' COMMENT '优先级: critical-关键, high-高, medium-中, low-低',
                        `status` VARCHAR(20) DEFAULT 'pending' COMMENT '状态: pending-待开始, in_progress-进行中, completed-已完成, cancelled-已取消',
                        `sort_order` INT DEFAULT 0 COMMENT '排序',
                        `tags` JSON COMMENT '标签',
                        `attachments` JSON COMMENT '附件列表',
                        `extra_data` JSON COMMENT '扩展数据',
                        `create_by` BIGINT COMMENT '创建人',
                        `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                        `update_by` BIGINT COMMENT '更新人',
                        `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                        `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
                        PRIMARY KEY (`id`),
                        KEY `idx_project_id` (`project_id`),
                        KEY `idx_milestone_id` (`milestone_id`),
                        KEY `idx_parent_id` (`parent_id`),
                        KEY `idx_assignee_id` (`assignee_id`),
                        KEY `idx_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='任务表';

-- 任务依赖关系表
DROP TABLE IF EXISTS `task_dependency`;
CREATE TABLE `task_dependency` (
                                   `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
                                   `task_id` BIGINT NOT NULL COMMENT '任务ID',
                                   `depends_on_task_id` BIGINT NOT NULL COMMENT '依赖的任务ID',
                                   `dependency_type` VARCHAR(20) DEFAULT 'finish_to_start' COMMENT '依赖类型: finish_to_start-完成-开始, start_to_start-开始-开始, finish_to_finish-完成-完成, start_to_finish-开始-完成',
                                   `lag_days` INT DEFAULT 0 COMMENT '滞后天数',
                                   `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                   PRIMARY KEY (`id`),
                                   UNIQUE KEY `uk_task_dependency` (`task_id`, `depends_on_task_id`),
                                   KEY `idx_depends_on` (`depends_on_task_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='任务依赖关系表';

-- =====================================================
-- 5. 工单管理表
-- =====================================================

-- 工单表 (移除order_type_id外键，使用type字段替代)
-- 工单可关联风险，用于风险处理
DROP TABLE IF EXISTS work_order;
CREATE TABLE work_order (
                            id BIGSERIAL PRIMARY KEY,
                            order_code VARCHAR(50) NOT NULL UNIQUE COMMENT '工单编号',
                            order_type VARCHAR(50) COMMENT '工单类型: bug-缺陷, feature-需求, task-任务, incident-事件, risk_handle-风险处理, other-其他',
                            project_id BIGINT COMMENT '关联项目ID',
                            risk_id BIGINT COMMENT '关联风险ID(用于风险处理工单)',
                            title VARCHAR(200) NOT NULL COMMENT '工单标题',
                            description TEXT COMMENT '工单描述',
                            creator_id BIGINT NOT NULL COMMENT '创建人ID',
                            handler_id BIGINT COMMENT '处理人ID',
                            handler_group_id BIGINT COMMENT '处理组ID',
                            priority VARCHAR(20) DEFAULT 'medium' COMMENT '优先级: critical-紧急, high-高, medium-中, low-低',
                            status VARCHAR(20) DEFAULT 'pending' COMMENT '状态: pending-待处理, assigned-已分派, processing-处理中, resolved-已解决, closed-已关闭, reopened-已重开',
                            source VARCHAR(50) COMMENT '来源: web-网页, mobile-移动端, api-接口, system-系统生成, risk-风险分派',
                            deadline TIMESTAMP COMMENT '截止时间',
                            assigned_time TIMESTAMP COMMENT '分派时间',
                            first_response_time TIMESTAMP COMMENT '首次响应时间',
                            resolved_time TIMESTAMP COMMENT '解决时间',
                            closed_time TIMESTAMP COMMENT '关闭时间',
                            satisfaction_score INT COMMENT '满意度评分(1-5)',
                            tags JSONB COMMENT '标签',
                            attachments JSONB COMMENT '附件列表',
                            extra_data JSONB COMMENT '扩展数据',
                            create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                            update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                            deleted SMALLINT DEFAULT 0 COMMENT '删除标记',

                            CONSTRAINT fk_wo_project FOREIGN KEY (project_id) REFERENCES project(id) ON DELETE SET NULL,
                            CONSTRAINT fk_wo_risk FOREIGN KEY (risk_id) REFERENCES risk(id) ON DELETE SET NULL
);

CREATE INDEX idx_wo_project ON work_order(project_id);
CREATE INDEX idx_wo_risk ON work_order(risk_id);
CREATE INDEX idx_wo_creator ON work_order(creator_id);
CREATE INDEX idx_wo_handler ON work_order(handler_id);
CREATE INDEX idx_wo_status ON work_order(status);
CREATE INDEX idx_wo_priority ON work_order(priority);
CREATE INDEX idx_wo_type ON work_order(order_type);

COMMENT ON TABLE work_order IS '工单表';

-- 工单流转记录表
DROP TABLE IF EXISTS work_order_log;
CREATE TABLE work_order_log (
                                id BIGSERIAL PRIMARY KEY,
                                order_id BIGINT NOT NULL COMMENT '工单ID',
                                action_type VARCHAR(50) NOT NULL COMMENT '操作类型: create-创建, assign-分派, accept-接受, process-处理, resolve-解决, close-关闭, reopen-重开, comment-备注',
                                from_status VARCHAR(20) COMMENT '原状态',
                                to_status VARCHAR(20) COMMENT '新状态',
                                operator_id BIGINT COMMENT '操作人ID',
                                content TEXT COMMENT '操作内容',
                                attachments JSONB COMMENT '附件列表',
                                create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',

                                CONSTRAINT fk_wol_order FOREIGN KEY (order_id) REFERENCES work_order(id) ON DELETE CASCADE
);

CREATE INDEX idx_wol_order ON work_order_log(order_id);
CREATE INDEX idx_wol_operator ON work_order_log(operator_id);

COMMENT ON TABLE work_order_log IS '工单流转记录表';

-- =====================================================
-- 6. 风险管理表
-- =====================================================

-- 风险表 (移除category_id外键，使用category字符串字段)
-- 风险通过分派工单处理，工单完成后同步更新风险状态
DROP TABLE IF EXISTS risk;
CREATE TABLE risk (
                      id BIGSERIAL PRIMARY KEY,
                      risk_code VARCHAR(50) COMMENT '风险编号',
                      project_id BIGINT NOT NULL COMMENT '项目ID',
                      category VARCHAR(50) COMMENT '风险分类: technical-技术风险, schedule-进度风险, cost-成本风险, quality-质量风险, resource-资源风险, external-外部风险, other-其他',
                      risk_name VARCHAR(200) NOT NULL COMMENT '风险名称',
                      description TEXT COMMENT '风险描述',
                      risk_source VARCHAR(50) COMMENT '风险来源: internal-内部, external-外部, ai_detection-AI检测',
                      risk_type VARCHAR(50) COMMENT '风险类型',
                      probability DECIMAL(5,2) COMMENT '发生概率(0-100%)',
                      impact DECIMAL(5,2) COMMENT '影响程度(1-5)',
                      risk_score DECIMAL(5,2) COMMENT '风险得分(概率*影响)',
                      risk_level VARCHAR(20) DEFAULT 'low' COMMENT '风险等级: critical-严重, high-高, medium-中, low-低',
                      status VARCHAR(20) DEFAULT 'identified' COMMENT '状态: identified-已识别, assigned-已分派工单, mitigating-缓解中, resolved-已解决, closed-已关闭',
                      owner_id BIGINT COMMENT '负责人ID',

    -- 工单关联(风险分派的工单ID列表)
                      work_order_ids BIGINT[] COMMENT '关联的工单ID数组',

                      mitigation_plan TEXT COMMENT '缓解措施',
                      contingency_plan TEXT COMMENT '应急计划',
                      trigger_condition TEXT COMMENT '触发条件',
                      discover_time TIMESTAMP COMMENT '发现时间',
                      due_date DATE COMMENT '预期解决日期',
                      resolved_time TIMESTAMP COMMENT '解决时间',
                      ai_analysis JSONB COMMENT 'AI分析结果',
                      tags JSONB COMMENT '标签',
                      extra_data JSONB COMMENT '扩展数据',
                      create_by BIGINT COMMENT '创建人',
                      create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                      update_by BIGINT COMMENT '更新人',
                      update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                      deleted SMALLINT DEFAULT 0 COMMENT '删除标记',

                      CONSTRAINT fk_risk_project FOREIGN KEY (project_id) REFERENCES project(id) ON DELETE CASCADE
);

CREATE INDEX idx_risk_project ON risk(project_id);
CREATE INDEX idx_risk_category ON risk(category);
CREATE INDEX idx_risk_owner ON risk(owner_id);
CREATE INDEX idx_risk_level ON risk(risk_level);
CREATE INDEX idx_risk_status ON risk(status);

COMMENT ON TABLE risk IS '风险表';

-- 注：风险通过分派工单进行处理，工单处理完成后同步更新风险状态
-- 因此不需要单独的风险处理记录表，处理历史在工单流转记录中查看

-- =====================================================
-- 7. 数据录入与报告表
-- =====================================================

-- 日报/数据录入表
DROP TABLE IF EXISTS `daily_report`;
CREATE TABLE `daily_report` (
                                `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
                                `project_id` BIGINT NOT NULL COMMENT '项目ID',
                                `creator_id` BIGINT NOT NULL COMMENT '创建人ID',
                                `report_date` DATE COMMENT '报告日期',
                                `report_type` VARCHAR(50) DEFAULT 'daily' COMMENT '报告类型: daily-日报, weekly-周报, monthly-月报, milestone-里程碑报告, photo-照片记录',
                                `title` VARCHAR(200) COMMENT '标题',
                                `content` TEXT COMMENT '内容',
                                `work_content` TEXT COMMENT '工作内容',
                                `issues` TEXT COMMENT '问题与风险',
                                `next_plan` TEXT COMMENT '下一步计划',
                                `location` VARCHAR(200) COMMENT '位置',
                                `latitude` DECIMAL(10,7) COMMENT '纬度',
                                `longitude` DECIMAL(10,7) COMMENT '经度',
                                `weather` VARCHAR(50) COMMENT '天气',
                                `temperature` DECIMAL(5,2) COMMENT '温度',
                                `status` VARCHAR(20) DEFAULT 'draft' COMMENT '状态: draft-草稿, submitted-已提交, approved-已审批',
                                `ai_analysis` JSON COMMENT 'AI分析结果',
                                `tags` JSON COMMENT '标签',
                                `extra_data` JSON COMMENT '扩展数据',
                                `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                                `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
                                PRIMARY KEY (`id`),
                                KEY `idx_project_id` (`project_id`),
                                KEY `idx_creator_id` (`creator_id`),
                                KEY `idx_report_date` (`report_date`),
                                KEY `idx_report_type` (`report_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='日报/数据录入表';

-- 文件附件表
DROP TABLE IF EXISTS `file_attachment`;
CREATE TABLE `file_attachment` (
                                   `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
                                   `file_name` VARCHAR(200) NOT NULL COMMENT '文件名称',
                                   `original_name` VARCHAR(200) COMMENT '原始文件名',
                                   `file_path` VARCHAR(500) NOT NULL COMMENT '文件路径',
                                   `file_url` VARCHAR(500) COMMENT '文件URL',
                                   `file_type` VARCHAR(50) COMMENT '文件类型(MIME)',
                                   `file_size` BIGINT COMMENT '文件大小(字节)',
                                   `storage_type` VARCHAR(20) DEFAULT 'local' COMMENT '存储类型: local-本地, oss-对象存储, minio-MinIO',
                                   `related_type` VARCHAR(50) COMMENT '关联类型: project, task, work_order, risk, report',
                                   `related_id` BIGINT COMMENT '关联ID',
                                   `uploader_id` BIGINT COMMENT '上传人ID',
                                   `exif_data` JSON COMMENT 'EXIF信息(照片专用)',
                                   `ai_analysis` JSON COMMENT 'AI分析结果',
                                   `extra_data` JSON COMMENT '扩展数据',
                                   `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                   `deleted` TINYINT DEFAULT 0 COMMENT '删除标记',
                                   PRIMARY KEY (`id`),
                                   KEY `idx_related` (`related_type`, `related_id`),
                                   KEY `idx_uploader_id` (`uploader_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='文件附件表';

-- =====================================================
-- 8. 资源管理表
-- =====================================================

-- 资源表(项目资源抽象: 人力、物料、设备、资金等)
-- 简化设计：移除resource_type表，使用resource_type字符串字段
DROP TABLE IF EXISTS resource;
CREATE TABLE resource (
                          id BIGSERIAL PRIMARY KEY,
                          resource_code VARCHAR(50) COMMENT '资源编号',
                          project_id BIGINT NOT NULL COMMENT '项目ID',
                          resource_type VARCHAR(50) COMMENT '资源类型: human-人力, material-物料, equipment-设备, software-软件, finance-资金, other-其他',
                          resource_name VARCHAR(200) NOT NULL COMMENT '资源名称',
                          description TEXT COMMENT '资源描述',
                          specification VARCHAR(200) COMMENT '规格型号',
                          unit VARCHAR(20) COMMENT '单位',
                          plan_quantity DECIMAL(12,2) COMMENT '计划数量',
                          actual_quantity DECIMAL(12,2) COMMENT '实际数量',
                          unit_price DECIMAL(12,2) COMMENT '单价',
                          currency VARCHAR(10) DEFAULT 'CNY' COMMENT '币种',
                          supplier VARCHAR(200) COMMENT '供应商/来源',
                          status VARCHAR(20) DEFAULT 'planned' COMMENT '状态: planned-计划中, requested-已申请, approved-已批准, procuring-采购中, arrived-已到货, in_use-使用中, completed-已完成',
                          plan_arrive_date DATE COMMENT '计划到位日期',
                          actual_arrive_date DATE COMMENT '实际到位日期',
                          responsible_id BIGINT COMMENT '负责人ID',
                          location VARCHAR(200) COMMENT '存放位置',
                          tags JSONB COMMENT '标签',
                          extra_data JSONB COMMENT '扩展数据',
                          create_by BIGINT COMMENT '创建人',
                          create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                          update_by BIGINT COMMENT '更新人',
                          update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                          deleted SMALLINT DEFAULT 0 COMMENT '删除标记',

                          CONSTRAINT fk_resource_project FOREIGN KEY (project_id) REFERENCES project(id) ON DELETE CASCADE
);

CREATE INDEX idx_resource_project ON resource(project_id);
CREATE INDEX idx_resource_type ON resource(resource_type);
CREATE INDEX idx_resource_status ON resource(status);

COMMENT ON TABLE resource IS '资源表 - 项目资源统一管理(人力、物料、设备、资金等)';

-- =====================================================
-- 9. 流程卡点分析表
-- =====================================================

-- 流程卡点记录表
DROP TABLE IF EXISTS `bottleneck_record`;
CREATE TABLE `bottleneck_record` (
                                     `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
                                     `project_id` BIGINT NOT NULL COMMENT '项目ID',
                                     `user_id` BIGINT NOT NULL COMMENT '用户ID',
                                     `bottleneck_type` VARCHAR(50) NOT NULL COMMENT '卡点类型: resource-资源不足, approval-审批延迟, dependency-依赖阻塞, skill-技能不足, external-外部因素, other-其他',
                                     `related_type` VARCHAR(50) COMMENT '关联类型: task, work_order, risk',
                                     `related_id` BIGINT COMMENT '关联ID',
                                     `description` TEXT COMMENT '卡点描述',
                                     `impact_level` VARCHAR(20) DEFAULT 'medium' COMMENT '影响程度: critical-严重, high-高, medium-中, low-低',
                                     `status` VARCHAR(20) DEFAULT 'pending' COMMENT '状态: pending-待处理, resolving-解决中, resolved-已解决',
                                     `start_time` DATETIME COMMENT '卡点开始时间',
                                     `resolved_time` DATETIME COMMENT '解决时间',
                                     `duration_hours` DECIMAL(8,2) COMMENT '持续时长(小时)',
                                     `solution` TEXT COMMENT '解决方案',
                                     `extra_data` JSON COMMENT '扩展数据',
                                     `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                     `update_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
                                     PRIMARY KEY (`id`),
                                     KEY `idx_project_id` (`project_id`),
                                     KEY `idx_user_id` (`user_id`),
                                     KEY `idx_bottleneck_type` (`bottleneck_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='流程卡点记录表';

-- =====================================================
-- 10. AI服务相关表
-- =====================================================

-- AI文档向量表 (用于RAG知识库)
DROP TABLE IF EXISTS ai_document;
CREATE TABLE ai_document (
                             id BIGSERIAL PRIMARY KEY,
                             doc_id UUID DEFAULT uuid_generate_v4() COMMENT '文档唯一标识',

    -- 关联关系
                             project_id BIGINT COMMENT '关联项目ID',
                             timeline_node_id BIGINT COMMENT '关联时间节点ID',
                             kb_id BIGINT COMMENT '关联知识库ID',
    -- 文档来源
                             source_type VARCHAR(50) NOT NULL COMMENT '来源类型: project-项目文档, risk-风险文档, ticket-工单, report-日报, upload-上传文件, knowledge-知识库, chat-对话记录',
                             source_id BIGINT COMMENT '来源记录ID',

    -- 文档内容
                             title VARCHAR(500) COMMENT '文档标题',
                             content TEXT NOT NULL COMMENT '文档内容(纯文本)',
                             content_raw TEXT COMMENT '原始内容(带格式)',
                             summary TEXT COMMENT 'AI生成的摘要',

    -- 向量嵌入 (1536维适配OpenAI, 可调整为其他维度)
                             embedding vector(1536) COMMENT '向量嵌入',

    -- 文档元数据
                             doc_type VARCHAR(50) COMMENT '文档类型: requirement-需求, design-设计, plan-计划, report-报告, contract-合同, photo-照片, other-其他',
                             language VARCHAR(10) DEFAULT 'zh' COMMENT '语言: zh-中文, en-英文',
                             file_type VARCHAR(50) COMMENT '文件类型: pdf, doc, txt, md, jpg, png等',
                             file_size BIGINT COMMENT '文件大小(字节)',
                             file_path VARCHAR(500) COMMENT '文件存储路径',

    -- 时间信息 (用于时间维度检索)
                             doc_date DATE COMMENT '文档日期(如日报日期、照片拍摄日期)',
                             doc_datetime TIMESTAMP COMMENT '文档时间戳',

    -- 分块信息(大文档分块存储)
                             chunk_index INT DEFAULT 0 COMMENT '分块序号',
                             chunk_total INT DEFAULT 1 COMMENT '总分块数',
                             chunk_parent_id BIGINT COMMENT '父文档ID(分块时使用)',

    -- 标签和分类
                             tags JSONB COMMENT '标签数组',
                             category VARCHAR(100) COMMENT '分类',

    -- 使用统计
                             view_count INT DEFAULT 0 COMMENT '查看次数',
                             query_count INT DEFAULT 0 COMMENT '被检索次数',
                             last_queried_at TIMESTAMP COMMENT '最后被检索时间',

    -- 状态
                             status VARCHAR(20) DEFAULT 'active' COMMENT '状态: active-可用, processing-处理中, error-错误, archived-归档',
                             error_message TEXT COMMENT '错误信息',

    -- 创建信息
                             create_by BIGINT COMMENT '创建人',
                             create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                             update_by BIGINT COMMENT '更新人',
                             update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                             deleted SMALLINT DEFAULT 0 COMMENT '删除标记',

    -- 外键约束
                             CONSTRAINT fk_ai_doc_project FOREIGN KEY (project_id) REFERENCES project(id) ON DELETE SET NULL,
                             CONSTRAINT fk_ai_doc_timeline FOREIGN KEY (timeline_node_id) REFERENCES project_timeline(id) ON DELETE SET NULL,
                             CONSTRAINT fk_ai_doc_kb FOREIGN KEY (kb_id) REFERENCES ai_knowledge_base(id) ON DELETE SET NULL
);

-- 创建向量索引 (使用IVFFlat或HNSW)
-- IVFFlat: 适合中等数据量, 内存占用小
-- HNSW: 适合大数据量, 查询更快但内存占用大
CREATE INDEX idx_ai_document_embedding ON ai_document
    USING ivfflat (embedding vector_cosine_ops)
    WITH (lists = 100);

-- 创建其他常用索引
CREATE INDEX idx_ai_doc_project ON ai_document(project_id) WHERE deleted = 0;
CREATE INDEX idx_ai_doc_timeline ON ai_document(timeline_node_id) WHERE deleted = 0;
CREATE INDEX idx_ai_doc_kb ON ai_document(kb_id) WHERE deleted = 0;
CREATE INDEX idx_ai_doc_source ON ai_document(source_type, source_id) WHERE deleted = 0;
CREATE INDEX idx_ai_doc_status ON ai_document(status);
CREATE INDEX idx_ai_doc_type ON ai_document(doc_type);
CREATE INDEX idx_ai_doc_tags ON ai_document USING GIN(tags);

COMMENT ON TABLE ai_document IS 'AI文档向量表 - 存储所有用于RAG的文档向量';

-- AI对话记录表 (合并会话管理功能，无需单独的session表)
DROP TABLE IF EXISTS ai_chat_history;
CREATE TABLE ai_chat_history (
                                 id BIGSERIAL PRIMARY KEY,

    -- 会话标识 (使用UUID标识一个会话，无需单独的session表)
                                 session_id UUID NOT NULL COMMENT '会话ID(同一session_id的消息属于同一会话)',
                                 session_title VARCHAR(200) COMMENT '会话标题(首条消息自动生成)',

                                 user_id BIGINT NOT NULL COMMENT '用户ID',
                                 project_id BIGINT COMMENT '关联项目ID',
                                 timeline_node_id BIGINT COMMENT '关联时间节点ID',

    -- 消息内容
                                 role VARCHAR(20) NOT NULL COMMENT '角色: user-用户, assistant-助手, system-系统',
                                 content TEXT NOT NULL COMMENT '对话内容',
                                 content_embedding vector(1536) COMMENT '对话内容的向量表示(用于语义检索历史对话)',

    -- 引用的知识库文档
                                 referenced_doc_ids BIGINT[] COMMENT '引用的文档ID列表',

    -- 上下文配置
                                 system_prompt TEXT COMMENT '系统提示词(仅role=system时有值)',
                                 context_window INT DEFAULT 10 COMMENT '该会话的上下文窗口大小',
                                 kb_ids JSONB COMMENT '关联的知识库ID列表',

    -- 模型信息
                                 model VARCHAR(50) COMMENT '使用的模型',
                                 tokens_used INT COMMENT '消耗Token数',
                                 response_time INT COMMENT '响应时间(ms)',

    -- 用户反馈
                                 feedback_score INT COMMENT '反馈评分(1-5)',
                                 feedback_content TEXT COMMENT '反馈内容',

    -- 统计
                                 message_index INT DEFAULT 0 COMMENT '消息在会话中的序号',

                                 create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',

                                 CONSTRAINT fk_chat_project FOREIGN KEY (project_id) REFERENCES project(id) ON DELETE SET NULL,
                                 CONSTRAINT fk_chat_timeline FOREIGN KEY (timeline_node_id) REFERENCES project_timeline(id) ON DELETE SET NULL
);

-- 索引
CREATE INDEX idx_chat_session ON ai_chat_history(session_id);
CREATE INDEX idx_chat_user ON ai_chat_history(user_id);
CREATE INDEX idx_chat_project ON ai_chat_history(project_id);
CREATE INDEX idx_chat_timeline ON ai_chat_history(timeline_node_id);
CREATE INDEX idx_chat_time ON ai_chat_history(create_time);
CREATE INDEX idx_chat_role ON ai_chat_history(session_id, role);

COMMENT ON TABLE ai_chat_history IS 'AI对话记录表 - 包含会话管理功能';

-- AI分析结果表
DROP TABLE IF EXISTS ai_analysis_result;
CREATE TABLE ai_analysis_result (
                                    id BIGSERIAL PRIMARY KEY,
                                    analysis_type VARCHAR(50) NOT NULL COMMENT '分析类型: photo_analysis-照片分析, risk_prediction-风险预测, progress_analysis-进度分析, text_extraction-文本提取, embedding-向量生成',
                                    related_type VARCHAR(50) COMMENT '关联类型',
                                    related_id BIGINT COMMENT '关联ID',

    -- 输入输出
                                    input_data JSONB COMMENT '输入数据',
                                    result_data JSONB COMMENT '分析结果',
                                    result_embedding vector(1536) COMMENT '分析结果的向量表示',

    -- 模型信息
                                    confidence DECIMAL(5,2) COMMENT '置信度(0-100%)',
                                    model_name VARCHAR(100) COMMENT '模型名称',
                                    model_version VARCHAR(50) COMMENT '模型版本',
                                    processing_time INT COMMENT '处理时间(ms)',

    -- 成本和Token
                                    input_tokens INT COMMENT '输入token数',
                                    output_tokens INT COMMENT '输出token数',
                                    cost DECIMAL(10,6) COMMENT '成本(美元)',

                                    status VARCHAR(20) DEFAULT 'completed' COMMENT '状态: processing-处理中, completed-已完成, failed-失败',
                                    error_message TEXT COMMENT '错误信息',

                                    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',

                                    CONSTRAINT fk_analysis_project FOREIGN KEY (related_id) REFERENCES project(id) ON DELETE SET NULL
);

CREATE INDEX idx_analysis_type ON ai_analysis_result(analysis_type);
CREATE INDEX idx_analysis_related ON ai_analysis_result(related_type, related_id);
CREATE INDEX idx_analysis_time ON ai_analysis_result(create_time);

COMMENT ON TABLE ai_analysis_result IS 'AI分析结果表';

-- =====================================================
-- 11. 系统配置与日志表
-- =====================================================

-- 系统配置表
DROP TABLE IF EXISTS sys_config;
CREATE TABLE sys_config (
                            id BIGSERIAL PRIMARY KEY,
                            config_key VARCHAR(100) NOT NULL UNIQUE COMMENT '配置键',
                            config_value TEXT COMMENT '配置值',
                            config_type VARCHAR(50) DEFAULT 'system' COMMENT '配置类型: system-系统, business-业务, ai-AI配置',
                            description TEXT COMMENT '配置描述',
                            status SMALLINT DEFAULT 1 COMMENT '状态',
                            create_by BIGINT COMMENT '创建人',
                            create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                            update_by BIGINT COMMENT '更新人',
                            update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
                            deleted SMALLINT DEFAULT 0 COMMENT '删除标记'
);

COMMENT ON TABLE sys_config IS '系统配置表';

-- 操作日志表
DROP TABLE IF EXISTS sys_operation_log;
CREATE TABLE sys_operation_log (
                                   id BIGSERIAL PRIMARY KEY,
                                   trace_id VARCHAR(100) COMMENT '追踪ID',
                                   user_id BIGINT COMMENT '用户ID',
                                   `module` VARCHAR(50) COMMENT '模块',
                                   `operation` VARCHAR(100) COMMENT '操作',
                                   `method` VARCHAR(200) COMMENT '方法',
                                   `request_url` VARCHAR(500) COMMENT '请求URL',
                                   `request_method` VARCHAR(10) COMMENT '请求方法',
                                   `request_params` TEXT COMMENT '请求参数',
                                   `response_data` TEXT COMMENT '响应数据',
                                   `ip` VARCHAR(50) COMMENT 'IP地址',
                                   `user_agent` VARCHAR(500) COMMENT '用户代理',
                                   `execute_time` INT COMMENT '执行时长(ms)',
                                   `status` TINYINT DEFAULT 1 COMMENT '状态: 1-成功, 0-失败',
                                   `error_msg` TEXT COMMENT '错误信息',
                                   `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                   PRIMARY KEY (`id`),
                                   KEY `idx_trace_id` (`trace_id`),
                                   KEY `idx_user_id` (`user_id`),
                                   KEY `idx_module` (`module`),
                                   KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='操作日志表';

-- 通知消息表
DROP TABLE IF EXISTS `sys_notification`;
CREATE TABLE `sys_notification` (
                                    `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
                                    `user_id` BIGINT NOT NULL COMMENT '接收用户ID',
                                    `title` VARCHAR(200) NOT NULL COMMENT '标题',
                                    `content` TEXT COMMENT '内容',
                                    `notification_type` VARCHAR(50) COMMENT '通知类型: system-系统, task-任务, risk-风险, work_order-工单',
                                    `related_type` VARCHAR(50) COMMENT '关联类型',
                                    `related_id` BIGINT COMMENT '关联ID',
                                    `priority` VARCHAR(20) DEFAULT 'normal' COMMENT '优先级: urgent-紧急, high-高, normal-普通, low-低',
                                    `is_read` TINYINT DEFAULT 0 COMMENT '是否已读: 1-是, 0-否',
                                    `read_time` DATETIME COMMENT '阅读时间',
                                    `sender_id` BIGINT COMMENT '发送人ID',
                                    `extra_data` JSON COMMENT '扩展数据',
                                    `create_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
                                    PRIMARY KEY (`id`),
                                    KEY `idx_user_id` (`user_id`),
                                    KEY `idx_is_read` (`is_read`),
                                    KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='通知消息表';