<?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.education.business.mapper.education.ExtKnowledgePointMapper">

    <!-- 知识点分页列表 -->
    <select id="selectPageList" resultType="extKnowledgePointDto">
        select * from ext_knowledge_point
        <where>
            <if test="extKnowledgePoint.pointName != null and extKnowledgePoint.pointName != ''">
                <bind name="pointName" value="'%' + extKnowledgePoint.pointName + '%'"/>
                and point_name like #{pointName}
            </if>
            <if test="extKnowledgePoint.courseId != null">
                and course_id = #{extKnowledgePoint.courseId}
            </if>
        </where>
        order by id desc
    </select>

    <!-- 根据 ID 查询知识点 -->
    <select id="selectExtKnowledgePointById" parameterType="int" resultType="com.education.model.entity.ExtKnowledgePoint">
        SELECT * FROM ext_knowledge_point WHERE id = #{id}
    </select>

    <select id="selectListById" resultType="com.education.model.entity.ExtKnowledgePoint">
        WITH RECURSIVE KnowledgeHierarchy AS (
            -- 初始节点：知识点10002本身
            SELECT
                id,
                point_name,
                level,
                parent_id,
                CAST(id AS CHAR(255)) AS path
            FROM ext_knowledge_point
            WHERE id =  #{id}

            UNION ALL

            -- 递归查询所有后代节点
            SELECT
                child.id,
                child.point_name,
                child.level,
                child.parent_id,
                CONCAT(parent.path, ' > ', CAST(child.id AS CHAR(255)))
            FROM ext_knowledge_point child
                     INNER JOIN KnowledgeHierarchy parent
                                ON child.parent_id = parent.id
        )
        SELECT
            id,
            point_name,
            level,
            parent_id,
            path AS hierarchy_path
        FROM KnowledgeHierarchy
        ORDER BY level, id;

    </select>

    <!-- 根据 ID 更新知识点 -->
    <update id="updateExtKnowledgePointById" parameterType="com.education.model.entity.ExtKnowledgePoint">
        UPDATE ext_knowledge_point
        SET course_id = #{courseId},
            point_code = #{pointCode},
            point_name = #{pointName},
            description = #{description},
            level = #{level},
            parent_id = #{parentId},
            sequence = #{sequence},
            resource_url = #{resourceUrl}
        WHERE id = #{id}
    </update>

    <!-- 根据 ID 删除知识点 -->
    <delete id="deleteExtKnowledgePointById" parameterType="int">
        DELETE FROM ext_knowledge_point WHERE id = #{id}
    </delete>

</mapper>