-- ============================================
-- 考培练系统数据库初始化脚本
-- 版本：1.0.0
-- 更新时间：2024-12
-- ============================================

-- 创建数据库（如果不存在）
CREATE DATABASE IF NOT EXISTS `kaopeilian` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE `kaopeilian`;

-- ============================================
-- 一、用户管理模块
-- ============================================

-- 1.1 用户表
CREATE TABLE IF NOT EXISTS `users` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `username` VARCHAR(50) NOT NULL UNIQUE COMMENT '用户名',
    `email` VARCHAR(100) NOT NULL UNIQUE COMMENT '邮箱',
    `phone` VARCHAR(20) UNIQUE COMMENT '手机号',
    `password_hash` VARCHAR(200) NOT NULL COMMENT '密码哈希',
    `full_name` VARCHAR(100) COMMENT '姓名',
    `gender` VARCHAR(10) COMMENT '性别: male/female',
    `avatar_url` VARCHAR(500) COMMENT '头像URL',
    `bio` TEXT COMMENT '个人简介',
    `school` VARCHAR(100) COMMENT '学校',
    `major` VARCHAR(100) COMMENT '专业',
    `role` VARCHAR(20) DEFAULT 'trainee' COMMENT '系统角色: admin, manager, trainee',
    `is_active` BOOLEAN DEFAULT TRUE COMMENT '是否激活',
    `is_verified` BOOLEAN DEFAULT FALSE COMMENT '是否验证',
    `last_login_at` DATETIME COMMENT '最后登录时间',
    `password_changed_at` DATETIME COMMENT '密码修改时间',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `is_deleted` BOOLEAN DEFAULT FALSE COMMENT '是否删除',
    `deleted_at` DATETIME NULL COMMENT '删除时间',
    INDEX idx_role (role),
    INDEX idx_is_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户表';

-- 1.2 团队表
CREATE TABLE IF NOT EXISTS `teams` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(100) NOT NULL UNIQUE COMMENT '团队名称',
    `code` VARCHAR(50) NOT NULL UNIQUE COMMENT '团队代码',
    `description` TEXT COMMENT '团队描述',
    `team_type` VARCHAR(50) DEFAULT 'department' COMMENT '团队类型: department, project, study_group',
    `is_active` BOOLEAN DEFAULT TRUE COMMENT '是否激活',
    `leader_id` INT COMMENT '负责人ID',
    `parent_id` INT COMMENT '父团队ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (leader_id) REFERENCES users(id) ON DELETE SET NULL,
    FOREIGN KEY (parent_id) REFERENCES teams(id) ON DELETE CASCADE,
    INDEX idx_team_type (team_type),
    INDEX idx_is_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='团队表';

