package com.example.service;



import com.example.dto.SearchResultDTO;

import com.example.entity.Attachment;

import com.example.entity.Note;

import com.example.repository.AttachmentRepository;

import com.example.repository.NoteRepository;

import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;



import java.util.ArrayList;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

import java.util.stream.Collectors;



/**

 * 搜索服务层

 */

@Service

@RequiredArgsConstructor

@Slf4j

public class SearchService {

    

    private final NoteRepository noteRepository;

    private final AttachmentRepository attachmentRepository;

    

    /**

     * 全局搜索:搜索笔记标题、内容和附件的OCR文本

     * @param keyword 关键词

     * @return 搜索结果列表

     */

    @Transactional(readOnly = true)

    public List<SearchResultDTO> globalSearch(String keyword) {

        if (keyword == null || keyword.trim().isEmpty()) {

            log.warn("搜索关键词为空,返回空列表");

            return new ArrayList<>();

        }

        

        String searchKeyword = keyword.trim();

        log.info("开始全局搜索,关键词: {}", searchKeyword);

        

        Set<Long> processedNoteIds = new HashSet<>();

        List<SearchResultDTO> results = new ArrayList<>();

        

        // 1. 搜索笔记标题和内容(使用JPA查询)

        List<Note> notesByTitleOrContent = noteRepository.searchByTitleOrContent(searchKeyword);

        

        for (Note note : notesByTitleOrContent) {

            if (note == null) continue;

            

            boolean matchedInTitle = note.getTitle() != null && note.getTitle().contains(searchKeyword);

            boolean matchedInContent = note.getContent() != null && note.getContent().contains(searchKeyword);

            

            if (!processedNoteIds.contains(note.getId())) {

                String matchType;

                String highlight;

                

                if (matchedInTitle && matchedInContent) {

                    matchType = "title,content";

                    highlight = extractHighlight(note.getContent(), searchKeyword);

                } else if (matchedInTitle) {

                    matchType = "title";

                    highlight = extractHighlight(note.getTitle(), searchKeyword);

                } else {

                    matchType = "content";

                    highlight = extractHighlight(note.getContent(), searchKeyword);

                }

                

                SearchResultDTO dto = createSearchResultDTO(note, matchType, highlight);

                results.add(dto);

                processedNoteIds.add(note.getId());

            }

        }

        

        // 2. 搜索附件的OCR内容

        List<Attachment> attachments = attachmentRepository.searchByOcrContent(searchKeyword);

        

        for (Attachment attachment : attachments) {

            Long noteId = attachment.getNoteId();

            Note note = noteRepository.findById(noteId).orElse(null);

            

            if (note != null && !processedNoteIds.contains(noteId)) {

                SearchResultDTO dto = createSearchResultDTO(note, "attachment",

                        extractHighlight(attachment.getOcrContent(), searchKeyword));

                results.add(dto);

                processedNoteIds.add(noteId);

            } else if (note != null) {

                // 如果笔记已经在其他匹配中,更新匹配类型

                results.stream()

                        .filter(r -> r.getNoteId().equals(noteId))

                        .forEach(r -> {

                            String matchType = r.getMatchType();

                            if (!matchType.contains("attachment")) {

                                r.setMatchType(matchType + ",attachment");

                            }

                        });

            }

        }

        

        log.info("搜索完成,找到 {} 条结果", results.size());

        return results;

    }

    

    /**

     * 创建搜索结果DTO

     */

    private SearchResultDTO createSearchResultDTO(Note note, String matchType, String highlight) {

        if (note == null) {

            return null;

        }

        

        SearchResultDTO dto = new SearchResultDTO();

        dto.setNoteId(note.getId());

        dto.setNoteTitle(note.getTitle());

        dto.setNoteContent(truncateContent(note.getContent(), 200));

        dto.setNotebookId(note.getNotebookId());

        dto.setCreatedAt(note.getCreatedAt());

        dto.setUpdatedAt(note.getUpdatedAt());

        dto.setMatchType(matchType);

        dto.setHighlight(highlight);

        

        // 可以在这里查询笔记本名称,但为了性能考虑,暂时不查询

        // 如果需要,可以通过关联查询获取

        

        return dto;

    }

    

    /**

     * 提取高亮文本(包含关键词的片段)

     */

    private String extractHighlight(String text, String keyword) {

        if (text == null || keyword == null) {

            return "";

        }

        

        int index = text.indexOf(keyword);

        if (index == -1) {

            return truncateContent(text, 100);

        }

        

        int start = Math.max(0, index - 50);

        int end = Math.min(text.length(), index + keyword.length() + 50);

        String highlight = text.substring(start, end);

        

        // 替换关键词为高亮标记(前端可以进一步处理)

        highlight = highlight.replace(keyword, "【" + keyword + "】");

        

        return highlight;

    }

    

    /**

     * 截断内容

     */

    private String truncateContent(String content, int maxLength) {

        if (content == null) {

            return "";

        }

        if (content.length() <= maxLength) {

            return content;

        }

        return content.substring(0, maxLength) + "...";

    }

}