package org.dromara.knowledge.data;

import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.dromara.common.core.exception.ServiceException;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;

/**
 * Word 文档解析器（支持 .doc 和 .docx 格式）
 *
 * @author pengles
 */
@Component
public class WordDocumentParser implements DocumentParser {
    @Override
    public String parse(byte[] bytes, String filename) {
        String ext = filename != null && filename.contains(".") ? filename.substring(filename.lastIndexOf('.') + 1).toLowerCase() : "docx";
        try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            if ("doc".equals(ext)) {
                WordExtractor extractor = new WordExtractor(is);
                return extractor.getText();
            } else {
                XWPFDocument docx = new XWPFDocument(is);
                XWPFWordExtractor extractor = new XWPFWordExtractor(docx);
                return extractor.getText();
            }
        } catch (Exception e) {
            throw new org.dromara.common.core.exception.ServiceException("Word解析失败: " + e.getMessage());
        }
    }
}

