package com.hdkj.lt.utils.poi;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import cn.afterturn.easypoi.handler.inter.IExcelDictHandler;
import cn.hutool.core.net.URLEncoder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.google.common.base.Charsets;
import com.hdkj.easypoix.starter.annotation.ExcelFileAttr;
import com.hdkj.easypoix.starter.service.impl.DefaultExcelDictHandler;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

/**
 * @Description
 * @Author wucx
 * @Date 2024/7/15 16:08
 * @Version 1.0
 */
public class EasyPoiUtils {

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, boolean isCreateHeader, IExcelDataHandler dataHandler, HttpServletResponse response) {
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        exportParams.setDictHandler((IExcelDictHandler) SpringUtil.getBean(DefaultExcelDictHandler.class));
        exportParams.setType(ExcelType.XSSF);
        if ((Boolean) Optional.ofNullable(dataHandler).map(IExcelDataHandler::getNeedHandlerFields).map(ObjectUtil::isNotNull).orElse(false)) {
            exportParams.setDataHandler(dataHandler);
        }

        defaultExport(list, pojoClass, fileName, response, exportParams);
        ((DefaultExcelDictHandler)SpringUtil.getBean(DefaultExcelDictHandler.class)).removeMap();
    }

    public static void exportExcel(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        exportExcel(list, (String)null, pojoClass, fileName, response);
    }

    public static void exportExcel(List<?> list, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        exportExcel(list, (String)null, sheetName, pojoClass, fileName, response);
    }

    public static void exportExcel(List<?> list, HttpServletResponse response) {
        Class<?> cls = list.get(0).getClass();
        ExcelFileAttr fileAttr = (ExcelFileAttr)cls.getDeclaredAnnotation(ExcelFileAttr.class);
        exportExcel(list, (String)null, fileAttr.sheetName(), cls, fileAttr.fileName(), response);
    }

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, HttpServletResponse response) {
        exportExcel(list, title, sheetName, pojoClass, fileName, true, (IExcelDataHandler)null, response);
    }

    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass, String fileName, IExcelDataHandler dataHandler, HttpServletResponse response) {
        exportExcel(list, title, sheetName, pojoClass, fileName, true, dataHandler, response);
    }

    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list);
        downLoadExcel(fileName, response, workbook);
    }

    public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            // 处理文件名中包含的非法字符（转成全角的字符串）
            String dealFileName = fileName.replace("\\", "＼")
                    .replace("/", "／").replace(":", "：")
                    .replace("*", "＊").replace("?", "？")
                    .replace("\"", "＂").replace("|", "｜")
                    .replace("<", "＜").replace(">", "＞");
            response.setHeader("content-Type", "application/octet-stream");
            String name = URLEncoder.ALL.encode(dealFileName, Charsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment;filename=" + name);
            workbook.write(response.getOutputStream());
        } catch (Exception var4) {
            throw new RuntimeException(var4);
        }
    }
}
