<?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.ai.mapper.AiKnowledgeMapper">

    <!-- 基础结果映射 -->
    <resultMap id="BaseResultMap" type="org.xyzh.common.dto.ai.TbAiKnowledge">
        <id column="id" property="id" jdbcType="VARCHAR"/>
        <result column="title" property="title" jdbcType="VARCHAR"/>
        <result column="avatar" property="avatar" jdbcType="VARCHAR"/>
        <result column="description" property="description" jdbcType="VARCHAR"/>
        <result column="content" property="content" jdbcType="LONGVARCHAR"/>
        <result column="source_type" property="sourceType" jdbcType="INTEGER"/>
        <result column="source_id" property="sourceID" jdbcType="VARCHAR"/>
        <result column="file_name" property="fileName" jdbcType="VARCHAR"/>
        <result column="file_path" property="filePath" jdbcType="VARCHAR"/>
        <result column="category" property="category" jdbcType="VARCHAR"/>
        <result column="tags" property="tags" jdbcType="VARCHAR"/>
        <result column="dify_dataset_id" property="difyDatasetId" jdbcType="VARCHAR"/>
        <result column="dify_indexing_technique" property="difyIndexingTechnique" jdbcType="VARCHAR"/>
        <result column="embedding_model" property="embeddingModel" jdbcType="VARCHAR"/>
        <result column="embedding_model_provider" property="embeddingModelProvider" jdbcType="VARCHAR"/>
        <result column="rerank_model" property="rerankModel" jdbcType="VARCHAR"/>
        <result column="rerank_model_provider" property="rerankModelProvider" jdbcType="VARCHAR"/>
        <result column="reranking_enable" property="rerankingEnable" jdbcType="BOOLEAN"/>
        <result column="retrieval_top_k" property="retrievalTopK" jdbcType="INTEGER"/>
        <result column="retrieval_score_threshold" property="retrievalScoreThreshold" jdbcType="DECIMAL"/>
        <result column="vector_id" property="vectorID" jdbcType="VARCHAR"/>
        <result column="document_count" property="documentCount" jdbcType="INTEGER"/>
        <result column="total_chunks" property="totalChunks" jdbcType="INTEGER"/>
        <result column="status" property="status" jdbcType="INTEGER"/>
        <result column="creator" property="creator" jdbcType="VARCHAR"/>
        <result column="creator_dept" property="creatorDept" 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="permission_type" property="permissionType" jdbcType="VARCHAR"/>
        <result column="can_read" property="canRead" jdbcType="BOOLEAN"/>
        <result column="can_write" property="canWrite" jdbcType="BOOLEAN"/>
        <result column="can_delete" property="canDelete" jdbcType="BOOLEAN"/>
    </resultMap>

    <!-- 基础字段 -->
    <sql id="Base_Column_List">
        id, title, avatar, description, content, source_type, source_id, file_name, file_path, 
        category, tags, dify_dataset_id, dify_indexing_technique, embedding_model, embedding_model_provider, 
        rerank_model, rerank_model_provider, reranking_enable, retrieval_top_k, retrieval_score_threshold,
        vector_id, document_count, total_chunks, status, creator, creator_dept, 
        updater, create_time, update_time, delete_time, deleted
    </sql>

    <!-- 过滤条件 -->
    <sql id="Filter_Clause">
        <where>
            k.deleted = 0
            <if test="filter.title != null and filter.title != ''">
                AND k.title LIKE CONCAT('%', #{filter.title}, '%')
            </if>
            <if test="filter.sourceType != null">
                AND k.source_type = #{filter.sourceType}
            </if>
            <if test="filter.sourceID != null and filter.sourceID != ''">
                AND k.source_id = #{filter.sourceID}
            </if>
            <if test="filter.category != null and filter.category != ''">
                AND k.category = #{filter.category}
            </if>
            <if test="filter.creator != null and filter.creator != ''">
                AND k.creator = #{filter.creator}
            </if>
            <if test="filter.creatorDept != null and filter.creatorDept != ''">
                AND k.creator_dept = #{filter.creatorDept}
            </if>
            <if test="filter.difyDatasetId != null and filter.difyDatasetId != ''">
                AND k.dify_dataset_id = #{filter.difyDatasetId}
            </if>
            <if test="filter.status != null">
                AND k.status = #{filter.status}
            </if>
        </where>
    </sql>

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

    <!-- selectAiKnowledges（带权限过滤） -->
    <select id="selectAiKnowledges" resultMap="BaseResultMap">
        SELECT 
            k.*,
            CASE 
                WHEN MAX(CASE WHEN rp.dept_id IS NULL AND rp.role_id IS NULL THEN 1 ELSE 0 END) = 1 THEN 'all'
                WHEN MAX(CASE WHEN rp.dept_id IS NOT NULL AND rp.role_id IS NULL THEN 1 ELSE 0 END) = 1 THEN 'dept'
                WHEN MAX(CASE WHEN rp.dept_id IS NULL AND rp.role_id IS NOT NULL THEN 1 ELSE 0 END) = 1 THEN 'role'
                ELSE 'custom'
            END as permission_type,
            MAX(rp.can_read) as can_read,
            MAX(rp.can_write) as can_write,
            MAX(rp.can_execute) as can_delete
        FROM tb_ai_knowledge k
        <include refid="Permission_Filter"/>
        <include refid="Filter_Clause"/>
        GROUP BY k.id, k.title, k.avatar, k.description, k.content, k.source_type, k.source_id, 
                 k.file_name, k.file_path, k.category, k.tags, k.dify_dataset_id, 
                 k.dify_indexing_technique, k.embedding_model, k.embedding_model_provider,
                 k.rerank_model, k.rerank_model_provider, k.reranking_enable, 
                 k.retrieval_top_k, k.retrieval_score_threshold, k.vector_id, 
                 k.document_count, k.total_chunks, k.status, k.creator, k.creator_dept,
                 k.updater, k.create_time, k.update_time, k.delete_time, k.deleted
        ORDER BY k.create_time DESC
    </select>

    <!-- selectByIdWithPermission（根据ID查询并检查权限） -->
    <select id="selectByIdWithPermission" resultMap="BaseResultMap">
        SELECT k.*
        FROM tb_ai_knowledge k
        <include refid="Permission_Filter"/>
        WHERE k.id = #{knowledgeId}
          AND k.deleted = 0
    </select>

    <!-- checkKnowledgePermission（检查权限） -->
    <select id="checkKnowledgePermission" resultType="java.lang.Integer">
        SELECT COUNT(1)
        FROM tb_resource_permission rp
        WHERE rp.resource_type = 10
          AND rp.resource_id = #{knowledgeId}
          AND rp.deleted = 0
          AND (
              <choose>
                  <when test="permissionType == 'read'">
                      rp.can_read = 1
                  </when>
                  <when test="permissionType == 'write'">
                      rp.can_write = 1
                  </when>
                  <when test="permissionType == 'execute'">
                      rp.can_execute = 1
                  </when>
                  <otherwise>
                      rp.can_read = 1
                  </otherwise>
              </choose>
          )
          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>
          )
    </select>

    <!-- insertKnowledge（插入知识库） -->
    <insert id="insertKnowledge" parameterType="org.xyzh.common.dto.ai.TbAiKnowledge">
        INSERT INTO tb_ai_knowledge (
            id, title, avatar, description, content, source_type, source_id, file_name, file_path,
            category, tags, dify_dataset_id, dify_indexing_technique, embedding_model, embedding_model_provider,
            rerank_model, rerank_model_provider, reranking_enable, retrieval_top_k, retrieval_score_threshold,
            vector_id, document_count, total_chunks, status, creator, creator_dept,
            updater, create_time, update_time, deleted
        ) VALUES (
            #{ID}, #{title}, #{avatar}, #{description}, #{content}, #{sourceType}, #{sourceID}, #{fileName}, #{filePath},
            #{category}, #{tags}, #{difyDatasetId}, #{difyIndexingTechnique}, #{embeddingModel}, #{embeddingModelProvider},
            #{rerankModel}, #{rerankModelProvider}, #{rerankingEnable}, #{retrievalTopK}, #{retrievalScoreThreshold},
            #{vectorID}, #{documentCount}, #{totalChunks}, #{status}, #{creator}, #{creatorDept},
            #{updater}, #{createTime}, #{updateTime}, #{deleted}
        )
    </insert>

    <!-- updateKnowledge（更新知识库） -->
    <update id="updateKnowledge" parameterType="org.xyzh.common.dto.ai.TbAiKnowledge">
        UPDATE tb_ai_knowledge
        <set>
            <if test="title != null and title != ''">title = #{title},</if>
            <if test="avatar != null">avatar = #{avatar},</if>
            <if test="description != null">description = #{description},</if>
            <if test="content != null">content = #{content},</if>
            <if test="sourceType != null">source_type = #{sourceType},</if>
            <if test="sourceID != null">source_id = #{sourceID},</if>
            <if test="fileName != null">file_name = #{fileName},</if>
            <if test="filePath != null">file_path = #{filePath},</if>
            <if test="category != null">category = #{category},</if>
            <if test="tags != null">tags = #{tags},</if>
            <if test="difyDatasetId != null">dify_dataset_id = #{difyDatasetId},</if>
            <if test="difyIndexingTechnique != null">dify_indexing_technique = #{difyIndexingTechnique},</if>
            <if test="embeddingModel != null">embedding_model = #{embeddingModel},</if>
            <if test="embeddingModelProvider != null">embedding_model_provider = #{embeddingModelProvider},</if>
            <if test="rerankModel != null">rerank_model = #{rerankModel},</if>
            <if test="rerankModelProvider != null">rerank_model_provider = #{rerankModelProvider},</if>
            <if test="rerankingEnable != null">reranking_enable = #{rerankingEnable},</if>
            <if test="retrievalTopK != null">retrieval_top_k = #{retrievalTopK},</if>
            <if test="retrievalScoreThreshold != null">retrieval_score_threshold = #{retrievalScoreThreshold},</if>
            <if test="vectorID != null">vector_id = #{vectorID},</if>
            <if test="documentCount != null">document_count = #{documentCount},</if>
            <if test="totalChunks != null">total_chunks = #{totalChunks},</if>
            <if test="status != null">status = #{status},</if>
            <if test="updater != null">updater = #{updater},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
        </set>
        WHERE id = #{ID} AND deleted = 0
    </update>

    <!-- deleteKnowledge（逻辑删除知识库） -->
    <update id="deleteKnowledge" parameterType="org.xyzh.common.dto.ai.TbAiKnowledge">
        UPDATE tb_ai_knowledge
        SET deleted = 1,
            delete_time = NOW(),
            updater = #{updater}
        WHERE id = #{ID} AND deleted = 0
    </update>

    <!-- selectKnowledgeById（根据ID查询知识库，不带权限校验） -->
    <select id="selectKnowledgeById" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM tb_ai_knowledge
        WHERE id = #{knowledgeId} AND deleted = 0
    </select>

    <!-- selectAllKnowledges（查询所有知识库，管理员使用） -->
    <select id="selectAllKnowledges" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM tb_ai_knowledge k
        WHERE k.deleted = 0
        <if test="filter != null">
            <if test="filter.title != null and filter.title != ''">
                AND k.title LIKE CONCAT('%', #{filter.title}, '%')
            </if>
            <if test="filter.category != null and filter.category != ''">
                AND k.category = #{filter.category}
            </if>
            <if test="filter.status != null">
                AND k.status = #{filter.status}
            </if>
        </if>
        ORDER BY k.create_time DESC
    </select>

    <!-- selectKnowledgesPage（分页查询知识库，带权限过滤） -->
    <select id="selectKnowledgesPage" resultMap="BaseResultMap">
        SELECT 
            k.*,
            CASE 
                WHEN MAX(CASE WHEN rp.dept_id IS NULL AND rp.role_id IS NULL THEN 1 ELSE 0 END) = 1 THEN 'all'
                WHEN MAX(CASE WHEN rp.dept_id IS NOT NULL AND rp.role_id IS NULL THEN 1 ELSE 0 END) = 1 THEN 'dept'
                WHEN MAX(CASE WHEN rp.dept_id IS NULL AND rp.role_id IS NOT NULL THEN 1 ELSE 0 END) = 1 THEN 'role'
                ELSE 'custom'
            END as permission_type,
            MAX(rp.can_read) as can_read,
            MAX(rp.can_write) as can_write,
            MAX(rp.can_execute) as can_delete
        FROM tb_ai_knowledge k
        <include refid="Permission_Filter"/>
        <include refid="Filter_Clause"/>
        GROUP BY k.id, k.title, k.avatar, k.description, k.content, k.source_type, k.source_id, 
                 k.file_name, k.file_path, k.category, k.tags, k.dify_dataset_id, 
                 k.dify_indexing_technique, k.embedding_model, k.embedding_model_provider,
                 k.rerank_model, k.rerank_model_provider, k.reranking_enable, 
                 k.retrieval_top_k, k.retrieval_score_threshold, k.vector_id, 
                 k.document_count, k.total_chunks, k.status, k.creator, k.creator_dept,
                 k.updater, k.create_time, k.update_time, k.delete_time, k.deleted
        ORDER BY k.create_time DESC
        LIMIT #{pageParam.offset}, #{pageParam.pageSize}
    </select>

    <!-- countKnowledges（统计知识库总数，带权限过滤） -->
    <select id="countKnowledges" resultType="java.lang.Long">
        SELECT COUNT(DISTINCT k.id)
        FROM tb_ai_knowledge k
        <include refid="Permission_Filter"/>
        <include refid="Filter_Clause"/>
    </select>

    <!-- findByDifyDatasetId（根据Dify数据集ID查询知识库） -->
    <select id="findByDifyDatasetId" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM tb_ai_knowledge
        WHERE dify_dataset_id = #{difyDatasetId} AND deleted = 0
        LIMIT 1
    </select>

</mapper>
