package com.cf.imes.module.manage.service.plate;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.cf.imes.module.manage.controller.admin.plate.vo.plate.PlateImportExcelVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
public class PlateExcelUtil {

    private String value;

    private PlateExcelListener<PlateImportExcelVO> excelListener = new PlateExcelListener<>();

    public List<PlateImportExcelVO> read(MultipartFile file, Class<PlateImportExcelVO> head) throws IOException {

        if (file.isEmpty()) {
            value = "文件为空";
            throw new IOException("文件为空");
        } else if (!(file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xls"))) {
            value = "文件格式不正确";
            throw new IOException("文件格式不正确");
        } else if (file.getSize() > 1024 * 1024 * 10) {
            value = "文件大小超过 10M";
            throw new IOException("文件大小超过 10M");
        } else if (file.getSize() == 0) {
            value = "文件大小为 0";
            throw new IOException("文件大小为 0");
        } else {
            EasyExcel.read(file.getInputStream(), PlateImportExcelVO.class, excelListener)
                    .autoCloseStream(true)  // 不要自动关闭，交给 Servlet 自己处理
                    .headRowNumber(1).sheet(0).doRead();
            //获取读取的数据
            List<PlateImportExcelVO> list = excelListener.getDatas();

            if (excelListener.getValueMap().size() > 0)
                excelListener.getValueMap().forEach((k, v) -> {
                    list.get(k - 1).setResult(v);
                });
            return list;
        }
    }

    public boolean getFlag() {
        return excelListener.getFlag();
    }

    public void clear() {
        excelListener.getDatas().clear();
    }

    public Map<Integer, String> getValueMap() {
        return excelListener.getValueMap();
    }
}
