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

    <!-- 基础结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.resource.TbResourceRecommend">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="resource_id" property="resourceID" jdbcType="VARCHAR"/>
        <result column="recommend_type" property="recommendType" jdbcType="INTEGER"/>
        <result column="order_num" property="orderNum" jdbcType="INTEGER"/>
        <result column="reason" property="reason" 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>

    <!-- ResourceRecommendVO结果映射（包含资源信息和权限信息） -->
    <resultMap id="ResourceRecommendVOResultMap" type="org.xyzh.common.vo.ResourceRecommendVO">
        <!-- 推荐表字段 -->
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="resource_id" property="resourceID" jdbcType="VARCHAR"/>
        <result column="recommend_type" property="recommendType" jdbcType="INTEGER"/>
        <result column="order_num" property="orderNum" jdbcType="INTEGER"/>
        <result column="reason" property="reason" 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"/>
        <!-- 资源表字段 -->
        <result column="title" property="title" jdbcType="VARCHAR"/>
        <result column="summary" property="summary" jdbcType="VARCHAR"/>
        <result column="cover_image" property="coverImage" jdbcType="VARCHAR"/>
        <result column="tag_id" property="tagID" jdbcType="VARCHAR"/>
        <result column="author" property="author" jdbcType="VARCHAR"/>
        <result column="source" property="source" jdbcType="VARCHAR"/>
        <result column="source_url" property="sourceUrl" jdbcType="VARCHAR"/>
        <result column="view_count" property="viewCount" jdbcType="INTEGER"/>
        <result column="like_count" property="likeCount" jdbcType="INTEGER"/>
        <result column="collect_count" property="collectCount" jdbcType="INTEGER"/>
        <result column="status" property="status" jdbcType="INTEGER"/>
        <result column="is_recommend" property="isRecommend" jdbcType="BOOLEAN"/>
        <result column="is_banner" property="isBanner" jdbcType="BOOLEAN"/>
        <result column="publish_time" property="publishTime" jdbcType="TIMESTAMP"/>
        <result column="resource_creator" property="resourceCreator" jdbcType="VARCHAR"/>
        <result column="resource_updater" property="resourceUpdater" jdbcType="VARCHAR"/>
        <result column="resource_create_time" property="resourceCreateTime" jdbcType="TIMESTAMP"/>
        <result column="resource_update_time" property="resourceUpdateTime" jdbcType="TIMESTAMP"/>
        <!-- 权限字段 -->
        <result column="can_read" property="canRead" jdbcType="TINYINT"/>
        <result column="can_write" property="canWrite" jdbcType="TINYINT"/>
    </resultMap>

    <!-- 基础字段 -->
    <sql id="Base_Column_List">
        id, resource_id, recommend_type, order_num, reason, creator, updater, create_time, 
        update_time, delete_time, deleted
    </sql>

    <!-- 通用条件 -->
    <sql id="Where_Clause">
        <where>
            rr.deleted = 0
            <if test="filter != null">
                <if test="filter.id != null and filter.id != ''">
                    AND rr.id = #{filter.id}
                </if>
                <if test="filter.resourceID != null and filter.resourceID != ''">
                    AND rr.resource_id = #{filter.resourceID}
                </if>
                <if test="filter.recommendType != null">
                    AND rr.recommend_type = #{filter.recommendType}
                </if>
                <if test="filter.reason != null and filter.reason != ''">
                    AND rr.reason LIKE CONCAT('%', #{filter.reason}, '%')
                </if>
            </if>
        </where>
    </sql>

    <!-- 权限过滤条件（基于dept_path的高效继承，注意：需要先JOIN tb_resource表） -->
    <sql id="Permission_Filter">
        INNER JOIN tb_resource_permission rp ON r.resource_id = rp.resource_id 
            AND rp.resource_type = 1 
            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 
                           (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>

    <!-- selectResourceRecommends - 返回VO，包含资源信息和权限 -->
    <select id="selectResourceRecommends" resultMap="ResourceRecommendVOResultMap">
        SELECT DISTINCT 
            rr.id, rr.resource_id, rr.recommend_type, rr.order_num, rr.reason, 
            rr.creator, rr.updater, rr.create_time, rr.update_time, rr.delete_time, rr.deleted,
            r.title, r.summary, r.cover_image, r.tag_id, r.author, r.source, r.source_url,
            r.view_count, r.like_count, r.collect_count, r.status, r.is_recommend, r.is_banner, 
            r.publish_time, r.creator AS resource_creator, r.updater AS resource_updater,
            r.create_time AS resource_create_time, r.update_time AS resource_update_time,
            MAX(rp.can_read) AS can_read, MAX(rp.can_write) AS can_write
        FROM tb_resource_recommend rr
        INNER JOIN tb_resource r ON rr.resource_id = r.resource_id AND r.deleted = 0
        <include refid="Permission_Filter"/>
        <include refid="Where_Clause"/>
        GROUP BY rr.id, rr.resource_id, rr.recommend_type, rr.order_num, rr.reason, 
                 rr.creator, rr.updater, rr.create_time, rr.update_time, rr.delete_time, rr.deleted,
                 r.title, r.summary, r.cover_image, r.tag_id, r.author, r.source, r.source_url,
                 r.view_count, r.like_count, r.collect_count, r.status, r.is_recommend, r.is_banner, 
                 r.publish_time, r.creator, r.updater, r.create_time, r.update_time
        ORDER BY rr.order_num ASC, rr.create_time DESC
    </select>

    <!-- 根据推荐ID查询推荐信息 -->
    <select id="selectByRecommendId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_resource_recommend
        WHERE id = #{recommendId} AND deleted = 0
    </select>

    <!-- 根据资源ID查询推荐列表 -->
    <select id="selectByResourceId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_resource_recommend
        WHERE resource_id = #{resourceId} AND deleted = 0
        ORDER BY order_num ASC, create_time DESC
    </select>

    <!-- 根据状态查询推荐列表 -->
    <select id="selectByStatus" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_resource_recommend
        WHERE deleted = 0
        ORDER BY order_num ASC, create_time DESC
    </select>

    <!-- 根据推荐类型查询推荐列表 - 返回VO，包含资源信息和权限 -->
    <select id="selectByRecommendType" resultMap="ResourceRecommendVOResultMap">
        SELECT DISTINCT 
            rr.id, rr.resource_id, rr.recommend_type, rr.order_num, rr.reason, 
            rr.creator, rr.updater, rr.create_time, rr.update_time, rr.delete_time, rr.deleted,
            r.title, r.summary, r.cover_image, r.tag_id, r.author, r.source, r.source_url,
            r.view_count, r.like_count, r.collect_count, r.status, r.is_recommend, r.is_banner, 
            r.publish_time, r.creator AS resource_creator, r.updater AS resource_updater,
            r.create_time AS resource_create_time, r.update_time AS resource_update_time,
            MAX(rp.can_read) AS can_read, MAX(rp.can_write) AS can_write
        FROM tb_resource_recommend rr
        INNER JOIN tb_resource r ON rr.resource_id = r.resource_id AND r.deleted = 0
        <include refid="Permission_Filter"/>
        WHERE rr.deleted = 0
        <if test="recommendType != null">
            AND rr.recommend_type = #{recommendType}
        </if>
        GROUP BY rr.id, rr.resource_id, rr.recommend_type, rr.order_num, rr.reason, 
                 rr.creator, rr.updater, rr.create_time, rr.update_time, rr.delete_time, rr.deleted,
                 r.title, r.summary, r.cover_image, r.tag_id, r.author, r.source, r.source_url,
                 r.view_count, r.like_count, r.collect_count, r.status, r.is_recommend, r.is_banner, 
                 r.publish_time, r.creator, r.updater, r.create_time, r.update_time
        ORDER BY rr.order_num ASC, rr.create_time DESC
        <if test="limit != null and limit > 0">
            LIMIT #{limit}
        </if>
    </select>
    
    <!-- 根据资源ID和推荐类型查询 -->
    <select id="selectByResourceIdAndType" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_resource_recommend
        WHERE resource_id = #{resourceId} AND deleted = 0
        <if test="recommendType != null">
            AND recommend_type = #{recommendType}
        </if>
        ORDER BY order_num ASC, create_time DESC
    </select>

    <!-- 查询热门推荐列表 -->
    <select id="selectHotRecommends" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_resource_recommend
        WHERE deleted = 0
        ORDER BY order_num ASC, create_time DESC
        <if test="limit != null and limit > 0">
            LIMIT #{limit}
        </if>
    </select>

    <!-- 查询最新推荐列表 -->
    <select id="selectLatestRecommends" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List" />
        FROM tb_resource_recommend
        WHERE deleted = 0
        ORDER BY create_time DESC
        <if test="limit != null and limit > 0">
            LIMIT #{limit}
        </if>
    </select>

    <!-- 插入资源推荐 -->
    <insert id="insertResourceRecommend" parameterType="org.xyzh.common.dto.resource.TbResourceRecommend">
        INSERT INTO tb_resource_recommend (
            id, resource_id, recommend_type, order_num, reason, creator, updater, create_time,
            update_time, delete_time, deleted
        ) VALUES (
            #{id}, #{resourceID}, #{recommendType}, #{orderNum}, #{reason}, #{creator}, #{updater}, #{createTime},
            #{updateTime}, #{deleteTime}, #{deleted}
        )
    </insert>

    <!-- 更新资源推荐 -->
    <update id="updateResourceRecommend" parameterType="org.xyzh.common.dto.resource.TbResourceRecommend">
        UPDATE tb_resource_recommend
        <set>
            <if test="resourceID != null and resourceID != ''">
                resource_id = #{resourceID},
            </if>
            <if test="recommendType != null">
                recommend_type = #{recommendType},
            </if>
            <if test="orderNum != null">
                order_num = #{orderNum},
            </if>
            <if test="reason != null and reason != ''">
                reason = #{reason},
            </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="deleteResourceRecommend" parameterType="org.xyzh.common.dto.resource.TbResourceRecommend">
        DELETE FROM tb_resource_recommend
        WHERE id = #{id}
    </delete>

    <!-- 批量插入资源推荐 -->
    <insert id="batchInsertResourceRecommends" parameterType="java.util.List">
        INSERT INTO tb_resource_recommend (
            id, resource_id, recommend_type, order_num, reason, creator, updater, create_time,
            update_time, delete_time, deleted
        ) VALUES
        <foreach collection="resourceRecommendList" item="item" separator=",">
            (
                #{item.id}, #{item.resourceID}, #{item.recommendType}, #{item.orderNum}, #{item.reason}, #{item.creator}, 
                #{item.updater}, #{item.createTime}, #{item.updateTime}, #{item.deleteTime}, #{item.deleted}
            )
        </foreach>
    </insert>

    <!-- 批量删除资源推荐 -->
    <delete id="batchDeleteResourceRecommends">
        DELETE FROM tb_resource_recommend
        WHERE id IN
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

    <!-- 分页查询资源推荐 - 返回VO，包含资源信息和权限 -->
    <select id="selectResourceRecommendsPage" resultMap="ResourceRecommendVOResultMap">
        SELECT DISTINCT 
            rr.id, rr.resource_id, rr.recommend_type, rr.order_num, rr.reason, 
            rr.creator, rr.updater, rr.create_time, rr.update_time, rr.delete_time, rr.deleted,
            r.title, r.summary, r.cover_image, r.tag_id, r.author, r.source, r.source_url,
            r.view_count, r.like_count, r.collect_count, r.status, r.is_recommend, r.is_banner, 
            r.publish_time, r.creator AS resource_creator, r.updater AS resource_updater,
            r.create_time AS resource_create_time, r.update_time AS resource_update_time,
            MAX(rp.can_read) AS can_read, MAX(rp.can_write) AS can_write
        FROM tb_resource_recommend rr
        INNER JOIN tb_resource r ON rr.resource_id = r.resource_id AND r.deleted = 0
        <include refid="Permission_Filter"/>
        <include refid="Where_Clause" />
        GROUP BY rr.id, rr.resource_id, rr.recommend_type, rr.order_num, rr.reason, 
                 rr.creator, rr.updater, rr.create_time, rr.update_time, rr.delete_time, rr.deleted,
                 r.title, r.summary, r.cover_image, r.tag_id, r.author, r.source, r.source_url,
                 r.view_count, r.like_count, r.collect_count, r.status, r.is_recommend, r.is_banner, 
                 r.publish_time, r.creator, r.updater, r.create_time, r.update_time
        ORDER BY rr.order_num ASC, rr.create_time DESC
        LIMIT #{pageParam.pageSize} OFFSET #{pageParam.offset}
    </select>

    <!-- 统计资源推荐总数 - 添加权限过滤 -->
    <select id="countResourceRecommends" resultType="long">
        SELECT COUNT(DISTINCT rr.id)
        FROM tb_resource_recommend rr
        INNER JOIN tb_resource r ON rr.resource_id = r.resource_id AND r.deleted = 0
        <include refid="Permission_Filter"/>
        <include refid="Where_Clause" />
    </select>


</mapper>
