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

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.cf.imes.module.executor.util.fileConversion.admin.files.excel.OrderPlateImportExcelVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ResourceUtils;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;



/**
 * excel 文件写入
 */
@Slf4j
public class ExcelWriterUtil {

    // 写excel
    public static void write(HttpServletResponse response,
                             Map<String, String> orderMap,
                             List<OrderPlateImportExcelVO> list,
                             String filePathErr) {
        ServletOutputStream outputStream = null;
        ExcelWriter excelWriter = null;
        //输入流
        try (InputStream inputStream = ResourceUtils.getURL(filePathErr).openStream()){
            outputStream = response.getOutputStream();


            //设置输出流和模板信息
            excelWriter = EasyExcelFactory.write(outputStream).withTemplate(inputStream).build();
            WriteSheet writeSheet = EasyExcelFactory.writerSheet().build();

            //开启自动换行，自动换行表示每次写入一条list数据是都会重新生成一行空行,此选项默认是关闭的,需要提前设置为true
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();

            excelWriter.fill(orderMap, writeSheet);

            //列表
            excelWriter.fill(list, fillConfig, writeSheet);

            response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        } catch (IOException e) {
            log.error("文件【{}】写入异常", filePathErr, e);
        } finally {
            //关流
            IOUtils.closeQuietly(excelWriter);
            IOUtils.closeQuietly(outputStream);
        }
    }



}
