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

    <!-- 基础结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.dept.TbSysDept">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="dept_id" property="deptID" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="parent_id" property="parentID" jdbcType="VARCHAR"/>
        <result column="dept_path" property="deptPath" 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>

    <!-- 基础字段 -->
    <sql id="Base_Column_List">
        id, dept_id, name, parent_id, dept_path, description, creator, updater, 
        create_time, update_time, delete_time, deleted
    </sql>

    <!-- 通用条件 -->
    <sql id="Where_Clause">
        <where>
            deleted = 0
            <if test="deptID != null and deptID != ''">
                AND dept_id = #{deptID}
            </if>
            <if test="parentID != null and parentID != ''">
                AND parent_id = #{parentID}
            </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 d.dept_id = rp.resource_id 
            AND rp.resource_type = 4 
            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>

    <!-- selectDepts - 添加权限过滤 --> 

    <select id="selectDepts">
        SELECT DISTINCT d.*
        FROM tb_sys_dept d
        <include refid="Permission_Filter"/>
        WHERE d.deleted = 0
            <if test="filter.deptID != null and filter.deptID != ''">
                AND d.dept_id = #{filter.deptID}
            </if>
            <if test="filter.parentID != null and filter.parentID != ''">
                AND d.parent_id = #{filter.parentID}
            </if>
            <if test="filter.name != null and filter.name != ''">
                AND d.name LIKE CONCAT('%', #{filter.name}, '%')
            </if>
        ORDER BY d.dept_id, d.create_time DESC
    </select>

    <!-- 根据父部门ID查询子部门列表 -->
    <select id="selectByParentId" resultMap="BaseResultMap">
        SELECT 
        <include refid="Base_Column_List"/>
        FROM tb_sys_dept
        WHERE deleted = 0 
        AND parent_id = #{parentId}
        ORDER BY dept_id,create_time DESC
    </select>

    <!-- 检查部门名称是否存在 -->
    <select id="countByDeptName" resultType="int">
        SELECT COUNT(1)
        FROM tb_sys_dept
        WHERE deleted = 0 
        AND name = #{deptName}
        <if test="excludeId != null and excludeId != ''">
            AND id != #{excludeId}
        </if>
    </select>

    <!-- 根据部门ID获取部门路径（不带权限过滤，仅用于构建子部门路径） -->
    <select id="getDeptPathByDeptId" resultType="java.lang.String">
        SELECT dept_path
        FROM tb_sys_dept
        WHERE dept_id = #{deptId}
        AND deleted = 0
        LIMIT 1
    </select>

    <!-- 根据部门ID查询部门信息（包含父部门信息） -->
    <select id="selectDeptWithParent" resultMap="BaseResultMap">
        SELECT 
            d.id, d.dept_id, d.parent_id, d.name, d.description, 
            d.creator, d.updater, d.create_time, d.update_time, 
            d.delete_time, d.deleted,
            p.name AS parent_name
        FROM tb_sys_dept d
        LEFT JOIN tb_sys_dept p ON d.parent_id = p.dept_id AND p.deleted = 0
        WHERE d.deleted = 0 
        AND d.dept_id = #{deptId}
    </select>

    <!-- 查询部门树结构 -->
    <select id="selectDeptTree" resultMap="BaseResultMap">
        SELECT 
        <include refid="Base_Column_List"/>
        FROM tb_sys_dept
        WHERE deleted = 0
        ORDER BY 
            CASE WHEN parent_id IS NULL OR parent_id = '' THEN 0 ELSE 1 END,
            parent_id,
            create_time ASC
    </select>

    <!-- insertDept --> 
    <insert id="insertDept" parameterType="org.xyzh.common.dto.dept.TbSysDept">
        INSERT INTO tb_sys_dept (
            id,
            dept_id,
            name,
            parent_id,
            dept_path,
            description,
            creator,
            create_time,
            deleted
        ) VALUES (
            #{id},
            #{deptID},
            #{name},
            #{parentID},
            #{deptPath},
            #{description},
            #{creator},
            #{createTime},
            #{deleted}
        )
    </insert>

    <!-- updateDept -->
    <update id="updateDept" parameterType="org.xyzh.common.dto.dept.TbSysDept">
        UPDATE tb_sys_dept
        <set>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="parentID != null">
                parent_id = #{parentID},
            </if>
            <if test="deptPath != null">
                dept_path = #{deptPath},
            </if>
            <if test="description != null">
                description = #{description},
            </if>
            <if test="updater != null">
                updater = #{updater},
            </if>
            update_time = NOW()
        </set>
        WHERE dept_id = #{deptID} AND deleted = 0
    </update>

    <!-- deleteDept - 逻辑删除 -->
    <update id="deleteDept" parameterType="org.xyzh.common.dto.dept.TbSysDept">
        UPDATE tb_sys_dept
        SET deleted = 1,
            delete_time = NOW()
            <if test="updater != null">
                , updater = #{updater}
            </if>
        WHERE dept_id = #{deptID} AND deleted = 0
    </update>
</mapper>
