package com.lingyue.document.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lingyue.document.entity.DocumentElement;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 文档元素 Repository
 * 
 * @author lingyue
 * @since 2026-01-21
 */
@Mapper
public interface DocumentElementRepository extends BaseMapper<DocumentElement> {
    
    /**
     * 根据文档ID查询所有元素（按顺序）
     */
    @Select("SELECT * FROM document_elements WHERE document_id = #{documentId} ORDER BY element_index")
    List<DocumentElement> findByDocumentId(@Param("documentId") String documentId);
    
    /**
     * 根据文档ID和类型查询元素
     */
    @Select("SELECT * FROM document_elements WHERE document_id = #{documentId} AND element_type = #{elementType} ORDER BY element_index")
    List<DocumentElement> findByDocumentIdAndType(@Param("documentId") String documentId, 
                                                   @Param("elementType") String elementType);
    
    /**
     * 查询文档中的所有图片
     */
    @Select("SELECT * FROM document_elements WHERE document_id = #{documentId} AND element_type = 'image' ORDER BY element_index")
    List<DocumentElement> findImagesByDocumentId(@Param("documentId") String documentId);
    
    /**
     * 查询文档中的所有表格
     */
    @Select("SELECT * FROM document_elements WHERE document_id = #{documentId} AND element_type = 'table' ORDER BY element_index")
    List<DocumentElement> findTablesByDocumentId(@Param("documentId") String documentId);
    
    /**
     * 删除文档的所有元素
     */
    @Delete("DELETE FROM document_elements WHERE document_id = #{documentId}")
    int deleteByDocumentId(@Param("documentId") String documentId);
    
    /**
     * 统计文档元素数量
     */
    @Select("SELECT COUNT(*) FROM document_elements WHERE document_id = #{documentId}")
    int countByDocumentId(@Param("documentId") String documentId);
    
    /**
     * 按类型统计
     */
    @Select("SELECT element_type, COUNT(*) as count FROM document_elements WHERE document_id = #{documentId} GROUP BY element_type")
    List<java.util.Map<String, Object>> countByDocumentIdGroupByType(@Param("documentId") String documentId);
}
