package cn.com.qmth.examcloud.core.questions.base.excel;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * Created by songyue on 17/7/14.
 */
public final class ImportUtils {

    private static final Logger LOG = LoggerFactory.getLogger(ImportUtils.class);

    public static final String TEMP_FILE_IMP = "fileImport/";

    public static final String TEMP_FILE_EXP = "fileExport/";

    static {
        init();
    }

    /**
     * 初始化文件夹
     */
    public static void init() {
        File temp_file_exp = new File(TEMP_FILE_EXP);
        File temp_file_imp = new File(TEMP_FILE_IMP);
        // 如果输出目标文件夹不存在，则创建
        if (!temp_file_imp.exists()) {
            temp_file_imp.mkdirs();
        }
        if (!temp_file_exp.exists()) {
            temp_file_exp.mkdirs();
        }
    }

    /**
     * 获取上传文件
     *
     * @param file
     * @return
     */
    public static File getUploadFile(MultipartFile file) {
        File tempFile = new File(TEMP_FILE_IMP + file.getOriginalFilename());

        try (OutputStream os = new FileOutputStream(tempFile);
             InputStream is = file.getInputStream();) {
            IOUtils.copyLarge(is, os);
        } catch (FileNotFoundException e) {
            LOG.error(e.getMessage(), e);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }

        return tempFile;
    }

}