<?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.bonus.core.autth.role.mapper.MgrRoleOrgMapper">
    <insert id="insertBatch" parameterType="object">
        insert into mgr_role_org
        values
        <foreach collection="orgList" item="org" index="index" separator=",">
            (#{roleId}, #{org.orgId}, #{org.halfSelect})
        </foreach>
    </insert>

    <select id="getTenantOrg" resultType="com.bonus.core.customer.dto.CustOrgTreeDTO">
        SELECT c.org_id,
               c.org_num,
               c.org_name,
               c.org_full_name,
               c.org_level,
               c.super_id,
               c.sort
        <if test="'2'.toString() == authPO.roleType.toString()">
            ,
                t.half_select
        </if>
        FROM
        <choose>
            <when test="'2'.toString() == authPO.roleType.toString()">
                ( select org_id,
                half_select
                from (
                SELECT o.org_id, o.half_select
                FROM mgr_role_org o
                LEFT JOIN mgr_role r ON r.role_id = o.role_id
                LEFT JOIN mgr_user_role u ON o.role_id = u.role_id
                WHERE r.del_flag = 2
                AND u.user_id = #{authPO.userId}
                AND r.role_code = #{authPO.roleCode}
                ) s
                ORDER BY org_id, half_select) t
                LEFT JOIN cust_org c ON c.org_id = t.org_id
                <where>
                    <if test="delFlag != null">
                        AND c.if_del = #{delFlag}
                    </if>
                    <if test="excludeMiddle == 1">
                        AND t.half_select = 1
                    </if>
                </where>
            </when>
            <otherwise>
                cust_org c
                <where>
                    <if test="delFlag != null">
                        AND c.if_del = #{delFlag}
                    </if>
                </where>
            </otherwise>
        </choose>
    </select>

    <select id="getRoleListByOrgId" resultType="com.bonus.core.autth.role.entity.MgrRole">
        SELECT mro.role_id
        FROM mgr_role_org mro
        WHERE mro.org_id = #{orgId}
          AND mro.half_select = #{excludeMiddle}
        <if test="roleId != null">
            AND mro.role_id != #{roleId}
        </if>
        GROUP BY mro.role_id
    </select>
</mapper>
