package com.reading.platform;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reading.platform.entity.*;
import com.reading.platform.mapper.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 测试数据生成器
 * 用于生成一批测试数据并插入到数据库
 */
@SpringBootTest
@ActiveProfiles("dev")
public class TestDataGenerator {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ParentMapper parentMapper;

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private ClassTeacherMapper classTeacherMapper;

    @Autowired
    private ParentStudentMapper parentStudentMapper;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private CourseLessonMapper courseLessonMapper;

    @Autowired
    private LessonMapper lessonMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TaskTemplateMapper taskTemplateMapper;

    @Autowired
    private NotificationMapper notificationMapper;

    @Autowired
    private ThemeMapper themeMapper;

    @Autowired
    private SchedulePlanMapper schedulePlanMapper;

    @Autowired
    private GrowthRecordMapper growthRecordMapper;

    private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    /**
     * 清理测试数据（按顺序删除，避免外键约束问题）
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    private void cleanupTestData() {
        System.out.println("【清理】开始清理旧的测试数据...");

        // 测试租户的 code
        String testTenantCode1 = "sunshine_kinder";
        String testTenantCode2 = "hope_kinder";

        // 测试教师的 username
        String[] testTeacherUsernames = {"teacher_wang", "teacher_li", "teacher_zhang"};

        // 测试家长的 username
        String[] testParentUsernames = {"parent_zhang", "parent_liu"};

        System.out.println("  开始清理教师数据...");
        // 物理删除测试教师
        for (String username : testTeacherUsernames) {
            teacherMapper.deletePhysicalByUsername(username);
        }
        System.out.println("  ✓ 物理删除测试教师");

        System.out.println("  开始删除学校账号...");
        // 物理删除教师表中的学校账号（这些账号的用户名 = 租户 code）
        teacherMapper.deletePhysicalByUsername(testTenantCode1);
        teacherMapper.deletePhysicalByUsername(testTenantCode2);
        System.out.println("  ✓ 物理删除学校账号");

        System.out.println("  开始清理家长数据...");
        // 物理删除测试家长
        for (String username : testParentUsernames) {
            parentMapper.deletePhysicalByUsername(username);
        }
        System.out.println("  ✓ 物理删除测试家长");

        System.out.println("  开始清理学生数据...");
        // 物理删除测试学生（按学号）
        studentMapper.deletePhysicalByStudentNo("S2024001");
        studentMapper.deletePhysicalByStudentNo("S2024002");
        studentMapper.deletePhysicalByStudentNo("S2024003");
        System.out.println("  ✓ 物理删除测试学生");

        System.out.println("  开始物理删除租户...");
        // 使用物理删除清理租户
        int deleted1 = tenantMapper.deletePhysicalByCode(testTenantCode1);
        System.out.println("  ✓ 物理删除租户：" + testTenantCode1 + " (" + deleted1 + " 条)");

        int deleted2 = tenantMapper.deletePhysicalByCode(testTenantCode2);
        System.out.println("  ✓ 物理删除租户：" + testTenantCode2 + " (" + deleted2 + " 条)");

        // 清理主题数据（使用物理删除）
        System.out.println("  开始清理主题数据...");
        themeMapper.deletePhysical();
        System.out.println("  ✓ 删除所有主题数据");

        System.out.println("【清理】清理完成");
    }

    /**
     * 清理指定租户的所有数据
     */
    private void cleanupTenantData(Long tenantId) {
        // 按依赖顺序删除
        growthRecordMapper.delete(new LambdaQueryWrapper<GrowthRecord>().eq(GrowthRecord::getTenantId, tenantId));
        schedulePlanMapper.delete(new LambdaQueryWrapper<SchedulePlan>().eq(SchedulePlan::getTenantId, tenantId));
        notificationMapper.delete(new LambdaQueryWrapper<Notification>().eq(Notification::getTenantId, tenantId));
        taskTemplateMapper.delete(new LambdaQueryWrapper<TaskTemplate>().eq(TaskTemplate::getTenantId, tenantId));
        taskMapper.delete(new LambdaQueryWrapper<Task>().eq(Task::getTenantId, tenantId));
        lessonMapper.delete(new LambdaQueryWrapper<Lesson>().eq(Lesson::getTenantId, tenantId));
        courseMapper.delete(new LambdaQueryWrapper<Course>().eq(Course::getTenantId, tenantId));

        // 删除家长学生关联
        ParentStudentMapper psMapper = parentStudentMapper;
        // 先获取该租户的家长和学生
        var parents = parentMapper.selectList(new LambdaQueryWrapper<Parent>().eq(Parent::getTenantId, tenantId));
        for (Parent parent : parents) {
            psMapper.delete(new LambdaQueryWrapper<ParentStudent>().eq(ParentStudent::getParentId, parent.getId()));
        }

        // 删除学生
        studentMapper.delete(new LambdaQueryWrapper<Student>().eq(Student::getTenantId, tenantId));

        // 删除家长
        parentMapper.delete(new LambdaQueryWrapper<Parent>().eq(Parent::getTenantId, tenantId));

        // 删除班级教师关联
        var classes = clazzMapper.selectList(new LambdaQueryWrapper<Clazz>().eq(Clazz::getTenantId, tenantId));
        for (Clazz clazz : classes) {
            classTeacherMapper.delete(new LambdaQueryWrapper<ClassTeacher>().eq(ClassTeacher::getClassId, clazz.getId()));
        }

        // 删除班级
        clazzMapper.delete(new LambdaQueryWrapper<Clazz>().eq(Clazz::getTenantId, tenantId));

        // 删除教师（包括学校账号）
        teacherMapper.delete(new LambdaQueryWrapper<Teacher>().eq(Teacher::getTenantId, tenantId));
    }

