package com.xiaoniu.subsystem.file.utils;

import com.xiaoniu.subsystem.system.utils.MysqlDataBackupUtil;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.io.*;
import java.util.List;

/**
 * @packageName: com.xiaoniu.subsystem.file.utils
 * @className: WordTableReader.java
 * @author: 孙松涛
 * @date: 2025-01-15 16:08
 * @version:
 */
public class WordTableReader {
    public List<XWPFTable> readTables(String filePath) throws IOException {
        FileInputStream fileInputStream = new FileInputStream(filePath);
        XWPFDocument document = new XWPFDocument(fileInputStream);
        List<XWPFTable> tables = document.getTables();
        document.close();
        return tables;
    }

    public List<XWPFTable> readTables(InputStream inputStream) throws IOException {
        // 创建临时文件
        String name = System.currentTimeMillis()+ ".docx";
        File tempFile = MysqlDataBackupUtil.createFile(MysqlDataBackupUtil.MysqlPath,name);
        // 将InputStream写入临时文件
        try (InputStream input = inputStream;
             OutputStream output = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
        }
        // 创建FileInputStream对象读取临时文件
        FileInputStream fileInputStream = new FileInputStream(tempFile.getPath());
        XWPFDocument document = new XWPFDocument(fileInputStream);
        List<XWPFTable> tables = document.getTables();
        document.close();
        MysqlDataBackupUtil.deleteFiles(MysqlDataBackupUtil.MysqlPath + name);
        return tables;
    }

}
