package com.yeejoin.precontrol.common.utils;

/**
 * 文档中图片命名存储处理
 *
 * @author nihuanshan
 */

import org.apache.poi.util.IOUtils;
import org.apache.poi.xwpf.converter.core.IImageExtractor;

import java.io.*;

public class MyImageExtractor implements IImageExtractor {

    private final File baseDir;

    // 图片名前缀
    private String suffix;

    public MyImageExtractor(File baseDir) {
        this.baseDir = baseDir;
    }

    public MyImageExtractor(File baseDir, String suffix) {
        this.baseDir = baseDir;
        this.suffix = suffix;
    }

    @Override
    public void extract(String imagePath, byte[] imageData) throws IOException {
        System.out.println("imagepath:" + imagePath);
        String s1 = imagePath.substring(0, imagePath.lastIndexOf("/") + 1);
        String s2 = imagePath.substring(1 + imagePath.lastIndexOf("/"));
        String pre = null;
        if (this.suffix != null) {
            pre = this.suffix;
        } else {
            String temp = System.currentTimeMillis() + "_" + (System.nanoTime() % 100000) + "_";
            pre = temp;
        }
        FilePrefix.setFilePrefix(pre);
        imagePath = s1 + pre + s2;
        File imageFile = new File(baseDir, imagePath);
        imageFile.getParentFile().mkdirs();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new ByteArrayInputStream(imageData);
            out = new FileOutputStream(imageFile);
            IOUtils.copy(in, out);
        } finally {
            if (in != null) {
                IOUtils.closeQuietly(in);
            }
            if (out != null) {
                IOUtils.closeQuietly(out);
            }
        }
    }

}