    /**
     * 生成完整的测试数据
     * 包括：租户、教师、学生、家长、班级、课程、课时、任务、通知等
     */
    @Test
    public void generateAllTestData() {
        System.out.println("========== 开始生成测试数据 ==========");

        // 先清理测试租户的旧数据（如果存在）
        cleanupTestData();

        // 1. 创建租户（幼儿园）
        Long tenantId = createTenants();

        // 2. 创建主题
        createThemes();

        // 3. 创建教师
        Long teacherId1 = createTeachers(tenantId);
        Long teacherId2 = createTeachers2(tenantId);

        // 4. 创建学生
        Long studentId1 = createStudents(tenantId);
        Long studentId2 = createStudents2(tenantId);
        Long studentId3 = createStudents3(tenantId);

        // 5. 创建家长
        Long parentId1 = createParents(tenantId);
        Long parentId2 = createParents2(tenantId);

        // 6. 创建班级
        Long classId1 = createClasses(tenantId);
        Long classId2 = createClasses2(tenantId);

        // 7. 关联班级和教师
        createClassTeacher(classId1, teacherId1);
        createClassTeacher2(classId2, teacherId2);

        // 8. 关联家长和学生
        createParentStudents(parentId1, studentId1);
        createParentStudents2(parentId2, studentId2, studentId3);

        // 9. 创建课程
        Long courseId1 = createCourses(tenantId);
        Long courseId2 = createCourses2(tenantId);

        // 10. 创建课程课时
        createCourseLessons(courseId1);
        createCourseLessons2(courseId2);

        // 11. 创建课时（教学活动）
        createLessons(tenantId, courseId1, classId1, teacherId1);

        // 12. 创建任务
        createTasks(tenantId, courseId1, teacherId1);

        // 13. 创建任务模板
        createTaskTemplates(tenantId);

        // 14. 创建通知
        createNotifications(tenantId, teacherId1, parentId1);

        // 15. 创建课表计划
        createSchedulePlans(tenantId, classId1, courseId1, teacherId1);

        // 16. 创建成长记录
        createGrowthRecords(tenantId, studentId1);

        System.out.println("========== 测试数据生成完成 ==========");
    }

