<?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.haha.mapper.DataPermissionMapper">

    <!-- 结果映射 -->
    <resultMap id="BaseResultMap" type="com.haha.entity.DataPermission">
        <id column="id" property="id"/>
        <result column="permission_code" property="permissionCode"/>
        <result column="permission_name" property="permissionName"/>
        <result column="module_code" property="moduleCode"/>
        <result column="module_name" property="moduleName"/>
        <result column="operation_type" property="operationType"/>
        <result column="description" property="description"/>
        <result column="sort_order" property="sortOrder"/>
        <result column="status" property="status"/>
        <result column="create_time" property="createTime"/>
        <result column="update_time" property="updateTime"/>
    </resultMap>

    <!-- 基础列 -->
    <sql id="Base_Column_List">
        id, permission_code, permission_name, module_code, module_name, operation_type,
        description, sort_order, status, create_time, update_time
    </sql>

    <!-- 根据模块编码查询权限列表 -->
    <select id="selectByModuleCode" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List"/>
        FROM t_data_permission
        WHERE module_code = #{moduleCode}
        AND status = 1
        ORDER BY sort_order
    </select>

    <!-- 查询所有启用的权限 -->
    <select id="selectAllEnabled" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List"/>
        FROM t_data_permission
        WHERE status = 1
        ORDER BY sort_order
    </select>

    <!-- 根据权限编码查询权限 -->
    <select id="selectByPermissionCode" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List"/>
        FROM t_data_permission
        WHERE permission_code = #{permissionCode}
    </select>

    <!-- 按模块分组查询所有权限 -->
    <select id="selectAllGroupByModule" resultMap="BaseResultMap">
        SELECT <include refid="Base_Column_List"/>
        FROM t_data_permission
        WHERE status = 1
        ORDER BY module_code, sort_order
    </select>

    <!-- 根据角色ID查询权限列表 -->
    <select id="selectByRoleId" resultMap="BaseResultMap">
        SELECT dp.*
        FROM t_data_permission dp
        INNER JOIN t_role_permission rp ON dp.id = rp.permission_id
        WHERE rp.role_id = #{roleId}
        AND dp.status = 1
        ORDER BY dp.sort_order
    </select>

    <!-- 根据角色ID列表查询权限编码列表 -->
    <select id="selectPermissionCodesByRoleIds" resultType="java.lang.String">
        SELECT DISTINCT dp.permission_code
        FROM t_data_permission dp
        INNER JOIN t_role_permission rp ON dp.id = rp.permission_id
        WHERE rp.role_id IN
        <foreach collection="roleIds" item="roleId" open="(" separator="," close=")">
            #{roleId}
        </foreach>
        AND dp.status = 1
    </select>

</mapper>
