<?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.PermissionMapper">

    <!-- 基础结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.permission.TbSysPermission">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="permission_id" property="permissionID" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="code" property="code" jdbcType="VARCHAR"/>
        <result column="description" property="description" jdbcType="VARCHAR"/>
        <result column="module_id" property="moduleID" 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="PermissionVO" type="org.xyzh.common.vo.PermissionVO">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="permission_id" property="permissionID" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="code" property="code" 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="creator_name" property="creatorName" 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"/>
        <result column="delete_time" property="deleteTime" jdbcType="TIMESTAMP"/>
        <result column="deleted" property="deleted" jdbcType="BOOLEAN"/>
    </resultMap>

    <resultMap id="PermissionBindMenu" type="org.xyzh.common.dto.menu.TbSysMenu">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="menu_id" property="menuID" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
    </resultMap>

    <resultMap id="PermissionBindRole" type="org.xyzh.common.dto.role.TbSysRole">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="role_id" property="roleID" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="description" property="description" jdbcType="VARCHAR"/>
    </resultMap>

    <!-- 基础字段 -->
    <sql id="Base_Column_List">
        id, permission_id, name, code, description, module_id, creator, updater, 
        create_time, update_time, delete_time, deleted
    </sql>

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

    <!-- 根据用户ID查询权限列表 -->
    <select id="selectPermissionsByUserId" resultMap="BaseResultMap">
        SELECT DISTINCT
            p.id, p.permission_id, p.name, p.code, p.description, 
            p.creator, p.updater, 
            p.create_time, p.update_time, p.delete_time, p.deleted
        FROM tb_sys_user_dept_role ur
        INNER JOIN tb_sys_role_permission rp ON rp.role_id = ur.role_id
        INNER JOIN tb_sys_permission p ON p.permission_id = rp.permission_id
        WHERE p.deleted = 0 
        AND rp.deleted = 0
        AND ur.deleted = 0
        AND ur.user_id = #{userId}
        ORDER BY p.create_time ASC
    </select>

    <!-- 根据角色ID查询权限列表 -->
    <select id="selectPermissionsByRoleID" resultMap="BaseResultMap">
        SELECT 
            p.id, p.permission_id, p.name, p.code, p.description, 
            p.creator, p.updater, 
            p.create_time, p.update_time, p.delete_time, p.deleted
        FROM tb_sys_role_permission rp
        INNER JOIN tb_sys_permission p ON p.permission_id = rp.permission_id
        WHERE p.deleted = 0 
        AND rp.deleted = 0
        AND rp.role_id = #{roleID}
        ORDER BY p.create_time ASC
    </select>

    <!-- 根据权限编码查询权限 -->
    <select id="selectByPermissionCode" resultMap="BaseResultMap">
        SELECT 
        <include refid="Base_Column_List"/>
        FROM tb_sys_permission
        WHERE deleted = 0 
        AND code = #{permissionCode}
        LIMIT 1
    </select>

    <!-- 检查权限名称是否存在 -->
    <select id="countByPermissionName" resultType="int">
        SELECT COUNT(1)
        FROM tb_sys_permission
        WHERE deleted = 0 
        AND name = #{permissionName}
        <if test="excludeID != null and excludeID != ''">
            AND id != #{excludeID}
        </if>
    </select>

    <!-- 检查权限编码是否存在 -->
    <select id="countByPermissionCode" resultType="int">
        SELECT COUNT(1)
        FROM tb_sys_permission
        WHERE deleted = 0 
        AND code = #{permissionCode}
        <if test="excludeID != null and excludeID != ''">
            AND id != #{excludeID}
        </if>
    </select>

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

    <!-- 插入权限 -->
    <insert id="insertPermission" >
        INSERT INTO tb_sys_permission
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="permission.id != null">id,</if>
            <if test="permission.permissionID != null">permission_id,</if>
            <if test="permission.name != null">name,</if>
            <if test="permission.code != null">code,</if>
            <if test="permission.description != null">description,</if>
            <if test="permission.creator != null">creator,</if>
            <if test="permission.createTime != null">create_time,</if>
            deleted
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="permission.id != null">#{permission.id},</if>
            <if test="permission.permissionID != null">#{permission.permissionID},</if>
            <if test="permission.name != null">#{permission.name},</if>
            <if test="permission.code != null">#{permission.code},</if>
            <if test="permission.description != null">#{permission.description},</if>
            <if test="permission.creator != null">#{permission.creator},</if>
            <if test="permission.createTime != null">#{permission.createTime},</if>
            0
        </trim>
    </insert>

    <!-- 更新权限 -->
    <update id="updatePermission" >
        UPDATE tb_sys_permission
        <set>
            <if test="permission.permissionID != null">permission_id = #{permission.permissionID},</if>
            <if test="permission.name != null">name = #{permission.name},</if>
            <if test="permission.code != null">code = #{permission.code},</if>
            <if test="permission.description != null">description = #{permission.description},</if>
            <if test="permission.updater != null">updater = #{permission.updater},</if>
            update_time = NOW()
        </set>
        WHERE id = #{permission.id} AND deleted = 0
    </update>

    <!-- 根据ID删除（逻辑删除） -->
    <update id="deletePermission" >
        UPDATE tb_sys_permission 
        SET deleted = 1,
            delete_time = #{permission.deleteTime},
            updater = #{permission.updater},
            update_time = #{permission.updateTime}
        WHERE id = #{permission.id} AND deleted = 0
    </update>

    <!-- checkPermissionExists --> 

    <select id="checkPermissionExists" >
        SELECT 
        <include refid="Base_Column_List"/>
        FROM tb_sys_permission
        WHERE deleted = 0 
        AND permission_id IN
        <foreach collection="permissionIds" item="permissionId" open="(" separator="," close=")">
            #{permissionId}
        </foreach>
    </select>

    <!-- 查询权限列表 --> 
    <select id="selectPermission" resultMap="BaseResultMap" >
        SELECT 
            <include refid="Base_Column_List"/>
        FROM tb_sys_permission
        WHERE deleted = 0 
            <if test="permission.name != null and permission.name != ''">
                AND name LIKE CONCAT('%', #{permission.name}, '%')
            </if>
            <if test="permission.code != null and permission.code != ''">
                AND code = #{permission.code}
            </if>
            <if test="permission.id != null and permission.id != ''">
                AND id = #{permission.id}
            </if>
        LIMIT 1
    </select>

    <select id="selectPermissionList" resultMap="PermissionVO" >
        SELECT 
            tsp.id, tsp.permission_id, tsp.name, tsp.code, tsp.description, 
            tsp.creator, tsp.updater, 
            tsu.username as creator_name, tuu.username as updater_name,
            tsp.create_time, tsp.update_time, tsp.delete_time, tsp.deleted
        FROM tb_sys_permission tsp
        INNER JOIN tb_sys_user tsu ON tsp.creator = tsu.id
        LEFT JOIN tb_sys_user tuu ON tsp.updater = tuu.id
        WHERE tsp.deleted = 0 
            <if test="permission.name != null and permission.name != ''">
                AND tsp.name LIKE CONCAT('%', #{permission.name}, '%')
            </if>
            <if test="permission.code != null and permission.code != ''">
                AND tsp.code = #{permission.code}
            </if>
        ORDER BY tsp.code, tsp.create_time ASC
    </select>

    <!-- selectPermission --> 

    <select id="selectPermissionVO" resultMap="PermissionVO" >
        SELECT 
            tsp.id, tsp.permission_id, tsp.name, tsp.code, tsp.description, 
            tsp.creator, tsp.updater, 
            tsu.username as creator_name, tuu.username as updater_name,
            tsp.create_time, tsp.update_time, tsp.delete_time, tsp.deleted
        FROM tb_sys_permission tsp
        INNER JOIN tb_sys_user tsu ON tsp.creator = tsu.id
        LEFT JOIN tb_sys_user tuu ON tsp.updater = tuu.id
        WHERE tsp.deleted = 0 
            <if test="permission.name != null and permission.name != ''">
                AND tsp.name LIKE CONCAT('%', #{permission.name}, '%')
            </if>
            <if test="permission.code != null and permission.code != ''">
                AND tsp.code = #{permission.code}
            </if>
            <if test="permission.id != null and permission.id != ''">
                AND tsp.id = #{permission.id}
            </if>
        LIMIT 1
    </select>

    <!-- selectPermissionBindMenu --> 

    <select id="selectPermissionBindMenu" resultMap="PermissionBindMenu">
        SELECT 
            tsm.id, tsm.menu_id, tsm.name
        FROM tb_sys_menu tsm
        INNER JOIN tb_sys_menu_permission tsmp ON tsmp.menu_id = tsm.menu_id
        WHERE tsm.deleted = 0 
        AND tsmp.deleted = 0
        AND tsmp.permission_id = #{permission.permissionID}
        ORDER BY tsm.menu_id, tsm.create_time ASC
    </select>

    <!-- selectPermissionBindRole --> 
    <select id="selectPermissionBindRole" resultMap="PermissionBindRole">
        SELECT 
            tsr.id, tsr.role_id, tsr.name, tsr.description
        FROM tb_sys_role tsr
        INNER JOIN tb_sys_role_permission tsrp ON tsrp.role_id = tsr.role_id
        WHERE tsr.deleted = 0 
        AND tsrp.deleted = 0
        AND tsrp.permission_id = #{permission.permissionID}
        ORDER BY tsr.role_id, tsr.create_time ASC
    </select>

    <!-- 根据模块ID查询权限列表 -->
    <select id="selectPermissionsByModuleID" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_sys_permission
        WHERE module_id = #{moduleID} AND deleted = 0
        ORDER BY create_time DESC
    </select>

    <!-- 绑定权限到模块 -->
    <update id="bindPermissionsToModule">
        UPDATE tb_sys_permission
        SET module_id = #{moduleID}, update_time = NOW()
        WHERE permission_id IN
        <foreach collection="permissionIds" item="permissionId" open="(" separator="," close=")">
            #{permissionId}
        </foreach>
        AND deleted = 0
    </update>

    <!-- 解绑模块的权限 -->
    <update id="unbindPermissionsFromModule">
        UPDATE tb_sys_permission
        SET module_id = NULL, update_time = NOW()
        WHERE permission_id IN
        <foreach collection="permissionIds" item="permissionId" open="(" separator="," close=")">
            #{permissionId}
        </foreach>
        AND module_id = #{moduleID}
        AND deleted = 0
    </update>

    <!-- 获取模块的权限ID列表 -->
    <select id="getModulePermissionIds" resultType="String">
        SELECT permission_id
        FROM tb_sys_permission
        WHERE module_id = #{moduleID} AND deleted = 0
        ORDER BY create_time DESC
    </select>
</mapper>