    /**
     * 创建租户（幼儿园）
     */
    private Long createTenants() {
        System.out.println("【1】创建租户...");

        Tenant tenant = new Tenant();
        tenant.setName("阳光幼儿园");
        tenant.setCode("sunshine_kinder");
        tenant.setContactName("张园长");
        tenant.setContactPhone("13800138001");
        tenant.setContactEmail("sunshine@kinder.com");
        tenant.setAddress("北京市朝阳区阳光路 100 号");
        tenant.setLogoUrl("/uploads/logos/sunshine.png");
        tenant.setStatus("active");
        tenant.setExpireAt(LocalDateTime.now().plusYears(1));
        tenant.setMaxStudents(500);
        tenant.setMaxTeachers(50);

        tenantMapper.insert(tenant);
        System.out.println("  ✓ 创建租户：阳光幼儿园 (ID=" + tenant.getId() + ")");

        // 创建第二个租户
        Tenant tenant2 = new Tenant();
        tenant2.setName("希望幼儿园");
        tenant2.setCode("hope_kinder");
        tenant2.setContactName("李园长");
        tenant2.setContactPhone("13800138002");
        tenant2.setContactEmail("hope@kinder.com");
        tenant2.setAddress("北京市海淀区希望路 200 号");
        tenant2.setLogoUrl("/uploads/logos/hope.png");
        tenant2.setStatus("active");
        tenant2.setExpireAt(LocalDateTime.now().plusYears(1));
        tenant2.setMaxStudents(300);
        tenant2.setMaxTeachers(30);

        tenantMapper.insert(tenant2);
        System.out.println("  ✓ 创建租户：希望幼儿园 (ID=" + tenant2.getId() + ")");

        // 创建学校登录账号（教师表中）
        Teacher schoolAccount = new Teacher();
        schoolAccount.setTenantId(tenant.getId());
        schoolAccount.setUsername(tenant.getCode());
        schoolAccount.setPassword(passwordEncoder.encode("123456"));
        schoolAccount.setName("阳光幼儿园 - 学校账号");
        schoolAccount.setStatus("active");
        teacherMapper.insert(schoolAccount);
        System.out.println("  ✓ 创建学校登录账号 (username=" + tenant.getCode() + ", password=123456)");

        return tenant.getId();
    }

    /**
     * 创建主题
     */
    private void createThemes() {
        System.out.println("【2】创建主题...");

        String[][] themes = {
                {"language", "语言与文字", "#FF6B6B"},
                {"math", "数学与逻辑", "#4ECDC4"},
                {"science", "科学探索", "#45B7D1"},
                {"art", "艺术与创造", "#FFA07A"},
                {"social", "社会情感", "#98D8C8"},
                {"health", "健康运动", "#F7DC6F"},
                {"nature", "自然认知", "#82E0AA"}
        };

        int sortOrder = 1;
        for (String[] theme : themes) {
            Theme entity = new Theme();
            entity.setName(theme[0]);
            entity.setDisplayName(theme[1]);
            entity.setColor(theme[2]);
            entity.setIcon("icon-" + theme[0]);
            entity.setSortOrder(sortOrder++);
            entity.setIsEnabled(1);

            themeMapper.insert(entity);
            System.out.println("  ✓ 创建主题：" + theme[1] + " (" + theme[0] + ")");
        }
    }

    /**
     * 创建教师
     */
    private Long createTeachers(Long tenantId) {
        System.out.println("【3】创建教师...");

        Teacher teacher = new Teacher();
        teacher.setTenantId(tenantId);
        teacher.setUsername("teacher_wang");
        teacher.setPassword(passwordEncoder.encode("123456"));
        teacher.setName("王老师");
        teacher.setPhone("13900139001");
        teacher.setEmail("wang@kinder.com");
        teacher.setGender("female");
        teacher.setBio("资深幼儿教师，擅长语言教学");
        teacher.setStatus("active");

        teacherMapper.insert(teacher);
        System.out.println("  ✓ 创建教师：王老师 (ID=" + teacher.getId() + ", username=teacher_wang)");

        return teacher.getId();
    }

