package com.lingyue.parse.service;

import com.lingyue.parse.enums.FileType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 版面分析服务
 * 识别文档结构（标题、段落、表格、图片等）并提取位置信息
 * 
 * @author lingyue
 * @since 2026-01-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LayoutAnalysisService {
    
    /**
     * 分析文档版面结构
     * 
     * @param filePath 文件路径
     * @param fileType 文件类型
     * @param textContent 已提取的文本内容
     * @return 版面分析结果
     */
    public LayoutAnalysisResult analyzeLayout(String filePath, FileType fileType, String textContent) {
        log.info("开始版面分析: filePath={}, fileType={}", filePath, fileType);
        
        LayoutAnalysisResult result = new LayoutAnalysisResult();
        result.setFilePath(filePath);
        result.setFileType(fileType.name());
        
        List<LayoutElement> elements = new ArrayList<>();
        
        if (fileType == FileType.PDF) {
            elements = analyzePdfLayout(filePath, textContent);
        } else if (fileType == FileType.WORD || fileType == FileType.WORD_OLD) {
            elements = analyzeWordLayout(filePath, textContent);
        } else if (fileType == FileType.EXCEL || fileType == FileType.EXCEL_OLD) {
            elements = analyzeExcelLayout(filePath, textContent);
        } else {
            // 其他文件类型使用简单分析
            elements = analyzeSimpleLayout(textContent);
        }
        
        result.setElements(elements);
        result.setElementCount(elements.size());
        
        log.info("版面分析完成: 识别到 {} 个元素", elements.size());
        return result;
    }
    
    /**
     * 分析PDF版面结构
     */
    private List<LayoutElement> analyzePdfLayout(String filePath, String textContent) {
        List<LayoutElement> elements = new ArrayList<>();
        
        // TODO: 使用PDFBox的版面分析功能
        // 当前实现：基于文本内容进行简单分析
        // 后续可以使用PDFBox的PDFTextStripperByArea或PDFLayoutTextStripper进行更精确的分析
        
        String[] lines = textContent.split("\n");
        int lineIndex = 0;
        
        for (String line : lines) {
            if (line.trim().isEmpty()) {
                continue;
            }
            
            LayoutElement element = new LayoutElement();
            element.setType(detectElementType(line));
            element.setContent(line.trim());
            element.setLineIndex(lineIndex);
            element.setPosition(createPosition("line", lineIndex, 0, line.length()));
            
            elements.add(element);
            lineIndex++;
        }
        
        return elements;
    }
    
    /**
     * 分析Word版面结构
     */
    private List<LayoutElement> analyzeWordLayout(String filePath, String textContent) {
        List<LayoutElement> elements = new ArrayList<>();
        
        // TODO: 使用POI提取Word的结构信息（标题、段落等）
        // 当前实现：基于文本内容进行简单分析
        
        String[] paragraphs = textContent.split("\n\n");
        int paragraphIndex = 0;
        
        for (String paragraph : paragraphs) {
            if (paragraph.trim().isEmpty()) {
                continue;
            }
            
            LayoutElement element = new LayoutElement();
            element.setType(detectElementType(paragraph));
            element.setContent(paragraph.trim());
            element.setParagraphIndex(paragraphIndex);
            element.setPosition(createPosition("paragraph", paragraphIndex, 0, paragraph.length()));
            
            elements.add(element);
            paragraphIndex++;
        }
        
        return elements;
    }
    
    /**
     * 分析Excel版面结构
     */
    private List<LayoutElement> analyzeExcelLayout(String filePath, String textContent) {
        List<LayoutElement> elements = new ArrayList<>();
        
        // Excel主要是表格数据
        String[] lines = textContent.split("\n");
        int lineIndex = 0;
        
        for (String line : lines) {
            if (line.trim().isEmpty() || line.startsWith("===")) {
                // 跳过空行和工作表标题
                continue;
            }
            
            LayoutElement element = new LayoutElement();
            element.setType("table_row");
            element.setContent(line.trim());
            element.setLineIndex(lineIndex);
            element.setPosition(createPosition("row", lineIndex, 0, line.length()));
            
            // 解析表格单元格
            String[] cells = line.split("\t");
            List<Map<String, Object>> cellData = new ArrayList<>();
            for (int i = 0; i < cells.length; i++) {
                Map<String, Object> cell = new HashMap<>();
                cell.put("column", i);
                cell.put("value", cells[i].trim());
                cellData.add(cell);
            }
            Map<String, Object> metadata = new HashMap<>();
            metadata.put("cells", cellData);
            element.setMetadata(metadata);
            
            elements.add(element);
            lineIndex++;
        }
        
        return elements;
    }
    
    /**
     * 简单版面分析（用于图片等）
     */
    private List<LayoutElement> analyzeSimpleLayout(String textContent) {
        List<LayoutElement> elements = new ArrayList<>();
        
        if (textContent == null || textContent.trim().isEmpty()) {
            return elements;
        }
        
        LayoutElement element = new LayoutElement();
        element.setType("text");
        element.setContent(textContent.trim());
        element.setPosition(createPosition("text", 0, 0, textContent.length()));
        
        elements.add(element);
        return elements;
    }
    
    /**
     * 检测元素类型（基于内容特征）
     */
    private String detectElementType(String content) {
        if (content == null || content.trim().isEmpty()) {
            return "empty";
        }
        
        String trimmed = content.trim();
        
        // 检测标题（通常较短，可能是全大写，或包含特定格式）
        if (trimmed.length() < 100 && 
            (trimmed.toUpperCase().equals(trimmed) || 
             trimmed.matches("^[一二三四五六七八九十]+[、.].*") ||
             trimmed.matches("^第[一二三四五六七八九十]+[章节].*"))) {
            return "heading";
        }
        
        // 检测列表项
        if (trimmed.matches("^[•·\\-\\*]\\s+.*") || 
            trimmed.matches("^\\d+[.、]\\s+.*")) {
            return "list_item";
        }
        
        // 检测表格行（包含制表符）
        if (trimmed.contains("\t")) {
            return "table_row";
        }
        
        // 默认段落
        return "paragraph";
    }
    
    /**
     * 创建位置信息
     */
    private Map<String, Object> createPosition(String type, int index, int start, int length) {
        Map<String, Object> position = new HashMap<>();
        position.put("type", type);
        position.put("index", index);
        position.put("start", start);
        position.put("length", length);
        return position;
    }
    
    /**
     * 版面分析结果
     */
    public static class LayoutAnalysisResult {
        private String filePath;
        private String fileType;
        private List<LayoutElement> elements;
        private int elementCount;
        
        // Getters and Setters
        public String getFilePath() {
            return filePath;
        }
        
        public void setFilePath(String filePath) {
            this.filePath = filePath;
        }
        
        public String getFileType() {
            return fileType;
        }
        
        public void setFileType(String fileType) {
            this.fileType = fileType;
        }
        
        public List<LayoutElement> getElements() {
            return elements;
        }
        
        public void setElements(List<LayoutElement> elements) {
            this.elements = elements;
        }
        
        public int getElementCount() {
            return elementCount;
        }
        
        public void setElementCount(int elementCount) {
            this.elementCount = elementCount;
        }
    }
    
    /**
     * 版面元素
     */
    public static class LayoutElement {
        private String type; // heading/paragraph/list_item/table_row/text/image
        private String content;
        private Integer lineIndex;
        private Integer paragraphIndex;
        private Map<String, Object> position; // {type, index, start, length, page, x, y, width, height}
        private Map<String, Object> metadata; // 额外元数据
        
        // Getters and Setters
        public String getType() {
            return type;
        }
        
        public void setType(String type) {
            this.type = type;
        }
        
        public String getContent() {
            return content;
        }
        
        public void setContent(String content) {
            this.content = content;
        }
        
        public Integer getLineIndex() {
            return lineIndex;
        }
        
        public void setLineIndex(Integer lineIndex) {
            this.lineIndex = lineIndex;
        }
        
        public Integer getParagraphIndex() {
            return paragraphIndex;
        }
        
        public void setParagraphIndex(Integer paragraphIndex) {
            this.paragraphIndex = paragraphIndex;
        }
        
        public Map<String, Object> getPosition() {
            return position;
        }
        
        public void setPosition(Map<String, Object> position) {
            this.position = position;
        }
        
        public Map<String, Object> getMetadata() {
            return metadata;
        }
        
        public void setMetadata(Map<String, Object> metadata) {
            this.metadata = metadata;
        }
    }
}
