<?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.huiju.estateagents.mapper.SysMenuMapper">
    <select id="getUserModules" resultType="com.huiju.estateagents.entity.SysMenu">
        SELECT
            t.*,
            IF(s.user_id IS NULL, 0, 1) AS has_rights
        FROM
            sys_menu t
        LEFT JOIN (
            SELECT
                a.menu_id,
                b.user_id
            FROM
                ta_role_menu a
            INNER JOIN ta_user_role b ON a.role_id = b.role_id
            AND b.user_id = #{userId}
        ) s ON t.menu_id = s.menu_id
        WHERE
            t.menu_id = t.menu_root
        AND t.`status` = 1
        ORDER BY sort_num
    </select>

    <delete id="deleteAdminBtns">
        DELETE t
        FROM
            ta_role_button t
        INNER JOIN sys_button_in_menu b ON t.btn_id = b.btn_id
        INNER JOIN sys_menu m ON m.menu_id = b.menu_id
        INNER JOIN ta_role r ON t.role_id = r.role_id
        WHERE
            <if test="orgId != null">
                r.org_id = #{orgId}
            </if>
            <if test="roleId != null">
                r.role_id = #{roleId}
            </if>
        AND m.menu_root IN
            <foreach item="item" index="index" collection="menus" open="(" separator="," close=")">
              #{item}
            </foreach>
    </delete>

    <delete id="deleteAdminMenus">
        DELETE t
        FROM
            ta_role_menu t
        INNER JOIN sys_menu m ON m.menu_id = t.menu_id
        INNER JOIN ta_role r ON t.role_id = r.role_id
        WHERE
            <if test="orgId != null">
                r.org_id = #{orgId}
            </if>
            <if test="roleId != null">
                r.role_id = #{roleId}
            </if>
        AND m.menu_root IN
            <foreach item="item" index="index" collection="menus" open="(" separator="," close=")">
              #{item}
            </foreach>
    </delete>

    <insert id="insertAdminMenus">
        INSERT INTO ta_role_menu (role_id, menu_id)
        SELECT
            ${roleId},
            s.menu_id
        FROM
            sys_menu s
        WHERE
            s.menu_root IN
        <foreach item="item" index="index" collection="menus" open="(" separator="," close=")">
            #{item}
        </foreach>
    </insert>

    <insert id="insertAdminBtns">
        INSERT INTO ta_role_button (role_id, btn_id) SELECT
            ${roleId},
            m.btn_id
        FROM
            sys_menu s
        INNER JOIN sys_button_in_menu m ON s.menu_id = m.menu_id
        WHERE
            s.menu_root IN
        <foreach item="item" index="index" collection="menus" open="(" separator="," close=")">
            #{item}
        </foreach>
    </insert>
</mapper>
