package org.dromara.knowledge.data;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.dromara.common.core.exception.ServiceException;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.util.StringJoiner;

/**
 * Excel 文档解析器（支持 .xls 和 .xlsx 格式）
 *
 * @author pengles
 */
@Component
public class ExcelDocumentParser implements DocumentParser {
    @Override
    public String parse(byte[] bytes, String filename) {
        String ext = filename != null && filename.contains(".") ? filename.substring(filename.lastIndexOf('.') + 1).toLowerCase() : "xlsx";
        try (ByteArrayInputStream is = new ByteArrayInputStream(bytes)) {
            StringJoiner joiner = new StringJoiner("\n");
            if ("xls".equals(ext)) {
                HSSFWorkbook wb = new HSSFWorkbook(is);
                for (Sheet sheet : wb) {
                    for (Row row : sheet) {
                        StringJoiner rowJoin = new StringJoiner("\t");
                        for (Cell cell : row) {
                            rowJoin.add(cell.toString());
                        }
                        joiner.add(rowJoin.toString());
                    }
                }
                wb.close();
            } else {
                XSSFWorkbook wb = new XSSFWorkbook(is);
                for (Sheet sheet : wb) {
                    for (Row row : sheet) {
                        StringJoiner rowJoin = new StringJoiner("\t");
                        for (Cell cell : row) {
                            rowJoin.add(cell.toString());
                        }
                        joiner.add(rowJoin.toString());
                    }
                }
                wb.close();
            }
            return joiner.toString();
        } catch (Exception e) {
            throw new ServiceException("Excel解析失败: " + e.getMessage());
        }
    }
}

