<?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)
        FROM distri_share_path
        WHERE descendant = #{parentId}
        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);
    </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>
</mapper>