    private Long createTeachers2(Long tenantId) {
        Teacher teacher = new Teacher();
        teacher.setTenantId(tenantId);
        teacher.setUsername("teacher_li");
        teacher.setPassword(passwordEncoder.encode("123456"));
        teacher.setName("李老师");
        teacher.setPhone("13900139002");
        teacher.setEmail("li@kinder.com");
        teacher.setGender("male");
        teacher.setBio("体育教师，擅长运动游戏");
        teacher.setStatus("active");

        teacherMapper.insert(teacher);
        System.out.println("  ✓ 创建教师：李老师 (ID=" + teacher.getId() + ", username=teacher_li)");

        return teacher.getId();
    }

    /**
     * 创建学生
     */
    private Long createStudents(Long tenantId) {
        System.out.println("【4】创建学生...");

        Student student = new Student();
        student.setTenantId(tenantId);
        student.setName("小明");
        student.setGender("male");
        student.setBirthDate(LocalDate.of(2019, 5, 15));
        student.setAvatarUrl("/uploads/avatars/student1.png");
        student.setGrade("大班");
        student.setStudentNo("S2024001");
        student.setReadingLevel("中级");
        student.setInterests("阅读、画画、积木");
        student.setNotes("活泼好动，喜欢提问");
        student.setStatus("active");

        studentMapper.insert(student);
        System.out.println("  ✓ 创建学生：小明 (ID=" + student.getId() + ")");

        return student.getId();
    }

    private Long createStudents2(Long tenantId) {
        Student student = new Student();
        student.setTenantId(tenantId);
        student.setName("小红");
        student.setGender("female");
        student.setBirthDate(LocalDate.of(2019, 8, 20));
        student.setAvatarUrl("/uploads/avatars/student2.png");
        student.setGrade("大班");
        student.setStudentNo("S2024002");
        student.setReadingLevel("高级");
        student.setInterests("阅读、唱歌、跳舞");
        student.setNotes("文静乖巧，记忆力好");
        student.setStatus("active");

        studentMapper.insert(student);
        System.out.println("  ✓ 创建学生：小红 (ID=" + student.getId() + ")");

        return student.getId();
    }

    private Long createStudents3(Long tenantId) {
        Student student = new Student();
        student.setTenantId(tenantId);
        student.setName("小强");
        student.setGender("male");
        student.setBirthDate(LocalDate.of(2020, 2, 10));
        student.setAvatarUrl("/uploads/avatars/student3.png");
        student.setGrade("中班");
        student.setStudentNo("S2024003");
        student.setReadingLevel("初级");
        student.setInterests("运动、游戏");
        student.setNotes("性格开朗，喜欢集体活动");
        student.setStatus("active");

        studentMapper.insert(student);
        System.out.println("  ✓ 创建学生：小强 (ID=" + student.getId() + ")");

        return student.getId();
    }

    /**
     * 创建家长
     */
    private Long createParents(Long tenantId) {
        System.out.println("【5】创建家长...");

        Parent parent = new Parent();
        parent.setTenantId(tenantId);
        parent.setUsername("parent_zhang");
        parent.setPassword(passwordEncoder.encode("123456"));
        parent.setName("张先生");
        parent.setPhone("13700137001");
        parent.setEmail("zhang@qq.com");
        parent.setGender("male");
        parent.setStatus("active");

        parentMapper.insert(parent);
        System.out.println("  ✓ 创建家长：张先生 (ID=" + parent.getId() + ", username=parent_zhang)");

        return parent.getId();
    }

    private Long createParents2(Long tenantId) {
        Parent parent = new Parent();
        parent.setTenantId(tenantId);
        parent.setUsername("parent_liu");
        parent.setPassword(passwordEncoder.encode("123456"));
        parent.setName("刘女士");
        parent.setPhone("13700137002");
        parent.setEmail("liu@qq.com");
        parent.setGender("female");
        parent.setStatus("active");

        parentMapper.insert(parent);
        System.out.println("  ✓ 创建家长：刘女士 (ID=" + parent.getId() + ", username=parent_liu)");

        return parent.getId();
    }

