package com.cf.imes.module.executor.util.file;

import com.alibaba.excel.EasyExcelFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件读取
 */
@Slf4j
public final class ExcelReadUtil{

    private String value;
    private boolean flag;

    public <T> List<T> read(MultipartFile file, Class<T> head, ExcelListener<T> listener) throws IOException {
        value = "";
        Long fileSize = 1024 * 1024 * 10L; // 10 MB
        flag = FileHelperUtil.checkFile(file, fileSize);

        if (flag) {
            EasyExcelFactory.read(file.getInputStream(), head, listener)
                    .autoCloseStream(true)  // 不要自动关闭，交给 Servlet 自己处理
                    .headRowNumber(1).sheet(0).doRead();
            //获取读取的数据
            List<T> list = listener.getDates();
            flag = listener.getFlag();
            if (!flag) {
                value = "导入数据有误";
            }
            return list;
        }
        return new ArrayList<>();
    }

    public String getValue() {
        return value;
    }

    public boolean getFlag() {
        return flag;
    }

}
