<?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="org.xyzh.system.mapper.RoleMapper">

    <!-- 基础结果映射 -->
    <resultMap id="tbSysRoleResultMap" type="org.xyzh.common.dto.role.TbSysRole">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="dept_id" property="deptID" jdbcType="VARCHAR"/>
        <result column="role_id" property="roleID" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="description" property="description" jdbcType="VARCHAR"/>
        <result column="creator" property="creator" jdbcType="VARCHAR"/>
        <result column="updater" property="updater" jdbcType="VARCHAR"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
        <result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
        <result column="delete_time" property="deleteTime" jdbcType="TIMESTAMP"/>
        <result column="deleted" property="deleted" jdbcType="BOOLEAN"/>
    </resultMap>

    <resultMap id="deptRoleVOResultMap" type="org.xyzh.common.vo.UserDeptRoleVO">
        <result column="user_id" property="userID" jdbcType="VARCHAR"/>
        <result column="username" property="username" jdbcType="VARCHAR"/>
        <result column="dept_id" property="deptID" jdbcType="VARCHAR"/>
        <result column="dept_name" property="deptName" jdbcType="VARCHAR"/>
        <result column="dept_description" property="deptDescription" jdbcType="VARCHAR"/>
        <result column="dept_path" property="deptPath" jdbcType="VARCHAR"/>
        <result column="role_id" property="roleID" jdbcType="VARCHAR"/>
        <result column="role_name" property="roleName" jdbcType="VARCHAR"/>
        <result column="role_description" property="roleDescription" jdbcType="VARCHAR"/>
    </resultMap>
    <!-- 基础字段 -->
    <sql id="TbSysRole_Column_List">
        id, role_id, name, description, creator, updater, 
        create_time, update_time, delete_time, deleted
    </sql>

    <!-- 通用条件 -->
    <sql id="Where_Clause">
        <where>
            deleted = 0
            <if test="roleID != null and roleID != ''">
                AND role_id = #{roleID}
            </if>
            <if test="name != null and name != ''">
                AND name LIKE CONCAT('%', #{name}, '%')
            </if>
        </where>
    </sql>

    <!-- 权限过滤条件（基于dept_path的高效继承） -->
    <sql id="Permission_Filter">
        INNER JOIN tb_resource_permission rp ON r.role_id = rp.resource_id 
            AND rp.resource_type = 5 
            AND rp.deleted = 0
            AND rp.can_read = 1
            AND (
                -- 全局权限：所有用户可访问
                (rp.dept_id IS NULL AND rp.role_id IS NULL)
                <if test="userDeptRoles != null and userDeptRoles.size() > 0">
                    OR EXISTS (
                        SELECT 1 
                        FROM (
                            <foreach collection="userDeptRoles" item="udr" separator=" UNION ALL ">
                                SELECT #{udr.deptID} AS dept_id, #{udr.deptPath} AS dept_path, #{udr.roleID} AS role_id
                            </foreach>
                        ) user_roles
                        LEFT JOIN tb_sys_dept perm_dept ON perm_dept.dept_id = rp.dept_id AND perm_dept.deleted = 0
                        WHERE 
                           -- 部门级权限：当前部门或父部门（通过dept_path判断继承关系）
                           (rp.role_id IS NULL AND rp.dept_id IS NOT NULL 
                               AND user_roles.dept_path LIKE CONCAT(perm_dept.dept_path, '%'))
                           -- 角色级权限：跨部门的角色权限
                           OR (rp.dept_id IS NULL AND rp.role_id = user_roles.role_id)
                           -- 精确权限：特定部门的特定角色
                           OR (rp.dept_id = user_roles.dept_id AND rp.role_id = user_roles.role_id)
                    )
                </if>
            )
    </sql>

    <!-- 角色VO结果映射（包含创建人更新人名称） -->
    <resultMap id="RoleVOResultMap" type="org.xyzh.common.vo.PermissionVO">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="role_id" property="roleID" jdbcType="VARCHAR"/>
        <result column="role_name" property="roleName" jdbcType="VARCHAR"/>
        <result column="role_description" property="roleDescription" jdbcType="VARCHAR"/>
        <result column="creator" property="creator" jdbcType="VARCHAR"/>
        <result column="creator_name" property="creatorName" jdbcType="VARCHAR"/>
        <result column="updater" property="updater" jdbcType="VARCHAR"/>
        <result column="updater_name" property="updaterName" jdbcType="VARCHAR"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
        <result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <!-- selectAllRoles - 添加权限过滤和VO返回 --> 
    <select id="selectAllRoles" resultMap="RoleVOResultMap">
        SELECT DISTINCT
            r.id,
            r.role_id,
            r.name AS role_name,
            r.description AS role_description,
            r.creator,
            cu.username AS creator_name,
            r.updater,
            uu.username AS updater_name,
            r.create_time,
            r.update_time
        FROM tb_sys_role r
        <include refid="Permission_Filter"/>
        LEFT JOIN tb_sys_user cu ON r.creator = cu.id AND cu.deleted = 0
        LEFT JOIN tb_sys_user uu ON r.updater = uu.id AND uu.deleted = 0
        WHERE r.deleted = 0
        ORDER BY r.role_id, r.create_time ASC
    </select>

    <!-- 根据过滤条件查询角色列表 - 添加权限过滤 -->
    <select id="selectRole" resultMap="RoleVOResultMap">
        SELECT DISTINCT
            r.id,
            r.role_id,
            r.name AS role_name,
            r.description AS role_description,
            r.creator,
            cu.username AS creator_name,
            r.updater,
            uu.username AS updater_name,
            r.create_time,
            r.update_time
        FROM tb_sys_role r
        <include refid="Permission_Filter"/>
        LEFT JOIN tb_sys_user cu ON r.creator = cu.id AND cu.deleted = 0
        LEFT JOIN tb_sys_user uu ON r.updater = uu.id AND uu.deleted = 0
        WHERE r.deleted = 0
            <if test="filter.roleID != null and filter.roleID != ''">
                AND r.role_id = #{filter.roleID}
            </if>
            <if test="filter.name != null and filter.name != ''">
                AND r.name LIKE CONCAT('%', #{filter.name}, '%')
            </if>
        ORDER BY r.role_id, r.create_time ASC
    </select>

    <!-- 插入角色 -->
    <insert id="insertRole" parameterType="org.xyzh.common.dto.role.TbSysRole">
        INSERT INTO tb_sys_role
        (id, role_id, name, description, creator, create_time)
        VALUES (#{id}, #{roleID}, #{name}, #{description}, #{creator}, #{createTime})
    </insert>
    
    <!-- 更新角色 -->
    <update id="updateRole" parameterType="org.xyzh.common.dto.role.TbSysRole">
        UPDATE tb_sys_role
        (name, description, updater, update_time)
        VALUES (#{name}, #{description}, #{updater}, #{updateTime})
        WHERE role_id = #{roleID}
    </update>

    <!-- 删除角色 -->
    <delete id="deleteRole" parameterType="org.xyzh.common.dto.role.TbSysRole">
        DELETE FROM tb_sys_role
        WHERE role_id = #{roleID}
    </delete>

    <!-- 根据用户ID查询角色列表 -->
    <select id="selectDeptRolesByUserId" resultMap="deptRoleVOResultMap">
        SELECT 
            dr.user_id,
            u.username,
            dr.dept_id,
            d.name AS dept_name,
            d.description AS dept_description,
            d.dept_path,
            dr.role_id,
            r.name AS role_name,
            r.description AS role_description
        FROM tb_sys_user_dept_role dr
        LEFT JOIN tb_sys_user u ON dr.user_id = u.id AND u.deleted = 0
        LEFT JOIN tb_sys_role r ON dr.role_id = r.role_id AND r.deleted = 0
        LEFT JOIN tb_sys_dept d ON dr.dept_id = d.dept_id AND d.deleted = 0
        WHERE dr.deleted = 0 
        AND dr.user_id = #{userId}
        ORDER BY dr.create_time ASC
    </select>

    <!-- 检查角色名称是否存在 - 添加权限过滤 -->
    <select id="countByRoleName" resultType="int">
        SELECT COUNT(DISTINCT r.id)
        FROM tb_sys_role r
        <include refid="Permission_Filter"/>
        WHERE r.deleted = 0 
        AND r.name = #{roleName}
        <if test="excludeId != null and excludeId != ''">
            AND r.id != #{excludeId}
        </if>
    </select>

    <!-- 批量删除角色（逻辑删除） -->
    <update id="batchDeleteByIds">
        UPDATE tb_sys_role 
        SET deleted = 1,
            delete_time = NOW(),
            updater = #{updater}
        WHERE deleted = 0
        AND id IN
        <foreach collection="roleIds" item="roleId" open="(" separator="," close=")">
            #{roleId}
        </foreach>
    </update>



    <!-- checkRoleExists - 检查角色是否存在，不需要权限过滤 --> 
    <select id="checkRoleExists" resultMap="tbSysRoleResultMap">
        SELECT 
        <include refid="TbSysRole_Column_List"/>
        FROM tb_sys_role
        WHERE deleted = 0 
        AND role_id IN
        <foreach collection="roleIds" item="roleId" open="(" separator="," close=")">
            #{roleId}
        </foreach>
    </select>
</mapper>
