package com.yida.data.common.core.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.yida.data.common.core.entity.EasyExcelExportBaseDTO;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

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

/**
 * EasyExcel操作工具类
 *
 * @author ZYJ
 * @date 2021/8/24
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class EasyExcelUtil {

    /**
     * EasyExcel导出工具类
     *
     * @param list           需要导出的数据
     * @param clazz          需要转换的类, 需要继承EasyExcelExportBaseDTO
     * @param exportFileName 导出的文件名称. 不需要文件后缀
     * @param excelTypeEnum  导出的Excel文件类型. {@link ExcelTypeEnum}
     * @param response       response返回类
     * @author ZYJ
     * @date 2021/8/24 11:31
     */
    public static <T extends EasyExcelExportBaseDTO> void exportExcelData(
            List<T> list, Class<T> clazz, String exportFileName,
            ExcelTypeEnum excelTypeEnum,
            HttpServletResponse response) {
        try {
            OutputStream outputStream = response.getOutputStream();
            String fileName = new String((exportFileName + "." + excelTypeEnum.getValue()).getBytes(),
                    StandardCharsets.ISO_8859_1);
            // 添加响应头信息
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);

            // 实例化ExcelWriter
            ExcelWriter excelWriter = EasyExcelFactory.write(outputStream)
                    .excelType(excelTypeEnum)
                    .head(clazz)
                    .build();
            // 实例化表单
            WriteSheet writeSheet = EasyExcel.writerSheet("导出数据").build();
            // 输出Excel数据
            excelWriter.write(list, writeSheet);
            excelWriter.finish();
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

}