    /**
     * 创建班级
     */
    private Long createClasses(Long tenantId) {
        System.out.println("【6】创建班级...");

        Clazz clazz = new Clazz();
        clazz.setTenantId(tenantId);
        clazz.setName("大（一）班");
        clazz.setGrade("大班");
        clazz.setDescription("2019 年出生的小朋友");
        clazz.setCapacity(35);
        clazz.setStatus("active");

        clazzMapper.insert(clazz);
        System.out.println("  ✓ 创建班级：大（一）班 (ID=" + clazz.getId() + ")");

        return clazz.getId();
    }

    private Long createClasses2(Long tenantId) {
        Clazz clazz = new Clazz();
        clazz.setTenantId(tenantId);
        clazz.setName("中（一）班");
        clazz.setGrade("中班");
        clazz.setDescription("2020 年出生的小朋友");
        clazz.setCapacity(30);
        clazz.setStatus("active");

        clazzMapper.insert(clazz);
        System.out.println("  ✓ 创建班级：中（一）班 (ID=" + clazz.getId() + ")");

        return clazz.getId();
    }

    /**
     * 创建班级 - 教师关联
     */
    private void createClassTeacher(Long classId, Long teacherId) {
        System.out.println("【7】创建班级 - 教师关联...");

        ClassTeacher ct = new ClassTeacher();
        ct.setClassId(classId);
        ct.setTeacherId(teacherId);
        ct.setRole("head_teacher");

        classTeacherMapper.insert(ct);
        System.out.println("  ✓ 关联班级 - 教师：大（一）班 - 王老师（班主任）");
    }

    private void createClassTeacher2(Long classId, Long teacherId) {
        ClassTeacher ct = new ClassTeacher();
        ct.setClassId(classId);
        ct.setTeacherId(teacherId);
        ct.setRole("head_teacher");

        classTeacherMapper.insert(ct);
        System.out.println("  ✓ 关联班级 - 教师：中（一）班 - 李老师（班主任）");
    }

    /**
     * 创建家长 - 学生关联
     */
    private void createParentStudents(Long parentId, Long studentId) {
        System.out.println("【8】创建家长 - 学生关联...");

        ParentStudent ps = new ParentStudent();
        ps.setParentId(parentId);
        ps.setStudentId(studentId);
        ps.setRelationship("father");
        ps.setIsPrimary(1);

        parentStudentMapper.insert(ps);
        System.out.println("  ✓ 关联家长 - 学生：张先生 - 小明（父子）");
    }

    private void createParentStudents2(Long parentId, Long studentId1, Long studentId2) {
        ParentStudent ps1 = new ParentStudent();
        ps1.setParentId(parentId);
        ps1.setStudentId(studentId1);
        ps1.setRelationship("mother");
        ps1.setIsPrimary(1);

        parentStudentMapper.insert(ps1);

        ParentStudent ps2 = new ParentStudent();
        ps2.setParentId(parentId);
        ps2.setStudentId(studentId2);
        ps2.setRelationship("mother");
        ps2.setIsPrimary(1);

        parentStudentMapper.insert(ps2);
        System.out.println("  ✓ 关联家长 - 学生：刘女士 - 小红、小强（母子）");
    }

    /**
     * 创建课程
     */
    private Long createCourses(Long tenantId) {
        System.out.println("【9】创建课程...");

        Course course = new Course();
        course.setTenantId(tenantId);
        course.setName("绘本阅读入门");
        course.setCode("READ001");
        course.setDescription("适合大班幼儿的绘本阅读课程，培养孩子的阅读兴趣和基础阅读能力");
        course.setCoverUrl("/uploads/courses/reading101.png");
        course.setCategory("language");
        course.setAgeRange("5-6 岁");
        course.setDifficultyLevel("beginner");
        course.setDurationMinutes(30);
        course.setObjectives("培养阅读兴趣、提升语言表达能力、增强想象力");
        course.setStatus("published");
        course.setIsSystem(0);
        course.setThemeId(1L);
        course.setPictureBookName("《猜猜我有多爱你》");
        course.setVersion("1.0");
        course.setIsLatest(1);

        courseMapper.insert(course);
        System.out.println("  ✓ 创建课程：绘本阅读入门 (ID=" + course.getId() + ")");

        return course.getId();
    }

