package com.crm.rely.backend.util;

import com.crm.rely.backend.core.dto.base.ExportCsvDto;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Author houn
 * @Date 2024/10/21 15:23
 * @PackageName:com.crm.rely.backend.util
 * @ClassName: ToCsvFile
 * @Description: TODO
 */
public class ToCsvFile {

    /**
     * 生成csv文件
     *
     * @param exportCsvDtoList
     * @return
     */
    public static void toCsvFile(String fileName, String[] headArr, List<ExportCsvDto> exportCsvDtoList,
                                 HttpServletResponse response) throws Exception {
        if (exportCsvDtoList != null && exportCsvDtoList.size() > 0) {
            // 表格头
//            String[] headArr = new String[]{"PointId", "X", "Y"};

            setResponse(fileName, response);
            response.setCharacterEncoding("UTF-8");
            OutputStream outputStream = response.getOutputStream();
            Writer out = new OutputStreamWriter(outputStream, "UTF-8");
            try {

                out.write(String.join(",", headArr) + "\n");

                // 写入文件内容
                for (ExportCsvDto exportCsvDto : exportCsvDtoList) {
                    out.write(exportCsvDto.toRow());
                }
                out.flush();
                outputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    out.close();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void setResponse(String fileName, HttpServletResponse response) throws Exception {
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/force-download");


    }
}
