package com.zcloud.accident.util;

import com.alibaba.excel.EasyExcel;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * Excel工具类
 */
public class ExcelUtils {

    /**
     * 导出Excel文件
     * @param response HttpServletResponse
     * @param clazz 数据类型
     * @param fileName 文件名
     * @param arrayList 数据列表
     * @param <T> 泛型
     * @throws IOException IOException
     */
    public static <T> void exportExcel(HttpServletResponse response, Class<T> clazz, String fileName, List<T> arrayList) throws IOException {
        setupExcelResponse(response, fileName);
        EasyExcel.write(response.getOutputStream(), clazz).sheet(fileName).doWrite(() -> {
            return arrayList;
        });
    }

    /**
     * 设置Excel响应头
     * @param response HttpServletResponse
     * @param fileName 文件名
     * @throws IOException IOException
     */
    private static void setupExcelResponse(HttpServletResponse response, String fileName) throws IOException {
        // 设置响应头
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        // 文件名编码，防止中文乱码
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replaceAll("\\+", "%");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName + ".xlsx");
    }
}