package com.sckw.core;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Author: donglang
 * Time: 2025-11-05
 * Des: 表格工具类
 * Version: 1.0
 */

public class ExcelUtils {


    /**
     * 下载Excel模板
     * @param fileName 文件名
     * @param clazz 模板对应的实体类
     * @param response HttpServletResponse对象
     * @param <T> 实体类泛型
     * @throws Exception 异常
     */
    public static <T> void exportTemplate(HttpServletResponse response, String fileName, Class<T> clazz, List<T> dataList) throws Exception {
        // 设置响应内容类型
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        // 设置文件名
        String name = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xlsx");
        // 解决跨域问题
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");


        // 创建表头样式
        WriteCellStyle headStyle  = new WriteCellStyle();
        // 设置表头居中对齐
        headStyle .setHorizontalAlignment(HorizontalAlignment.CENTER);

        // 设置表头字体
        WriteFont headFont  = new WriteFont();
        headFont .setFontHeightInPoints((short) 12);
        headFont .setBold(true);
        headStyle .setWriteFont(headFont);

        // 创建内容样式
        WriteCellStyle contentStyle = new WriteCellStyle();
        // 设置内容居中对齐
        contentStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);


        // 初始化表格样式策略
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headStyle, contentStyle);

        // 使用EasyExcel导出
        EasyExcel.write(response.getOutputStream(), clazz)
                .excelType(ExcelTypeEnum.XLSX)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .registerWriteHandler(horizontalCellStyleStrategy)
                .sheet("模板")
                .doWrite(new ArrayList<>()); // 写入空列表，只生成表头
    }
}
