package com.lingyue.document.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingyue.document.entity.DocumentEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 文档实体 Repository
 * 
 * @author lingyue
 * @since 2026-01-21
 */
@Mapper
public interface DocumentEntityRepository extends BaseMapper<DocumentEntity> {
    
    /**
     * 根据文档ID查询所有实体
     */
    @Select("SELECT * FROM document_entities WHERE document_id = #{documentId} ORDER BY global_char_start")
    List<DocumentEntity> findByDocumentId(@Param("documentId") String documentId);
    
    /**
     * 根据块ID查询实体
     */
    @Select("SELECT * FROM document_entities WHERE block_id = #{blockId} ORDER BY block_char_start")
    List<DocumentEntity> findByBlockId(@Param("blockId") String blockId);
    
    /**
     * 根据文档ID和实体类型查询
     */
    @Select("SELECT * FROM document_entities WHERE document_id = #{documentId} AND entity_type = #{entityType} ORDER BY global_char_start")
    List<DocumentEntity> findByDocumentIdAndType(@Param("documentId") String documentId, 
                                                  @Param("entityType") String entityType);
    
    /**
     * 根据实体名称模糊查询
     */
    @Select("SELECT * FROM document_entities WHERE document_id = #{documentId} AND name LIKE CONCAT('%', #{keyword}, '%')")
    List<DocumentEntity> searchByName(@Param("documentId") String documentId, 
                                       @Param("keyword") String keyword);
    
    /**
     * 确认实体
     */
    @Update("UPDATE document_entities SET confirmed = true, update_time = CURRENT_TIMESTAMP WHERE id = #{entityId}")
    int confirmEntity(@Param("entityId") String entityId);
    
    /**
     * 批量确认实体
     */
    @Update("<script>UPDATE document_entities SET confirmed = true, update_time = CURRENT_TIMESTAMP " +
            "WHERE id IN <foreach collection='entityIds' item='id' open='(' separator=',' close=')'>#{id}</foreach></script>")
    int batchConfirmEntities(@Param("entityIds") List<String> entityIds);
    
    /**
     * 删除文档的所有实体
     */
    @Delete("DELETE FROM document_entities WHERE document_id = #{documentId}")
    int deleteByDocumentId(@Param("documentId") String documentId);
    
    /**
     * 删除块的所有实体
     */
    @Delete("DELETE FROM document_entities WHERE block_id = #{blockId}")
    int deleteByBlockId(@Param("blockId") String blockId);
    
    /**
     * 统计文档实体数量（按类型分组）
     */
    @Select("SELECT entity_type, COUNT(*) as count FROM document_entities " +
            "WHERE document_id = #{documentId} GROUP BY entity_type")
    List<java.util.Map<String, Object>> countByType(@Param("documentId") String documentId);
}
