package com.njcn.gather.system.log.util;


import cn.afterturn.easypoi.csv.CsvExportUtil;
import cn.afterturn.easypoi.csv.entity.CsvExportParams;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.njcn.web.utils.HttpServletUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author caozehui
 * @data 2024-12-2
 */
@Slf4j
public class CSVUtil {

    /**
     * CSV文件列分隔符
     */
    private static final String CSV_COLUMN_SEPARATOR = ",";

    /**
     * CSV文件行分隔符
     */
    private static final String CSV_ROW_SEPARATOR = System.lineSeparator();

    /**
     * 导出CSV文件
     *
     * @param fileName 文件名
     * @param titles   表头
     * @param keys     字段名
     * @param dataList 数据集
     */
    public static void export(String fileName, String[] titles, String[] keys, List<Map<String, Object>> dataList) {
        // 保证线程安全
        StringBuffer buf = new StringBuffer();

        // 组装表头
        for (String title : titles) {
            buf.append(title).append(CSV_COLUMN_SEPARATOR);
        }
        buf.append(CSV_ROW_SEPARATOR);
        // 组装数据
        if (CollectionUtils.isNotEmpty(dataList)) {
            for (Map<String, Object> map : dataList) {
                for (String key : keys) {
                    if (ObjectUtil.isEmpty(map.get(key))) {
                        buf.append("").append(CSV_COLUMN_SEPARATOR);
                    } else {
                        // 如果数据内容中包含逗号，则进行使用!替换
                        buf.append(map.get(key).toString().replaceAll(",", "!")).append(CSV_COLUMN_SEPARATOR);
                    }
                }
                buf.deleteCharAt(buf.length() - 1).append(CSV_ROW_SEPARATOR);
            }
        }

        HttpServletResponse response = HttpServletUtil.getResponse();

        try {
            ServletOutputStream os = response.getOutputStream();
            Throwable var1 = null;

            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.reset();
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                response.setContentType("application/octet-stream;charset=UTF-8");
                // 写出响应
                os.write(buf.toString().getBytes("UTF-8"));
                os.flush();
            } catch (Throwable var2) {
                var1 = var2;
                throw var2;
            } finally {
                if (os != null) {
                    if (var1 != null) {
                        try {
                            os.close();
                        } catch (Throwable var3) {
                            var1.addSuppressed(var3);
                        }
                    } else {
                        os.close();
                    }
                }
            }
        } catch (IOException var4) {
            IOException e = var4;
            log.error(">>> 导出数据异常：{}", e.getMessage());
        }
    }


    public static void exportCsv(String fileName, CsvExportParams params, Class<?> pojoClass, Collection<?> dataSet) {
        HttpServletResponse response = HttpServletUtil.getResponse();
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");

            CsvExportUtil.exportCsv(params, pojoClass, dataSet, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error(">>> 导出数据异常：{}", e.getMessage());
        }
    }
}
