package com.jeequan.jeepay.core.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvUtil;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 导出EXCEL util
 *
 * @author xiaoyu
 *
 * @date 2022/1/12 18:02
 */
public class ExcelUtil {


    /**
     * excel 导出
     *
     * @param list         数据列表
     * @param pojoClass    pojo类型
     * @param fileName     导出时的excel名称
     * @param response
     * @param exportParams 导出参数（标题、sheet名称、是否创建表头，表格类型）
     */
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) throws IOException {
        //把数据添加到excel表格中
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    /**
     * excel 导出
     *
     * @param list      数据列表
     * @param title     表格内数据标题
     * @param sheetName sheet名称
     * @param pojoClass pojo类型
     * @param fileName  导出时的excel名称
     * @param response
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) throws IOException {
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF));
    }

    /**
     * excel下载
     *
     * @param fileName 下载时的文件名称
     * @param response
     * @param workbook excel数据
     */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }



    /**
     * 功能描述: 通过inputStream解压Zip 并读取csv文件
     *
     * @param inputStream
     * @param zipFileNameCharset
     * @param inputStreamReaderCharset
     * @Return: csv集合
     * @Author: terrfly
     * @Date: 2022/10/27 10:04
     */
    public static List<MutablePair<ZipEntry, CsvData>> readCsvDataByZipInputStream(InputStream inputStream, Charset zipFileNameCharset, Charset inputStreamReaderCharset) throws IOException {

        List<MutablePair<ZipEntry, CsvData>> result = new ArrayList<>();

        ZipInputStream zipInputStream = new ZipInputStream(inputStream, zipFileNameCharset);
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        while (zipEntry != null) {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            IoUtil.copy(zipInputStream, byteArrayOutputStream);

            CsvData csvData = CsvUtil.getReader(new InputStreamReader(IoUtil.toStream(byteArrayOutputStream), inputStreamReaderCharset)).read();
            result.add(MutablePair.of(zipEntry, csvData));
            zipEntry = zipInputStream.getNextEntry();
        }

        return result;
    }

    /**
     * 读取csv文件内容
     * @param outputStream
     * @param inputStreamReaderCharset
     * @return
     */
    public static CsvData readCsvData(ByteArrayOutputStream outputStream, Charset inputStreamReaderCharset) {
        CsvData csvData = CsvUtil.getReader(new InputStreamReader(IoUtil.toStream(outputStream), inputStreamReaderCharset)).read();
        return csvData;
    }
}