    private Long createCourses2(Long tenantId) {
        Course course = new Course();
        course.setTenantId(tenantId);
        course.setName("趣味数学游戏");
        course.setCode("MATH001");
        course.setDescription("通过游戏的方式学习基础数学概念");
        course.setCoverUrl("/uploads/courses/math101.png");
        course.setCategory("math");
        course.setAgeRange("4-5 岁");
        course.setDifficultyLevel("beginner");
        course.setDurationMinutes(25);
        course.setObjectives("认识数字、学习简单加减法、培养逻辑思维");
        course.setStatus("published");
        course.setIsSystem(0);
        course.setThemeId(2L);
        course.setVersion("1.0");
        course.setIsLatest(1);

        courseMapper.insert(course);
        System.out.println("  ✓ 创建课程：趣味数学游戏 (ID=" + course.getId() + ")");

        return course.getId();
    }

    /**
     * 创建课程课时
     */
    private void createCourseLessons(Long courseId) {
        System.out.println("【10】创建课程课时...");

        String[][] lessons = {
                {"第一讲：认识绘本", "了解绘本的结构和特点"},
                {"第二讲：封面故事", "从封面猜测故事内容"},
                {"第三讲：角色认知", "认识故事中的主要角色"},
                {"第四讲：情节理解", "理解故事的发展脉络"},
                {"第五讲：情感体验", "感受故事中的情感表达"},
                {"第六讲：创意延伸", "发挥想象，创编故事结局"}
        };

        for (int i = 0; i < lessons.length; i++) {
            CourseLesson lesson = new CourseLesson();
            lesson.setCourseId(courseId);
            lesson.setTitle(lessons[i][0]);
            lesson.setDescription(lessons[i][1]);
            lesson.setContent("这里是课时内容详情...");
            lesson.setSortOrder(i + 1);
            lesson.setDurationMinutes(15);
            lesson.setStatus("published");

            courseLessonMapper.insert(lesson);
        }
        System.out.println("  ✓ 创建课程课时：" + lessons.length + " 个课时");
    }

    private void createCourseLessons2(Long courseId) {
        String[][] lessons = {
                {"第一讲：数字歌", "学习数字 1-10"},
                {"第二讲：比大小", "认识大小概念"},
                {"第三讲：数一数", "练习点数"},
                {"第四讲：简单加法", "学习 5 以内加法"},
                {"第五讲：简单减法", "学习 5 以内减法"}
        };

        for (int i = 0; i < lessons.length; i++) {
            CourseLesson lesson = new CourseLesson();
            lesson.setCourseId(courseId);
            lesson.setTitle(lessons[i][0]);
            lesson.setDescription(lessons[i][1]);
            lesson.setContent("这里是课时内容详情...");
            lesson.setSortOrder(i + 1);
            lesson.setDurationMinutes(12);
            lesson.setStatus("published");

            courseLessonMapper.insert(lesson);
        }
        System.out.println("  ✓ 创建课程课时：" + lessons.length + " 个课时");
    }

