package com.njcn.poi.excel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.CharsetUtil;
import com.njcn.web.utils.HttpServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2022年04月01日 10:48
 */
@Slf4j
public class ExcelUtil {

    /**
     * 指定名称、数据下载报表
     *
     * @param fileName 文件名
     */
    public static void exportExcel(String fileName, Class<?> pojoClass, Collection<?> dataSet) {
        HttpServletResponse response = HttpServletUtil.getResponse();
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            fileName = URLEncoder.encode(fileName, CharsetUtil.UTF_8);
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, dataSet);
            workbook.write(outputStream);
        } catch (IOException e) {
            log.error(">>> 导出数据异常：{}", e.getMessage());
        }
    }


    /**
     * @param excel          目标excel
     * @param statisticsType 统计类型
     * @param statisticsName 统计名称
     * @param pojoClass      目标class
     * @param dataSet        数据集合
     */
    public static void exportExcelWithTargetFile(File excel, String statisticsType, String statisticsName, Class<?> pojoClass, Collection<?> dataSet) {
        try (FileOutputStream outputStream = new FileOutputStream(excel)) {
            if (!excel.getParentFile().exists()) {
                excel.getParentFile().mkdirs();
            }
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(statisticsType, statisticsName), pojoClass, dataSet);
            workbook.write(outputStream);
        } catch (IOException e) {
            log.error(">>> 导出数据异常：{}", e.getMessage());
        }
    }

    /**
     * @param excel     目标excel
     * @param pojoClass 目标class
     * @param dataSet   数据集合
     */
    public static void exportExcelWithTargetFile(File excel, Class<?> pojoClass, Collection<?> dataSet) {
        try (FileOutputStream outputStream = new FileOutputStream(excel)) {
            if (!excel.getParentFile().exists()) {
                excel.getParentFile().mkdirs();
            }
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), pojoClass, dataSet);
            workbook.write(outputStream);
        } catch (IOException e) {
            log.error(">>> 导出数据异常：{}", e.getMessage());
        }
    }


}
