package com.railway.common.utils.poi;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.railway.common.constant.Constants;
import com.railway.common.utils.file.FileUploadUtils;
import org.apache.poi.ss.formula.functions.T;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class EasyExcelUtil {

    public String getExcel(Map<String, Object> params, List list,
                          String template, String wordName)  {
        String fileName = encodingFilename(wordName);
        String filePath = FileUploadUtils.getAbsoluteFile(fileName);
        try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(template);
             OutputStream os = new FileOutputStream(filePath)){
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            ExcelWriter excelWriter = EasyExcel.write(os).withTemplate(is)
                    .excelType(ExcelTypeEnum.XLS)
                    .registerConverter(new LocalDateConverter())
                    .build();
            //列表自动添加行
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list,fillConfig, writeSheet);
            excelWriter.fill(params, writeSheet);
            excelWriter.finish();
        } catch (IOException e) {
            return null;
        }
        return filePath;
    }

    public <T> String writeExcel(String fileName, String templateFileName, List<T> list) {
        String filePath = FileUploadUtils.getAbsoluteFile(encodingFilename(fileName));
        try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(templateFileName)) {
            EasyExcel.write(filePath).withTemplate(is).registerConverter(new LocalDateConverter()).sheet().doFill(list);
        } catch (IOException e) {
            return null;
        }
        return filePath;
    }

    /**
     * 编码文件名
     */
    public String encodingFilename(String filename) {
        filename = UUID.randomUUID() + Constants.UNDERLINE + filename;
        return filename;
    }

}
