package org.wcs.plugin.excel;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * easypoi导出excel
 */
@Component
public class ExcelPoi {

    /**
     * 导出excel
     *
     * @param fileName 文件名
     * @param response 响应
     * @param list     数据
     * @param clazz    数据类型
     * @param <T>      数据类型
     * @throws IOException IOException
     */
    public <T> void doWriteExcel(String fileName, HttpServletResponse response, List<T> list, Class<T> clazz) throws IOException {
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName("sheet1");
        exportParams.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
        setResponseHeaderOfExcel(fileName, response);
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    private void setResponseHeaderOfExcel(String fileDesc, HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(fileDesc, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }

    /**
     * 读取excel
     *
     * @param file 文件
     * @param clazz 数据类型
     * @param <T> 数据类型
     * @return 数据
     * @throws Exception Exception
     */
    public <T> List<T> doReadExcelOnlyHeader(MultipartFile file, Class<T> clazz) throws Exception {
        ImportParams importParams = new ImportParams();
        importParams.setHeadRows(1);
        return ExcelImportUtil.importExcel(file.getInputStream(), clazz, importParams);
    }



}
