-- ========================================
-- 创建辅助视图，便于查询和统计
-- ========================================

USE study;

-- 视图1：学生当前班级视图（只显示有效分配）
DROP VIEW IF EXISTS v_student_current_class;
CREATE VIEW v_student_current_class AS
SELECT 
    u.user_id,
    u.nick_name AS student_name,
    u.prison_area,
    c.id AS class_id,
    c.class_name,
    sc.join_time,
    sc.status
FROM sys_user u
INNER JOIN student_class sc ON u.user_id = sc.student_id
INNER JOIN class c ON sc.class_id = c.id
WHERE u.del_flag = '0' 
  AND u.register_type = 'student'
  AND sc.status = 1;

-- 视图2：班级统计视图（各班级学生数）
DROP VIEW IF EXISTS v_class_statistics;
CREATE VIEW v_class_statistics AS
SELECT 
    c.id AS class_id,
    c.class_name,
    c.prison_area AS class_prison_area,
    COUNT(DISTINCT sc.student_id) AS total_students,
    COUNT(DISTINCT CASE WHEN sc.status = 1 THEN sc.student_id END) AS active_students,
    COUNT(DISTINCT CASE WHEN sc.status = 0 THEN sc.student_id END) AS inactive_students,
    MIN(sc.join_time) AS first_join_time,
    MAX(sc.join_time) AS last_join_time
FROM class c
LEFT JOIN student_class sc ON c.id = sc.class_id
LEFT JOIN sys_user u ON sc.student_id = u.user_id AND u.del_flag = '0'
GROUP BY c.id, c.class_name, c.prison_area;

-- 视图3：监区统计视图
DROP VIEW IF EXISTS v_prison_area_statistics;
CREATE VIEW v_prison_area_statistics AS
SELECT 
    u.prison_area,
    COUNT(DISTINCT u.user_id) AS total_students,
    COUNT(DISTINCT CASE WHEN sc.student_id IS NOT NULL THEN u.user_id END) AS assigned_students,
    COUNT(DISTINCT CASE WHEN sc.student_id IS NULL THEN u.user_id END) AS unassigned_students,
    COUNT(DISTINCT sc.class_id) AS total_classes
FROM sys_user u
LEFT JOIN student_class sc ON u.user_id = sc.student_id AND sc.status = 1
WHERE u.del_flag = '0' 
  AND u.register_type = 'student'
GROUP BY u.prison_area;

-- 视图4：课程分配详情视图（包含课程信息）
DROP VIEW IF EXISTS v_course_assignment_detail;
CREATE VIEW v_course_assignment_detail AS
SELECT 
    ca.id AS assignment_id,
    co.course_name,
    c.class_name,
    u.prison_area,
    ca.student_count,
    ca.start_time,
    ca.end_time,
    CASE 
        WHEN ca.end_time < NOW() THEN '已结束'
        WHEN ca.start_time > NOW() THEN '未开始'
        ELSE '进行中'
    END AS status_desc
FROM course_assignment ca
INNER JOIN course co ON ca.course_id = co.id
LEFT JOIN class c ON ca.class_id = c.id
LEFT JOIN (
    SELECT DISTINCT prison_area, class_id 
    FROM student_class sc 
    INNER JOIN sys_user u ON sc.student_id = u.user_id 
    WHERE sc.status = 1
) u ON ca.class_id = u.class_id;

SELECT '✅ 视图创建成功！' AS result;
SELECT '' AS blank_line;
SELECT '可用视图：' AS info;
SELECT '1. v_student_current_class - 学生当前班级' AS view_list;
SELECT '2. v_class_statistics - 班级统计' AS view_list;
SELECT '3. v_prison_area_statistics - 监区统计' AS view_list;
SELECT '4. v_course_assignment_detail - 课程分配详情' AS view_list;