    /**
     * 创建课时（教学活动）
     */
    private void createLessons(Long tenantId, Long courseId, Long classId, Long teacherId) {
        System.out.println("【11】创建课时（教学活动）...");

        LocalDate baseDate = LocalDate.now();

        for (int i = 0; i < 4; i++) {
            Lesson lesson = new Lesson();
            lesson.setTenantId(String.valueOf(tenantId));
            lesson.setCourseId(String.valueOf(courseId));
            lesson.setClassId(String.valueOf(classId));
            lesson.setTeacherId(String.valueOf(teacherId));
            lesson.setTitle("绘本阅读 - 第" + (i + 1) + "课");
            lesson.setLessonDate(baseDate.plusWeeks(i));
            lesson.setStartTime(LocalTime.of(9, 0));
            lesson.setEndTime(LocalTime.of(9, 30));
            lesson.setLocation("大一班教室");
            lesson.setStatus("scheduled");
            lesson.setNotes("请小朋友们提前准备好绘本");

            lessonMapper.insert(lesson);
        }
        System.out.println("  ✓ 创建课时：4 个教学活动");
    }

    /**
     * 创建任务
     */
    private void createTasks(Long tenantId, Long courseId, Long teacherId) {
        System.out.println("【12】创建任务...");

        LocalDate baseDate = LocalDate.now();

        // 任务 1
        Task task1 = new Task();
        task1.setTenantId(String.valueOf(tenantId));
        task1.setTitle("阅读打卡第 1 周");
        task1.setDescription("请家长陪同孩子每天阅读 15 分钟，并记录阅读内容");
        task1.setType("reading");
        task1.setCourseId(String.valueOf(courseId));
        task1.setCreatorId(String.valueOf(teacherId));
        task1.setCreatorRole("teacher");
        task1.setStartDate(baseDate);
        task1.setDueDate(baseDate.plusDays(7));
        task1.setStatus("published");

        taskMapper.insert(task1);

        // 任务 2
        Task task2 = new Task();
        task2.setTenantId(String.valueOf(tenantId));
        task2.setTitle("绘画作业：我喜欢的故事角色");
        task2.setDescription("画出你最喜欢的故事角色，并说明理由");
        task2.setType("homework");
        task2.setCourseId(String.valueOf(courseId));
        task2.setCreatorId(String.valueOf(teacherId));
        task2.setCreatorRole("teacher");
        task2.setStartDate(baseDate);
        task2.setDueDate(baseDate.plusDays(5));
        task2.setStatus("published");

        taskMapper.insert(task2);

        // 任务 3
        Task task3 = new Task();
        task3.setTenantId(String.valueOf(tenantId));
        task3.setTitle("周末亲子活动");
        task3.setDescription("周末和孩子一起去图书馆或书店");
        task3.setType("activity");
        task3.setCourseId(String.valueOf(courseId));
        task3.setCreatorId(String.valueOf(teacherId));
        task3.setCreatorRole("teacher");
        task3.setStartDate(baseDate.plusDays(5));
        task3.setDueDate(baseDate.plusDays(7));
        task3.setStatus("published");

        taskMapper.insert(task3);

        System.out.println("  ✓ 创建任务：3 个任务");
    }

    /**
     * 创建任务模板
     */
    private void createTaskTemplates(Long tenantId) {
        System.out.println("【13】创建任务模板...");

        String[][] templates = {
                {"阅读打卡模板", "用于日常阅读打卡记录", "reading", "请记录今天的阅读内容..."},
                {"绘画作业模板", "用于美术类作业", "homework", "请上传孩子的绘画作品..."},
                {"亲子活动模板", "用于记录亲子活动", "activity", "请分享活动过程和感受..."},
                {"观察记录模板", "用于观察类作业", "homework", "请记录观察到的现象..."}
        };

        for (int i = 0; i < templates.length; i++) {
            String[] template = templates[i];
            TaskTemplate tt = new TaskTemplate();
            tt.setTenantId(String.valueOf(tenantId));
            tt.setName(template[0]);
            tt.setDescription(template[1]);
            tt.setType(template[2]);
            tt.setContent(template[3]);
            tt.setIsPublic(1);

            taskTemplateMapper.insert(tt);
        }
        System.out.println("  ✓ 创建任务模板：" + templates.length + " 个模板");
    }

