<?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="cn.newfeifan.mall.module.distri.dal.mysql.sharepath.SharePathMapper">


    <!-- 增加节点 -->
    <insert id="addNode">
        INSERT INTO distri_share_path (ancestor,
                                       anc_name,
                                       anc_nick_name,
                                       anc_phone,
                                       descendant,
                                       desc_name,
                                       desc_nick_name,
                                       desc_phone,
                                       depth, sort)
        SELECT ancestor,
               anc_name,
               anc_nick_name,
               anc_phone,

               #{newDescendantId},
               #{newDescendantName},
               #{newDescendantNickName},
               #{newDescendantMobile},

               depth + 1,
               (SELECT IFNULL(MAX(sort), 0) + 1 FROM distri_share_path WHERE ancestor = #{parentId} AND depth = 1 and deleted = 0)
        FROM distri_share_path
        WHERE descendant = #{parentId} and deleted = 0
        UNION ALL
        SELECT #{parentId},
               #{parentName},
               #{parentNickName},
               #{parentMobile},

               #{newDescendantId},
               #{newDescendantName},
               #{newDescendantNickName},
               #{newDescendantMobile},
               1,
               (SELECT IFNULL(MAX(sort), 0) + 1 FROM distri_share_path WHERE ancestor = #{parentId} AND depth = 1 and deleted = 0);
    </insert>


    <!-- Get the maximum sort value for a given parent ID -->
    <select id="getMaxSortByParentId" resultType="int" parameterType="long">
        SELECT IFNULL(MAX(sort), 0) + 1
        FROM distri_share_path
        WHERE ancestor = #{parentId}
          AND depth = 1
    </select>


    <!-- 删除旧的祖先关系 -->
    <delete id="deleteOldAncestors" parameterType="java.lang.Long">
        DELETE
        FROM distri_share_path
        WHERE descendant IN (SELECT descendant
                             FROM distri_share_path
                             WHERE ancestor = #{nodeId})
          AND ancestor NOT IN (SELECT descendant
                               FROM distri_share_path
                               WHERE ancestor = #{nodeId});
    </delete>

    <!-- 添加新的祖先关系 -->
    <insert id="addNewAncestors" parameterType="map">
        INSERT INTO distri_share_path (ancestor, descendant, depth, sort)
        SELECT np.ancestor, c.descendant, np.depth + c.depth + 1, 0
        FROM distri_share_path AS np
                 CROSS JOIN (SELECT descendant, depth
                             FROM distri_share_path
                             WHERE ancestor = #{nodeId}) AS c
        WHERE np.descendant = #{newParentId}
        UNION ALL
        SELECT #{nodeId} as ancestor, descendant, depth + 1, 0
        FROM distri_share_path
        WHERE ancestor = #{nodeId};
    </insert>


    <!-- 查询某节点的所有后代节点 -->
    <select id="findAllDescendants" resultType="long">
        SELECT descendant
        FROM distri_share_path
        WHERE ancestor = #{ancestorId}
    </select>

    <!-- 查询排序号小于当前节点的兄弟节点 -->
    <select id="findLessSortedSiblings" resultType="long">
        SELECT a.descendant
        FROM distri_share_path a
                 JOIN distri_share_path b ON a.ancestor = b.ancestor
        WHERE b.descendant = #{descendantId}
          AND a.sort &gt; b.sort
    </select>

    <select id="selectListByVisitor"
            resultType="cn.newfeifan.mall.module.distri.dal.dataobject.sharepath.SharePathDO">
        select path.* from distri_share_path path
                    left join member_user user on user.id = path.descendant
                    where depth = 1 and ancestor = #{ancestor} and user.visitor = #{visitor} and path.deleted = 0
    </select>
    <select id="selectListByUserId"
            resultType="cn.newfeifan.mall.module.distri.dal.dataobject.sharepath.SharePathDO">
        WITH RECURSIVE user_hierarchy AS (
        -- 初始查询，获取目标用户及其直接左右区用户
        SELECT user_id, user_name, left_child_id, right_child_id,parent_id, depth, referrer_id,phone
        FROM distri_share_path
        WHERE user_id = #{userId}
        UNION ALL
        -- 递归部分，获取左右区用户的下级用户，处理NULL值
        SELECT u.user_id, u.user_name, u.left_child_id, u.right_child_id, u.parent_id, u.depth, u.referrer_id, u.phone
        FROM distri_share_path u
        INNER JOIN user_hierarchy uh ON (
        (u.user_id = uh.left_child_id AND uh.left_child_id IS NOT NULL) OR
        (u.user_id = uh.right_child_id AND uh.right_child_id IS NOT NULL)
        ) where u.depth &lt;= #{maxDepth}
        )
        SELECT * FROM user_hierarchy;
    </select>
    <select id="selectListPage"
            resultType="cn.newfeifan.mall.module.distri.dal.dataobject.sharepath.SharePathDO">
        WITH RECURSIVE user_hierarchy AS (
        -- 初始查询，获取目标用户及其直接左右区用户
        SELECT user_id, user_name, left_child_id, right_child_id,parent_id, depth, referrer_id,phone
        FROM distri_share_path
        WHERE user_id = #{userId}
        UNION ALL
        -- 递归部分，获取左右区用户的下级用户，处理NULL值
        SELECT u.user_id, u.user_name, u.left_child_id, u.right_child_id, u.parent_id, u.depth, u.referrer_id, u.phone
        FROM distri_share_path u
        INNER JOIN user_hierarchy uh ON (
        (u.user_id = uh.left_child_id AND uh.left_child_id IS NOT NULL) OR
        (u.user_id = uh.right_child_id AND uh.right_child_id IS NOT NULL)
        )
        )
        SELECT * FROM user_hierarchy
        ORDER BY depth  -- 根据深度排序，确保层次结构正确
        LIMIT #{pageSize} OFFSET #{pageNo};
    </select>
</mapper>