-- 学生成绩管理系统数据库初始化脚本
-- 创建数据库
CREATE DATABASE IF NOT EXISTS score_management DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE score_management;

-- 用户表（学生、教师、管理员）
CREATE TABLE IF NOT EXISTS users (
    id VARCHAR(20) PRIMARY KEY COMMENT '用户ID（学号/工号）',
    name VARCHAR(50) NOT NULL COMMENT '姓名',
    password VARCHAR(100) NOT NULL COMMENT '密码（bcrypt加密）',
    role ENUM('student', 'teacher', 'admin') NOT NULL COMMENT '角色',
    class VARCHAR(20) DEFAULT NULL COMMENT '班级（学生和教师需要，管理员为NULL）',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX idx_role (role),
    INDEX idx_class (class)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';

-- students 表：学生详细信息（与 users 表 id 关联）
CREATE TABLE IF NOT EXISTS students (
    id VARCHAR(20) PRIMARY KEY COMMENT '学生ID（与users表id一致）',
    name VARCHAR(50) NOT NULL COMMENT '姓名',
    class VARCHAR(20) COMMENT '班级',
    FOREIGN KEY (id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='学生详细信息表';

-- scores 表：成绩记录
CREATE TABLE IF NOT EXISTS scores (
    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '成绩记录ID',
    student_id VARCHAR(20) NOT NULL COMMENT '学生ID',
    course VARCHAR(100) NOT NULL COMMENT '课程名称',
    score DECIMAL(5,2) NOT NULL CHECK (score >= 0 AND score <= 100) COMMENT '成绩',
    teacher_id VARCHAR(20) NOT NULL COMMENT '教师ID',
    class VARCHAR(20) NOT NULL COMMENT '班级',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    FOREIGN KEY (student_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (teacher_id) REFERENCES users(id) ON DELETE CASCADE,
    INDEX idx_student_id (student_id),
    INDEX idx_teacher_id (teacher_id),
    INDEX idx_class (class)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='成绩记录表';

-- 班级表
CREATE TABLE IF NOT EXISTS classes (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '班级ID',
    class_name VARCHAR(50) NOT NULL COMMENT '班级名称',
    grade VARCHAR(20) COMMENT '年级',
    major VARCHAR(100) COMMENT '专业',
    teacher_id INT COMMENT '班主任ID',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX idx_class_name (class_name),
    INDEX idx_teacher_id (teacher_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='班级表';

-- 课程表
CREATE TABLE IF NOT EXISTS courses (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '课程ID',
    course_code VARCHAR(20) UNIQUE NOT NULL COMMENT '课程代码',
    course_name VARCHAR(100) NOT NULL COMMENT '课程名称',
    credit DECIMAL(3,1) NOT NULL DEFAULT 2.0 COMMENT '学分',
    teacher_id INT NOT NULL COMMENT '授课教师ID',
    class_id INT NOT NULL COMMENT '授课班级ID',
    semester VARCHAR(20) COMMENT '学期',
    academic_year VARCHAR(20) COMMENT '学年',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    INDEX idx_course_code (course_code),
    INDEX idx_teacher_id (teacher_id),
    INDEX idx_class_id (class_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='课程表';

-- 成绩表
CREATE TABLE IF NOT EXISTS grades (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '成绩ID',
    student_id INT NOT NULL COMMENT '学生ID',
    course_id INT NOT NULL COMMENT '课程ID',
    usual_score DECIMAL(5,2) COMMENT '平时成绩',
    midterm_score DECIMAL(5,2) COMMENT '期中成绩',
    final_score DECIMAL(5,2) COMMENT '期末成绩',
    total_score DECIMAL(5,2) COMMENT '总评成绩',
    grade_point DECIMAL(3,2) COMMENT '绩点',
    grade_level VARCHAR(10) COMMENT '成绩等级（A/B/C/D/F）',
    teacher_id INT NOT NULL COMMENT '录入教师ID',
    remark TEXT COMMENT '备注',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    UNIQUE KEY uk_student_course (student_id, course_id),
    INDEX idx_student_id (student_id),
    INDEX idx_course_id (course_id),
    INDEX idx_teacher_id (teacher_id),
    INDEX idx_total_score (total_score)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='成绩表';

-- 操作日志表
CREATE TABLE IF NOT EXISTS operation_logs (
    id INT PRIMARY KEY AUTO_INCREMENT COMMENT '日志ID',
    user_id INT NOT NULL COMMENT '操作用户ID',
    operation_type VARCHAR(50) NOT NULL COMMENT '操作类型',
    operation_target VARCHAR(100) COMMENT '操作目标',
    operation_details TEXT COMMENT '操作详情',
    ip_address VARCHAR(45) COMMENT 'IP地址',
    user_agent TEXT COMMENT '用户代理',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
    INDEX idx_user_id (user_id),
    INDEX idx_operation_type (operation_type),
    INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='操作日志表';

-- 插入初始数据
-- 插入管理员用户（密码：admin123）
INSERT INTO users (username, password, name, role, email, phone) VALUES 
('admin', '$2b$10$N9qo8uLOickgx2ZMRZoMy.MrqK.3.6Z1zXjJX.3Q7JzQ7JzQ7JzQ7', '系统管理员', 'admin', 'admin@school.edu', '13800138000');

-- 插入示例班级
INSERT INTO classes (class_name, grade, major) VALUES 
('计算机科学与技术2023级1班', '2023', '计算机科学与技术'),
('软件工程2023级1班', '2023', '软件工程'),
('人工智能2023级1班', '2023', '人工智能');

-- 插入示例教师（密码：teacher123）
INSERT INTO users (username, password, name, role, class_id, email, phone) VALUES 
('t1001', '$2b$10$N9qo8uLOickgx2ZMRZoMy.MrqK.3.6Z1zXjJX.3Q7JzQ7JzQ7JzQ7', '张老师', 'teacher', 1, 'zhang@school.edu', '13800138001'),
('t1002', '$2b$10$N9qo8uLOickgx2ZMRZoMy.MrqK.3.6Z1zXjJX.3Q7JzQ7JzQ7JzQ7', '李老师', 'teacher', 2, 'li@school.edu', '13800138002');

-- 插入示例学生（密码：student123）
INSERT INTO users (username, password, name, role, class_id, email, phone) VALUES 
('s2023001', '$2b$10$N9qo8uLOickgx2ZMRZoMy.MrqK.3.6Z1zXjJX.3Q7JzQ7JzQ7JzQ7', '张三', 'student', 1, 'zhangsan@school.edu', '13800138111'),
('s2023002', '$2b$10$N9qo8uLOickgx2ZMRZoMy.MrqK.3.6Z1zXjJX.3Q7JzQ7JzQ7JzQ7', '李四', 'student', 1, 'lisi@school.edu', '13800138112'),
('s2023003', '$2b$10$N9qo8uLOickgx2ZMRZoMy.MrqK.3.6Z1zXjJX.3Q7JzQ7JzQ7JzQ7', '王五', 'student', 2, 'wangwu@school.edu', '13800138113');

-- 插入示例课程
INSERT INTO courses (course_code, course_name, credit, teacher_id, class_id, semester, academic_year) VALUES 
('CS101', '计算机基础', 3.0, 2, 1, '2023-2024-1', '2023-2024'),
('CS201', '数据结构', 4.0, 2, 1, '2023-2024-1', '2023-2024'),
('SE101', '软件工程导论', 3.0, 3, 2, '2023-2024-1', '2023-2024'),
('AI101', '人工智能基础', 3.5, 3, 3, '2023-2024-1', '2023-2024');

-- 插入示例成绩
INSERT INTO grades (student_id, course_id, usual_score, midterm_score, final_score, total_score, grade_point, grade_level, teacher_id) VALUES 
(3, 1, 85.00, 78.00, 82.00, 81.50, 3.2, 'B', 2),
(3, 2, 90.00, 85.00, 88.00, 87.50, 3.7, 'A', 2),
(4, 1, 78.00, 82.00, 80.00, 80.50, 3.0, 'B', 2),
(5, 3, 88.00, 85.00, 90.00, 88.50, 3.8, 'A', 3);

-- 更新班级表的班主任信息
UPDATE classes SET teacher_id = 2 WHERE id = 1;
UPDATE classes SET teacher_id = 3 WHERE id = 2;

-- 创建视图：学生成绩详情视图
CREATE OR REPLACE VIEW student_grade_details AS
SELECT 
    g.id,
    g.student_id,
    u1.name AS student_name,
    u1.username AS student_no,
    g.course_id,
    c.course_code,
    c.course_name,
    c.credit,
    g.usual_score,
    g.midterm_score,
    g.final_score,
    g.total_score,
    g.grade_point,
    g.grade_level,
    g.teacher_id,
    u2.name AS teacher_name,
    g.remark,
    g.created_at,
    g.updated_at
FROM grades g
JOIN users u1 ON g.student_id = u1.id
JOIN courses c ON g.course_id = c.id
JOIN users u2 ON g.teacher_id = u2.id;

-- 创建视图：班级成绩统计视图
CREATE OR REPLACE VIEW class_grade_statistics AS
SELECT 
    cl.id AS class_id,
    cl.class_name,
    c.id AS course_id,
    c.course_code,
    c.course_name,
    COUNT(g.id) AS student_count,
    AVG(g.total_score) AS avg_score,
    MAX(g.total_score) AS max_score,
    MIN(g.total_score) AS min_score,
    SUM(CASE WHEN g.grade_level = 'A' THEN 1 ELSE 0 END) AS a_count,
    SUM(CASE WHEN g.grade_level = 'B' THEN 1 ELSE 0 END) AS b_count,
    SUM(CASE WHEN g.grade_level = 'C' THEN 1 ELSE 0 END) AS c_count,
    SUM(CASE WHEN g.grade_level = 'D' THEN 1 ELSE 0 END) AS d_count,
    SUM(CASE WHEN g.grade_level = 'F' THEN 1 ELSE 0 END) AS f_count
FROM classes cl
JOIN courses c ON cl.id = c.class_id
LEFT JOIN grades g ON c.id = g.course_id
GROUP BY cl.id, c.id;

-- 显示表结构信息
SHOW TABLES;

-- 显示各表记录数
SELECT 'users' AS table_name, COUNT(*) AS record_count FROM users
UNION ALL
SELECT 'classes', COUNT(*) FROM classes
UNION ALL
SELECT 'courses', COUNT(*) FROM courses
UNION ALL
SELECT 'grades', COUNT(*) FROM grades
UNION ALL
SELECT 'operation_logs', COUNT(*) FROM operation_logs;

-- 显示视图
SHOW FULL TABLES WHERE TABLE_TYPE = 'VIEW';