<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dora.mapper.CourseChapterMapper">

    <resultMap id="CourseChapterResultMap" type="com.dora.entity.CourseChapter">
        <id column="id" property="id"/>
        <result column="course_id" property="courseId"/>
        <result column="title" property="title"/>
        <result column="description" property="description"/>
        <result column="order_num" property="orderNum"/>
        <result column="create_time" property="createTime"/>
        <result column="update_time" property="updateTime"/>
        <result column="is_deleted" property="isDeleted"/>
    </resultMap>

    <select id="selectNextOrderNum" resultType="int">
        SELECT IFNULL(MAX(order_num), 0) + 1
        FROM course_chapter
        WHERE course_id = #{courseId} AND is_deleted = 0
    </select>

    <insert id="insert" parameterType="com.dora.entity.CourseChapter" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO course_chapter (course_id, title, description, order_num, create_time, update_time, is_deleted)
        VALUES (#{courseId}, #{title}, #{description}, #{orderNum}, NOW(), NOW(), 0)
    </insert>

    <!-- 根据ID查询章节 -->
    <select id="selectById" resultMap="CourseChapterResultMap">
        SELECT * FROM course_chapter 
        WHERE id = #{id} AND is_deleted = 0
    </select>

    <select id="selectByCourseId" resultMap="CourseChapterResultMap">
        SELECT id, course_id, title, description, order_num, create_time, update_time, is_deleted
        FROM course_chapter
        WHERE course_id = #{courseId}
          AND is_deleted = 0
        ORDER BY order_num ASC, id ASC
    </select>

    <!-- 新增：根据ID更新章节 -->
    <update id="updateById" parameterType="com.dora.entity.CourseChapter">
        UPDATE course_chapter
        <set>
            <if test="title != null">title = #{title},</if>
            <if test="description != null">description = #{description},</if>
            <if test="orderNum != null">order_num = #{orderNum},</if>
            update_time = NOW()
        </set>
        WHERE id = #{id} AND is_deleted = 0
    </update>

    <!-- 新增：软删除章节 -->
    <update id="softDelete">
        UPDATE course_chapter
        SET is_deleted = 1,
            update_time = NOW()
        WHERE id = #{id} AND course_id = #{courseId} AND is_deleted = 0
    </update>

    <!-- 新增：根据课程ID软删除所有章节 -->
    <update id="softDeleteByCourseId">
        UPDATE course_chapter
        SET is_deleted = 1,
            update_time = NOW()
        WHERE course_id = #{courseId} AND is_deleted = 0
    </update>

</mapper>


