<?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.news.mapper.TagMapper">

    <!-- 基础结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.resource.TbTag">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="tag_id" property="tagID" jdbcType="VARCHAR"/>
        <result column="name" property="name" jdbcType="VARCHAR"/>
        <result column="color" property="color" jdbcType="VARCHAR"/>
        <result column="description" property="description" jdbcType="VARCHAR"/>
        <result column="tag_type" property="tagType" jdbcType="INTEGER"/>
        <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, tag_id, name, color, description, tag_type, creator, updater, create_time, 
        update_time, delete_time, deleted
    </sql>

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

    <!-- 权限过滤条件（基于dept_path的高效继承） -->
    <sql id="Permission_Filter">
        INNER JOIN tb_resource_permission rp ON t.tag_id = rp.resource_id 
            AND rp.resource_type = 9 
            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>

    <!-- selectTags - 添加权限过滤 -->
    <select id="selectTags" resultMap="BaseResultMap">
        SELECT DISTINCT t.*
        FROM tb_tag t
        <include refid="Permission_Filter"/>
        WHERE t.deleted = 0
            <if test="filter.tagID != null and filter.tagID != ''">
                AND t.tag_id = #{filter.tagID}
            </if>
            <if test="filter.name != null and filter.name != ''">
                AND t.name LIKE CONCAT('%', #{filter.name}, '%')
            </if>
            <if test="filter.color != null and filter.color != ''">
                AND t.color = #{filter.color}
            </if>
            <if test="filter.tagType != null">
                AND t.tag_type = #{filter.tagType}
            </if>
        ORDER BY t.create_time DESC
    </select>

    <!-- 根据标签ID查询标签信息 -->
    <select id="selectByTagId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_tag
        WHERE tag_id = #{tagId} AND deleted = 0
    </select>

    <!-- 根据标签名称查询标签 - 添加权限过滤 -->
    <select id="selectByName" resultMap="BaseResultMap">
        SELECT DISTINCT t.*
        FROM tb_tag t
        <include refid="Permission_Filter"/>
        WHERE t.name = #{name} AND t.deleted = 0
    </select>

    <!-- 根据状态查询标签列表 - 添加权限过滤 -->
    <select id="selectByStatus" resultMap="BaseResultMap">
        SELECT DISTINCT t.*
        FROM tb_tag t
        <include refid="Permission_Filter"/>
        WHERE t.deleted = 0
        ORDER BY t.create_time DESC
    </select>

    <!-- 根据标签类型查询标签列表 -->
    <select id="selectByTagType" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_tag
        WHERE deleted = 0
        <if test="tagType != null">
            AND tag_type = #{tagType}
        </if>
        ORDER BY create_time DESC
    </select>

    <!-- 查询热门标签列表 -->
    <select id="selectHotTags" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_tag
        WHERE deleted = 0
        ORDER BY create_time DESC
        <if test="limit != null and limit > 0">
            LIMIT #{limit}
        </if>
    </select>

    <!-- 检查标签名称是否存在（同类型下） - 添加权限过滤 -->
    <select id="countByNameAndType" resultType="int">
        SELECT COUNT(DISTINCT t.id)
        FROM tb_tag t
        <include refid="Permission_Filter"/>
        WHERE t.name = #{name} AND t.deleted = 0
        <if test="tagType != null">
            AND t.tag_type = #{tagType}
        </if>
        <if test="excludeId != null and excludeId != ''">
            AND t.id != #{excludeId}
        </if>
    </select>

    <!-- 插入标签 -->
    <insert id="insertTag" parameterType="org.xyzh.common.dto.resource.TbTag">
        INSERT INTO tb_tag (
            id, tag_id, name, color, description, tag_type, creator, updater, create_time,
            update_time, delete_time, deleted
        ) VALUES (
            #{id}, #{tagID}, #{name}, #{color}, #{description}, #{tagType}, #{creator}, #{updater}, #{createTime},
            #{updateTime}, #{deleteTime}, #{deleted}
        )
    </insert>

    <!-- 更新标签 -->
    <update id="updateTag" parameterType="org.xyzh.common.dto.resource.TbTag">
        UPDATE tb_tag
        <set>
            <if test="tagID != null and tagID != ''">
                tag_id = #{tagID},
            </if>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="color != null and color != ''">
                color = #{color},
            </if>
            <if test="description != null and description != ''">
                description = #{description},
            </if>
            <if test="tagType != null">
                tag_type = #{tagType},
            </if>
            <if test="updater != null and updater != ''">
                updater = #{updater},
            </if>
            <if test="updateTime != null">
                update_time = #{updateTime},
            </if>
            <if test="deleteTime != null">
                delete_time = #{deleteTime},
            </if>
            <if test="deleted != null">
                deleted = #{deleted},
            </if>
        </set>
        WHERE id = #{id}
    </update>

    <!-- 删除标签 -->
    <delete id="deleteTag" parameterType="org.xyzh.common.dto.resource.TbTag">
        DELETE FROM tb_tag
        WHERE id = #{id}
    </delete>

    <!-- 批量插入标签 -->
    <insert id="batchInsertTags" parameterType="java.util.List">
        INSERT INTO tb_tag (
            id, tag_id, name, color, description, tag_type, creator, updater, create_time,
            update_time, delete_time, deleted
        ) VALUES
        <foreach collection="tagList" item="item" separator=",">
            (
                #{item.id}, #{item.tagID}, #{item.name}, #{item.color}, #{item.description}, 
                #{item.tagType}, #{item.creator}, #{item.updater}, #{item.createTime}, #{item.updateTime}, 
                #{item.deleteTime}, #{item.deleted}
            )
        </foreach>
    </insert>

    <!-- 批量删除标签 -->
    <delete id="batchDeleteTags">
        DELETE FROM tb_tag
        WHERE id IN
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

    <!-- 分页查询标签 -->
    <select id="selectTagsPage" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_tag
        <include refid="Where_Clause" />
        ORDER BY create_time DESC
        LIMIT #{pageParam.pageSize} OFFSET #{pageParam.offset}
    </select>

    <!-- 统计标签总数 -->
    <select id="countTags" resultType="long">
        SELECT COUNT(1)
        FROM tb_tag
        <include refid="Where_Clause" />
    </select>

</mapper>