    /**
     * 创建通知
     */
    private void createNotifications(Long tenantId, Long teacherId, Long parentId) {
        System.out.println("【14】创建通知...");

        // 通知 1 - 系统通知
        Notification n1 = new Notification();
        n1.setTenantId(String.valueOf(tenantId));
        n1.setTitle("新学期开始通知");
        n1.setContent("亲爱的家长们，新学期即将开始，请做好入园准备。");
        n1.setType("system");
        n1.setRecipientType("all");
        n1.setIsRead(0);

        notificationMapper.insert(n1);

        // 通知 2 - 课程通知
        Notification n2 = new Notification();
        n2.setTenantId(String.valueOf(tenantId));
        n2.setTitle("绘本阅读课程更新");
        n2.setContent("《猜猜我有多爱你》课程已更新，请查看。");
        n2.setType("course");
        n2.setSenderId(String.valueOf(teacherId));
        n2.setSenderRole("teacher");
        n2.setRecipientType("all");
        n2.setIsRead(0);

        notificationMapper.insert(n2);

        // 通知 3 - 任务通知
        Notification n3 = new Notification();
        n3.setTenantId(String.valueOf(tenantId));
        n3.setTitle("新任务发布");
        n3.setContent("本周的阅读打卡任务已发布，请家长陪同完成。");
        n3.setType("task");
        n3.setSenderId(String.valueOf(teacherId));
        n3.setSenderRole("teacher");
        n3.setRecipientId(String.valueOf(parentId));
        n3.setRecipientType("parent");
        n3.setIsRead(0);

        notificationMapper.insert(n3);

        System.out.println("  ✓ 创建通知：3 条通知");
    }

    /**
     * 创建课表计划
     */
    private void createSchedulePlans(Long tenantId, Long classId, Long courseId, Long teacherId) {
        System.out.println("【15】创建课表计划...");

        int[][] schedules = {
                {1, 1}, // 周一第 1 节
                {1, 3}, // 周一第 3 节
                {3, 2}, // 周三第 2 节
                {5, 1}  // 周五第 1 节
        };

        for (int[] schedule : schedules) {
            SchedulePlan plan = new SchedulePlan();
            plan.setTenantId(String.valueOf(tenantId));
            plan.setName("绘本阅读课");
            plan.setClassId(String.valueOf(classId));
            plan.setCourseId(String.valueOf(courseId));
            plan.setTeacherId(String.valueOf(teacherId));
            plan.setDayOfWeek(schedule[0]);
            plan.setPeriod(schedule[1]);
            plan.setStartTime(LocalTime.of(9, 0));
            plan.setEndTime(LocalTime.of(9, 30));
            plan.setStartDate(LocalDate.now());
            plan.setEndDate(LocalDate.now().plusMonths(4));
            plan.setLocation("大一班教室");
            plan.setStatus("active");

            schedulePlanMapper.insert(plan);
        }
        System.out.println("  ✓ 创建课表计划：" + schedules.length + " 个课程安排");
    }

    /**
     * 创建成长记录
     */
    private void createGrowthRecords(Long tenantId, Long studentId) {
        System.out.println("【16】创建成长记录...");

        String[][] records = {
                {"reading", "第一次独立阅读", "今天小明第一次独立读完了一本绘本，非常棒！", "阅读进步"},
                {"behavior", "帮助同学", "小明主动帮助摔倒的同学，很有爱心", "品德表现"},
                {"achievement", "绘画比赛获奖", "在幼儿园绘画比赛中获得一等奖", "荣誉奖项"}
        };

        for (String[] record : records) {
            GrowthRecord gr = new GrowthRecord();
            gr.setTenantId(String.valueOf(tenantId));
            gr.setStudentId(String.valueOf(studentId));
            gr.setType(record[0]);
            gr.setTitle(record[1]);
            gr.setContent(record[2]);
            gr.setRecordedBy("1");  // 设置记录人 ID
            gr.setRecorderRole("teacher");  // 设置记录人角色
            gr.setRecordDate(LocalDate.now());
            gr.setTags("[\"" + record[3] + "\"]");

            growthRecordMapper.insert(gr);
        }
        System.out.println("  ✓ 创建成长记录：" + records.length + " 条记录");
    }
}