-- 1.3 用户团队关联表
CREATE TABLE IF NOT EXISTS `user_teams` (
    `user_id` INT NOT NULL,
    `team_id` INT NOT NULL,
    `role` VARCHAR(50) DEFAULT 'member' COMMENT '团队角色: member, leader',
    `joined_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '加入时间',
    PRIMARY KEY (user_id, team_id),
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (team_id) REFERENCES teams(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='用户团队关联表';

-- ============================================
-- 二、组织与岗位管理模块
-- ============================================

-- 2.0 岗位表
CREATE TABLE IF NOT EXISTS `positions` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(100) NOT NULL COMMENT '岗位名称',
    `code` VARCHAR(100) NOT NULL UNIQUE COMMENT '岗位编码',
    `description` TEXT COMMENT '岗位描述',
    `parent_id` INT NULL COMMENT '上级岗位ID',
    `status` VARCHAR(20) NOT NULL DEFAULT 'active' COMMENT '状态: active/inactive',
    `skills` JSON NULL COMMENT '核心技能',
    `level` VARCHAR(20) NULL COMMENT '岗位等级: junior/intermediate/senior/expert',
    `sort_order` INT DEFAULT 0 COMMENT '排序',
    `is_deleted` BOOLEAN DEFAULT FALSE COMMENT '是否删除',
    `deleted_at` DATETIME NULL COMMENT '删除时间',
    `created_by` INT NULL COMMENT '创建人ID',
    `updated_by` INT NULL COMMENT '更新人ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (parent_id) REFERENCES positions(id) ON DELETE SET NULL,
    INDEX idx_positions_name (name)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='岗位表';

-- 插入轻医美连锁岗位（按层级关系）
-- 注意：需要按顺序插入以正确设置parent_id

-- 第一层：区域经理
INSERT INTO positions (name, code, description, status, skills, level, sort_order) VALUES
('区域经理', 'region_manager', '负责多家门店的运营管理和业绩达成', 'active', '["团队管理", "业绩分析", "战略规划", "客户关系"]', 'expert', 10);

-- 获取区域经理ID
SET @region_manager_id = LAST_INSERT_ID();

-- 第二层：店长
INSERT INTO positions (name, code, description, parent_id, status, skills, level, sort_order) VALUES
('店长', 'store_manager', '负责门店日常运营管理，团队建设和业绩达成', @region_manager_id, 'active', '["门店管理", "团队建设", "销售管理", "客户维护"]', 'senior', 20);

-- 获取店长ID
SET @store_manager_id = LAST_INSERT_ID();

-- 第三层：各职能岗位
INSERT INTO positions (name, code, description, parent_id, status, skills, level, sort_order) VALUES
('美容顾问', 'beauty_consultant', '为客户提供专业的美容咨询和方案设计', @store_manager_id, 'active', '["产品知识", "销售技巧", "方案设计", "客户沟通"]', 'intermediate', 30),
('医美咨询师', 'medical_beauty_consultant', '提供医疗美容项目咨询和方案制定', @store_manager_id, 'active', '["医美知识", "风险评估", "方案设计", "合规意识"]', 'senior', 35),
('美容技师', 'beauty_therapist', '为客户提供专业的美容护理服务', @store_manager_id, 'active', '["护肤技术", "仪器操作", "手法技巧", "服务意识"]', 'intermediate', 40),
('护士', 'nurse', '协助医生进行医美项目操作，负责术后护理', @store_manager_id, 'active', '["护理技术", "无菌操作", "应急处理", "医疗知识"]', 'intermediate', 45),
('前台接待', 'receptionist', '负责客户接待、预约管理和前台事务', @store_manager_id, 'active', '["接待礼仪", "沟通能力", "信息管理", "服务意识"]', 'junior', 50),
('市场专员', 'marketing_specialist', '负责门店营销活动策划和执行', @store_manager_id, 'active', '["活动策划", "社媒运营", "数据分析", "创意设计"]', 'intermediate', 60);

-- ============================================
-- 二、课程管理模块
-- ============================================

-- 2.1 课程表
CREATE TABLE IF NOT EXISTS `courses` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(200) NOT NULL COMMENT '课程名称',
    `description` TEXT COMMENT '课程描述',
    `category` ENUM('technology', 'management', 'business', 'general') DEFAULT 'general' COMMENT '课程分类',
    `status` ENUM('draft', 'published', 'archived') DEFAULT 'draft' COMMENT '课程状态',
    `cover_image` VARCHAR(500) COMMENT '封面图片URL',
    `duration_hours` FLOAT COMMENT '课程时长(小时)',
    `difficulty_level` INT COMMENT '难度等级(1-5)',
    `tags` JSON COMMENT '标签列表',
    `published_at` DATETIME COMMENT '发布时间',
    `publisher_id` INT COMMENT '发布人ID',
    `sort_order` INT DEFAULT 0 COMMENT '排序顺序',
    `is_featured` BOOLEAN DEFAULT FALSE COMMENT '是否推荐',
    `is_deleted` BOOLEAN DEFAULT FALSE COMMENT '是否删除',
    `deleted_at` DATETIME COMMENT '删除时间',
    `created_by` INT COMMENT '创建人ID',
    `updated_by` INT COMMENT '更新人ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_status (status),
    INDEX idx_category (category),
    INDEX idx_is_featured (is_featured),
    INDEX idx_is_deleted (is_deleted),
    INDEX idx_sort_order (sort_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='课程表';

-- 2.2 课程资料表
CREATE TABLE IF NOT EXISTS `course_materials` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `course_id` INT NOT NULL COMMENT '课程ID',
    `name` VARCHAR(200) NOT NULL COMMENT '资料名称',
    `description` TEXT COMMENT '资料描述',
    `file_url` VARCHAR(500) NOT NULL COMMENT '文件URL',
    `file_type` VARCHAR(50) NOT NULL COMMENT '文件类型',
    `file_size` INT NOT NULL COMMENT '文件大小(字节)',
    `sort_order` INT DEFAULT 0 COMMENT '排序顺序',
    `is_deleted` BOOLEAN DEFAULT FALSE COMMENT '是否删除',
    `deleted_at` DATETIME COMMENT '删除时间',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
    INDEX idx_course_id (course_id),
    INDEX idx_is_deleted (is_deleted)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='课程资料表';

-- 2.3 知识点表
CREATE TABLE IF NOT EXISTS `knowledge_points` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `course_id` INT NOT NULL COMMENT '课程ID',
    `name` VARCHAR(200) NOT NULL COMMENT '知识点名称',
    `description` TEXT COMMENT '知识点描述',
    `parent_id` INT COMMENT '父知识点ID',
    `level` INT DEFAULT 1 COMMENT '层级深度',
    `path` VARCHAR(500) COMMENT '路径(如: 1.2.3)',
    `sort_order` INT DEFAULT 0 COMMENT '排序顺序',
    `weight` FLOAT DEFAULT 1.0 COMMENT '权重',
    `is_required` BOOLEAN DEFAULT TRUE COMMENT '是否必修',
    `estimated_hours` FLOAT COMMENT '预计学习时间(小时)',
    `is_deleted` BOOLEAN DEFAULT FALSE COMMENT '是否删除',
    `deleted_at` DATETIME COMMENT '删除时间',
    `created_by` INT NULL COMMENT '创建人ID',
    `updated_by` INT NULL COMMENT '更新人ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
    FOREIGN KEY (parent_id) REFERENCES knowledge_points(id) ON DELETE CASCADE,
    INDEX idx_course_id (course_id),
    INDEX idx_parent_id (parent_id),
    INDEX idx_is_deleted (is_deleted),
    INDEX idx_sort_order (sort_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='知识点表';

-- 2.4 成长路径表
CREATE TABLE IF NOT EXISTS `growth_paths` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(200) NOT NULL COMMENT '路径名称',
    `description` TEXT COMMENT '路径描述',
    `target_role` VARCHAR(100) COMMENT '目标角色',
    `courses` JSON COMMENT '课程列表[{course_id, order, is_required}]',
    `estimated_duration_days` INT COMMENT '预计完成天数',
    `is_active` BOOLEAN DEFAULT TRUE COMMENT '是否启用',
    `sort_order` INT DEFAULT 0 COMMENT '排序顺序',
    `is_deleted` BOOLEAN DEFAULT FALSE COMMENT '是否删除',
    `deleted_at` DATETIME COMMENT '删除时间',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_is_active (is_active),
    INDEX idx_is_deleted (is_deleted),
    INDEX idx_sort_order (sort_order)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='成长路径表';

-- 资料知识点关联表
CREATE TABLE `material_knowledge_points` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `material_id` INT NOT NULL COMMENT '资料ID',
    `knowledge_point_id` INT NOT NULL COMMENT '知识点ID',
    `sort_order` INT DEFAULT 0 COMMENT '排序顺序',
    `is_ai_generated` BOOLEAN DEFAULT FALSE COMMENT '是否AI生成',
    `is_deleted` BOOLEAN DEFAULT FALSE COMMENT '是否删除',
    `deleted_at` DATETIME COMMENT '删除时间',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    UNIQUE KEY `idx_material_knowledge` (`material_id`, `knowledge_point_id`),
    FOREIGN KEY (material_id) REFERENCES course_materials(id) ON DELETE CASCADE,
    FOREIGN KEY (knowledge_point_id) REFERENCES knowledge_points(id) ON DELETE CASCADE,
    INDEX idx_material_id (material_id),
    INDEX idx_knowledge_point_id (knowledge_point_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='资料知识点关联表';

-- ============================================
-- 三、考试模块
-- ============================================

-- 3.1 题目表
CREATE TABLE IF NOT EXISTS `questions` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `course_id` INT NOT NULL COMMENT '课程ID',
    `question_type` VARCHAR(20) NOT NULL COMMENT '题目类型: single_choice, multiple_choice, true_false, fill_blank, essay',
    `title` TEXT NOT NULL COMMENT '题目标题',
    `content` TEXT COMMENT '题目内容',
    `options` JSON COMMENT '选项（JSON格式）',
    `correct_answer` TEXT NOT NULL COMMENT '正确答案',
    `explanation` TEXT COMMENT '答案解释',
    `score` FLOAT DEFAULT 10.0 COMMENT '分值',
    `difficulty` VARCHAR(10) DEFAULT 'medium' COMMENT '难度等级: easy, medium, hard',
    `tags` JSON COMMENT '标签（JSON格式）',
    `usage_count` INT DEFAULT 0 COMMENT '使用次数',
    `correct_count` INT DEFAULT 0 COMMENT '答对次数',
    `is_active` BOOLEAN DEFAULT TRUE COMMENT '是否启用',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
    INDEX idx_course_id (course_id),
    INDEX idx_question_type (question_type),
    INDEX idx_difficulty (difficulty),
    INDEX idx_is_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='题目表';

-- 3.2 考试记录表
CREATE TABLE IF NOT EXISTS `exams` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `user_id` INT NOT NULL COMMENT '用户ID',
    `course_id` INT NOT NULL COMMENT '课程ID',
    `exam_name` VARCHAR(255) NOT NULL COMMENT '考试名称',
    `question_count` INT DEFAULT 10 COMMENT '题目数量',
    `total_score` FLOAT DEFAULT 100.0 COMMENT '总分',
    `pass_score` FLOAT DEFAULT 60.0 COMMENT '及格分',
    `start_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '开始时间',
    `end_time` DATETIME COMMENT '结束时间',
    `duration_minutes` INT DEFAULT 60 COMMENT '考试时长（分钟）',
    `score` FLOAT COMMENT '得分',
    `is_passed` BOOLEAN COMMENT '是否通过',
    `status` VARCHAR(20) DEFAULT 'started' COMMENT '状态: started, submitted, timeout',
    `questions` JSON COMMENT '题目数据（JSON格式）',
    `answers` JSON COMMENT '答案数据（JSON格式）',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (course_id) REFERENCES courses(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id),
    INDEX idx_course_id (course_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='考试记录表';

-- 3.3 考试结果详情表
CREATE TABLE IF NOT EXISTS `exam_results` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `exam_id` INT NOT NULL COMMENT '考试ID',
    `question_id` INT NOT NULL COMMENT '题目ID',
    `user_answer` TEXT COMMENT '用户答案',
    `is_correct` BOOLEAN DEFAULT FALSE COMMENT '是否正确',
    `score` FLOAT DEFAULT 0.0 COMMENT '得分',
    `answer_time` INT COMMENT '答题时长（秒）',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (exam_id) REFERENCES exams(id) ON DELETE CASCADE,
    FOREIGN KEY (question_id) REFERENCES questions(id) ON DELETE CASCADE,
    INDEX idx_exam_id (exam_id),
    INDEX idx_question_id (question_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='考试结果详情表';

-- ============================================
-- 四、陪练模块
-- ============================================

-- 4.1 陪练场景表
CREATE TABLE IF NOT EXISTS `training_scenes` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `name` VARCHAR(100) NOT NULL COMMENT '场景名称',
    `description` TEXT COMMENT '场景描述',
    `category` VARCHAR(50) NOT NULL COMMENT '场景分类',
    `ai_config` JSON COMMENT 'AI配置（如Coze Bot ID等）',
    `prompt_template` TEXT COMMENT '提示词模板',
    `evaluation_criteria` JSON COMMENT '评估标准',
    `status` ENUM('DRAFT', 'ACTIVE', 'INACTIVE') DEFAULT 'DRAFT' COMMENT '场景状态',
    `is_public` BOOLEAN DEFAULT TRUE COMMENT '是否公开',
    `required_level` INT COMMENT '所需用户等级',
    `is_deleted` BOOLEAN DEFAULT FALSE COMMENT '是否删除',
    `deleted_at` DATETIME COMMENT '删除时间',
    `created_by` BIGINT COMMENT '创建人ID',
    `updated_by` BIGINT COMMENT '更新人ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_status (status),
    INDEX idx_category (category),
    INDEX idx_is_public (is_public),
    INDEX idx_is_deleted (is_deleted)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='陪练场景表';

-- 4.2 陪练会话表
CREATE TABLE IF NOT EXISTS `training_sessions` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `user_id` INT NOT NULL COMMENT '用户ID',
    `scene_id` INT NOT NULL COMMENT '场景ID',
    `coze_conversation_id` VARCHAR(100) COMMENT 'Coze会话ID',
    `start_time` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '开始时间',
    `end_time` DATETIME COMMENT '结束时间',
    `duration_seconds` INT COMMENT '持续时长（秒）',
    `status` ENUM('CREATED', 'IN_PROGRESS', 'COMPLETED', 'CANCELLED', 'ERROR') DEFAULT 'CREATED' COMMENT '会话状态',
    `session_config` JSON COMMENT '会话配置',
    `total_score` FLOAT COMMENT '总分',
    `evaluation_result` JSON COMMENT '评估结果详情',
    `created_by` BIGINT COMMENT '创建人ID',
    `updated_by` BIGINT COMMENT '更新人ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (scene_id) REFERENCES training_scenes(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id),
    INDEX idx_scene_id (scene_id),
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='陪练会话表';

-- 4.3 陪练消息表
CREATE TABLE IF NOT EXISTS `training_messages` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `session_id` INT NOT NULL COMMENT '会话ID',
    `role` ENUM('USER', 'ASSISTANT', 'SYSTEM') NOT NULL COMMENT '消息角色',
    `type` ENUM('TEXT', 'VOICE', 'SYSTEM') NOT NULL COMMENT '消息类型',
    `content` TEXT NOT NULL COMMENT '消息内容',
    `voice_url` VARCHAR(500) COMMENT '语音文件URL',
    `voice_duration` FLOAT COMMENT '语音时长（秒）',
    `message_metadata` JSON COMMENT '消息元数据',
    `coze_message_id` VARCHAR(100) COMMENT 'Coze消息ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (session_id) REFERENCES training_sessions(id) ON DELETE CASCADE,
    INDEX idx_session_id (session_id),
    INDEX idx_role (role)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='陪练消息表';

-- 4.4 陪练报告表
CREATE TABLE IF NOT EXISTS `training_reports` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `session_id` INT NOT NULL UNIQUE COMMENT '会话ID',
    `user_id` INT NOT NULL COMMENT '用户ID',
    `overall_score` FLOAT NOT NULL COMMENT '总体得分',
    `dimension_scores` JSON NOT NULL COMMENT '各维度得分',
    `strengths` JSON NOT NULL COMMENT '优势点',
    `weaknesses` JSON NOT NULL COMMENT '待改进点',
    `suggestions` JSON NOT NULL COMMENT '改进建议',
    `detailed_analysis` TEXT COMMENT '详细分析',
    `transcript` TEXT COMMENT '对话文本记录',
    `statistics` JSON COMMENT '统计数据',
    `created_by` BIGINT COMMENT '创建人ID',
    `updated_by` BIGINT COMMENT '更新人ID',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    FOREIGN KEY (session_id) REFERENCES training_sessions(id) ON DELETE CASCADE,
    INDEX idx_user_id (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='陪练报告表';

-- ============================================
-- 五、初始测试数据
-- ============================================

-- 插入测试用户
INSERT INTO users (username, email, phone, password_hash, full_name, role, is_active, is_verified) VALUES
('superadmin', 'superadmin@kaopeilian.com', '13800000001', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewKyNiQdP/sQj6C6', '超级管理员', 'admin', TRUE, TRUE),
('admin', 'admin@kaopeilian.com', '13800000002', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewKyNiQdP/sQj6C6', '系统管理员', 'admin', TRUE, TRUE),
('testuser', 'testuser@kaopeilian.com', '13800000003', '$2b$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewKyNiQdP/sQj6C6', '测试学员', 'trainee', TRUE, TRUE);

-- 插入测试团队
INSERT INTO teams (name, code, description, team_type, leader_id) VALUES
('技术部', 'TECH', '负责技术研发和维护', 'department', 2),
('产品部', 'PROD', '负责产品设计和规划', 'department', 2),
('Python学习小组', 'PY_GROUP', 'Python技术学习交流', 'study_group', 2);

-- 插入用户团队关联
INSERT INTO user_teams (user_id, team_id, role) VALUES
(2, 1, 'leader'),
(2, 2, 'leader'),
(3, 1, 'member'),
(3, 3, 'member');

-- 插入轻医美相关课程
INSERT INTO courses (name, description, category, status, duration_hours, difficulty_level, tags, is_featured, sort_order, published_at) VALUES
-- 技术类课程
('皮肤生理学基础', '学习皮肤结构、功能和常见问题，为专业护理打下基础', 'technology', 'published', 16, 2, '["皮肤学", "基础理论", "必修课"]', TRUE, 100, NOW()),
('医美产品知识与应用', '全面了解各类医美产品的成分、功效和适用人群', 'technology', 'published', 20, 3, '["产品知识", "医美", "专业技能"]', TRUE, 110, NOW()),
('美容仪器操作与维护', '掌握各类美容仪器的操作方法、注意事项和日常维护', 'technology', 'published', 24, 3, '["仪器操作", "实操技能", "设备维护"]', FALSE, 120, NOW()),
('医美项目介绍与咨询', '详细了解各类医美项目的原理、效果和适应症', 'technology', 'published', 30, 4, '["医美项目", "专业咨询", "风险告知"]', TRUE, 170, NOW()),

-- 业务类课程
('轻医美销售技巧', '学习专业的销售话术、客户需求分析和成交技巧', 'business', 'published', 16, 2, '["销售技巧", "客户沟通", "业绩提升"]', TRUE, 130, NOW()),
('客户服务与投诉处理', '提升服务意识，掌握客户投诉处理的方法和技巧', 'business', 'published', 12, 2, '["客户服务", "危机处理", "沟通技巧"]', FALSE, 140, NOW()),
('社媒营销与私域运营', '学习如何通过社交媒体进行品牌推广和客户维护', 'business', 'published', 16, 2, '["社媒营销", "私域流量", "客户维护"]', FALSE, 180, NOW()),

-- 管理类课程
('门店运营管理', '学习门店日常管理、团队建设和业绩管理', 'management', 'published', 20, 3, '["门店管理", "团队管理", "运营策略"]', FALSE, 160, NOW()),

-- 通用类课程
('卫生消毒与感染控制', '学习医美机构的卫生标准和消毒流程，确保服务安全', 'general', 'published', 8, 1, '["卫生安全", "消毒规范", "合规管理"]', TRUE, 150, NOW()),

-- 保留原有的技术课程作为选修参考
('Python编程基础', 'Python语言入门课程，适合零基础学员', 'technology', 'published', 40, 2, '["Python", "编程基础", "入门"]', FALSE, 200, NOW()),
('数据分析基础', '学习数据分析方法和工具，提升数据驱动决策能力', 'technology', 'published', 32, 3, '["数据分析", "Excel", "可视化"]', FALSE, 210, NOW());

-- 为第一个课程添加资料
INSERT INTO course_materials (course_id, name, description, file_url, file_type, file_size) VALUES
(1, 'Python基础教程.pdf', 'Python编程基础教程文档', '/uploads/python-basics.pdf', 'pdf', 2048000),
(1, '课程视频1', '第一章节视频教程', '/uploads/video1.mp4', 'mp4', 104857600);

-- 为第一个课程添加知识点
INSERT INTO knowledge_points (course_id, name, description, parent_id, level, weight, estimated_hours) VALUES
(1, 'Python环境搭建', '学习如何安装和配置Python开发环境', NULL, 1, 1.0, 2),
(1, 'Python基础语法', '学习Python的基本语法规则', NULL, 1, 2.0, 8),
(1, '变量和数据类型', '了解Python中的变量和基本数据类型', 2, 2, 1.5, 3),
(1, '控制流程', '学习条件语句和循环结构', 2, 2, 1.5, 4);

-- 插入测试题目
INSERT INTO questions (course_id, question_type, title, content, options, correct_answer, explanation, score, difficulty, tags) VALUES
(1, 'single_choice', 'Python中哪个关键字用于定义函数？', NULL, '{"A": "def", "B": "function", "C": "fun", "D": "define"}', 'A', 'Python使用def关键字来定义函数', 10.0, 'easy', '["python", "基础", "函数"]'),
(1, 'single_choice', 'Python中列表和元组的主要区别是什么？', NULL, '{"A": "列表是有序的，元组是无序的", "B": "列表可变，元组不可变", "C": "列表只能存储数字，元组可以存储任何类型", "D": "没有区别"}', 'B', '列表是可变的（mutable），而元组是不可变的（immutable）', 10.0, 'medium', '["python", "数据结构"]'),
(1, 'true_false', 'Python是一种编译型语言', NULL, NULL, 'false', 'Python是一种解释型语言，不需要编译成机器码', 10.0, 'easy', '["python", "基础"]'),
(1, 'fill_blank', 'Python中使用____关键字定义类', NULL, NULL, 'class', '使用class关键字定义类', 10.0, 'easy', '["python", "面向对象"]');

-- 插入陪练场景
INSERT INTO training_scenes (name, description, category, ai_config, status, is_public) VALUES
('Python编程助手', '帮助学员解决Python编程问题', '技术辅导', '{"bot_id": "python_assistant_bot"}', 'active', TRUE),
('面试模拟', '模拟技术面试场景', '职业发展', '{"bot_id": "interview_simulator_bot"}', 'active', TRUE),
('项目讨论', '项目方案讨论和优化', '项目管理', '{"bot_id": "project_discussion_bot"}', 'draft', TRUE);

-- 插入成长路径
INSERT INTO growth_paths (name, description, target_role, courses, estimated_duration_days) VALUES
('Python工程师成长路径', '从入门到精通的Python学习路径', 'Python开发工程师', '[{"course_id": 1, "order": 1, "is_required": true}, {"course_id": 4, "order": 2, "is_required": true}]', 90),
('技术管理者路径', '技术人员转型管理岗位', '技术经理', '[{"course_id": 2, "order": 1, "is_required": true}, {"course_id": 3, "order": 2, "is_required": false}]', 60);

-- ============================================
-- 六、创建视图（可选）
-- ============================================

-- 用户课程进度视图
CREATE OR REPLACE VIEW v_user_course_progress AS
SELECT 
    u.id as user_id,
    u.username,
    c.id as course_id,
    c.name as course_name,
    COUNT(DISTINCT e.id) as exam_count,
    AVG(e.score) as avg_score,
    MAX(e.score) as best_score
FROM users u
CROSS JOIN courses c
LEFT JOIN exams e ON e.user_id = u.id AND e.course_id = c.id AND e.status = 'submitted'
GROUP BY u.id, c.id;

-- ============================================
-- 七、岗位成员和课程关联表
-- ============================================

-- 创建岗位成员关联表
CREATE TABLE IF NOT EXISTS position_members (
    id INT AUTO_INCREMENT PRIMARY KEY,
    position_id INT NOT NULL COMMENT '岗位ID',
    user_id INT NOT NULL COMMENT '用户ID',
    role VARCHAR(50) COMMENT '成员角色（预留字段）',
    joined_at DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '加入时间',
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    created_by INT COMMENT '创建人ID',
    updated_by INT COMMENT '更新人ID',
    is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
    deleted_at DATETIME,
    FOREIGN KEY (position_id) REFERENCES positions(id),
    FOREIGN KEY (user_id) REFERENCES users(id),
    UNIQUE KEY uix_position_user (position_id, user_id, is_deleted),
    INDEX ix_position_members_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='岗位成员关联表';

-- 创建岗位课程关联表
CREATE TABLE IF NOT EXISTS position_courses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    position_id INT NOT NULL COMMENT '岗位ID',
    course_id INT NOT NULL COMMENT '课程ID',
    course_type VARCHAR(20) NOT NULL DEFAULT 'required' COMMENT '课程类型',
    priority INT DEFAULT 0 COMMENT '优先级/排序',
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    created_by INT COMMENT '创建人ID',
    updated_by INT COMMENT '更新人ID',
    is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
    deleted_at DATETIME,
    FOREIGN KEY (position_id) REFERENCES positions(id),
    FOREIGN KEY (course_id) REFERENCES courses(id),
    UNIQUE KEY uix_position_course (position_id, course_id, is_deleted),
    INDEX ix_position_courses_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='岗位课程关联表';

-- 创建课程考试设置表
CREATE TABLE IF NOT EXISTS course_exam_settings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    course_id INT NOT NULL UNIQUE COMMENT '课程ID',
    single_choice_count INT NOT NULL DEFAULT 10 COMMENT '单选题数量',
    multiple_choice_count INT NOT NULL DEFAULT 5 COMMENT '多选题数量',
    true_false_count INT NOT NULL DEFAULT 5 COMMENT '判断题数量',
    fill_blank_count INT NOT NULL DEFAULT 0 COMMENT '填空题数量',
    duration_minutes INT NOT NULL DEFAULT 60 COMMENT '考试时长(分钟)',
    difficulty_level INT NOT NULL DEFAULT 3 COMMENT '难度系数(1-5)',
    passing_score INT NOT NULL DEFAULT 60 COMMENT '及格分数',
    is_enabled BOOLEAN NOT NULL DEFAULT TRUE COMMENT '是否启用',
    show_answer_immediately BOOLEAN NOT NULL DEFAULT FALSE COMMENT '是否立即显示答案',
    allow_retake BOOLEAN NOT NULL DEFAULT TRUE COMMENT '是否允许重考',
    max_retake_times INT COMMENT '最大重考次数',
    created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    created_by INT COMMENT '创建人ID',
    updated_by INT COMMENT '更新人ID',
    is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
    deleted_at DATETIME,
    deleted_by INT COMMENT '删除人ID',
    FOREIGN KEY (course_id) REFERENCES courses(id),
    INDEX ix_course_exam_settings_id (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='课程考试设置表';

-- 插入岗位成员样例数据（使用已存在的用户）
INSERT INTO position_members (position_id, user_id) VALUES
(2, 2), -- 店长：admin
(3, 3); -- 美容顾问：testuser

-- 插入岗位课程关联数据
-- 需要根据实际插入的课程ID来设置，这里使用子查询获取课程ID

-- 店长必修课程
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 2, id, 'required', 1 FROM courses WHERE name = '门店运营管理' AND is_deleted = FALSE LIMIT 1;
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 2, id, 'required', 2 FROM courses WHERE name = '轻医美销售技巧' AND is_deleted = FALSE LIMIT 1;
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 2, id, 'required', 3 FROM courses WHERE name = '客户服务与投诉处理' AND is_deleted = FALSE LIMIT 1;
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 2, id, 'required', 4 FROM courses WHERE name = '卫生消毒与感染控制' AND is_deleted = FALSE LIMIT 1;

-- 美容顾问必修课程
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 3, id, 'required', 1 FROM courses WHERE name = '皮肤生理学基础' AND is_deleted = FALSE LIMIT 1;
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 3, id, 'required', 2 FROM courses WHERE name = '医美产品知识与应用' AND is_deleted = FALSE LIMIT 1;
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 3, id, 'required', 3 FROM courses WHERE name = '轻医美销售技巧' AND is_deleted = FALSE LIMIT 1;
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 3, id, 'required', 4 FROM courses WHERE name = '客户服务与投诉处理' AND is_deleted = FALSE LIMIT 1;
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 3, id, 'optional', 5 FROM courses WHERE name = '社媒营销与私域运营' AND is_deleted = FALSE LIMIT 1;

-- 美容技师必修课程
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 4, id, 'required', 1 FROM courses WHERE name = '皮肤生理学基础' AND is_deleted = FALSE LIMIT 1;
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 4, id, 'required', 2 FROM courses WHERE name = '美容仪器操作与维护' AND is_deleted = FALSE LIMIT 1;
INSERT INTO position_courses (position_id, course_id, course_type, priority) 
SELECT 4, id, 'required', 3 FROM courses WHERE name = '卫生消毒与感染控制' AND is_deleted = FALSE LIMIT 1;

-- ============================================
-- 八、输出完成信息
-- ============================================

SELECT '数据库初始化完成！' as message;
SELECT '默认账号-超级管理员：superadmin / Superadmin123!' as info1;
SELECT '默认账号-系统管理员：admin / Admin123!' as info2;
SELECT '默认账号-测试学员：testuser / TestPass123!' as info3;
