package com.gxwebsoft.ai.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.gxwebsoft.ai.config.AuditExcelStyle;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

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

/**
 * Excel导出工具类
 */
@Slf4j
public class ExcelExportTool {

    /**
     * 通用Excel导出方法
     *
     * @param dataList     数据列表
     * @param entityClass  实体类Class
     * @param fileName     文件名（不含扩展名）
     * @param sheetName    工作表名
     * @param title        标题
     * @param response     HttpServletResponse
     */
    public static <T> void exportExcel(List<T> dataList, 
                                     Class<T> entityClass, 
                                     String fileName, 
                                     String sheetName, 
                                     String title, 
                                     HttpServletResponse response) {
        exportExcel(dataList, entityClass, fileName, sheetName, title, response, true);
    }

    /**
     * 通用Excel导出方法（完整参数）
     *
     * @param dataList     数据列表
     * @param entityClass  实体类Class
     * @param fileName     文件名（不含扩展名）
     * @param sheetName    工作表名
     * @param title        标题
     * @param response     HttpServletResponse
     * @param autoHeight   是否自适应行高
     */
    public static <T> void exportExcel(List<T> dataList, 
                                     Class<T> entityClass, 
                                     String fileName, 
                                     String sheetName, 
                                     String title, 
                                     HttpServletResponse response, 
                                     boolean autoHeight) {
        try {
            if (dataList == null || dataList.isEmpty()) {
                throw new RuntimeException("没有可导出的数据");
            }

            log.info("开始导出Excel - 文件: {}, 数据条数: {}", fileName, dataList.size());

            // 设置响应头
            setupResponse(response, fileName);

            // 创建导出参数
            ExportParams exportParams = createExportParams(sheetName, title);

            // 创建Workbook并导出
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, entityClass, dataList);

            // 应用样式
            if (autoHeight) {
                applyAutoStyle(workbook);
            }

            // 写入响应流
            writeToResponse(workbook, response);

            log.info("成功导出Excel文件: {}, 共{}条数据", fileName, dataList.size());

        } catch (Exception e) {
            log.error("导出Excel失败: {}", fileName, e);
            throw new RuntimeException("导出失败: " + e.getMessage());
        }
    }

    /**
     * 设置响应头
     */
    private static void setupResponse(HttpServletResponse response, String fileName) throws Exception {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        String encodedFileName = URLEncoder.encode(fileName + ".xlsx", StandardCharsets.UTF_8.toString());
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
        response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
    }

    /**
     * 创建导出参数
     */
    private static ExportParams createExportParams(String sheetName, String title) {
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName(sheetName);
        exportParams.setTitle(title);
        exportParams.setType(ExcelType.XSSF); // 使用xlsx格式
        exportParams.setStyle(AuditExcelStyle.class);
        return exportParams;
    }

    /**
     * 应用自动样式
     */
    private static void applyAutoStyle(Workbook workbook) {
        Sheet sheet = workbook.getSheetAt(0);
        
        // 设置自适应行高
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                row.setHeight((short) -1); // 设置为自动行高
            }
        }
    }

    /**
     * 写入响应流
     */
    private static void writeToResponse(Workbook workbook, HttpServletResponse response) throws Exception {
        try (OutputStream out = response.getOutputStream()) {
            workbook.write(out);
            out.flush();
        }
    }
}