package cn.novalon.gym.manage.sys.core.util;

import cn.novalon.gym.manage.sys.core.domain.OperationLog;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * Excel导出工具类
 * 
 * @author 张翔
 * @date 2026-04-03
 */
public class ExcelExportUtil {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 导出操作日志到Excel
     * 
     * @param logs 操作日志列表
     * @return Excel文件字节数组
     * @throws IOException IO异常
     */
    public static byte[] exportOperationLogs(List<OperationLog> logs) throws IOException {
        try (Workbook workbook = new XSSFWorkbook();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            Sheet sheet = workbook.createSheet("操作日志");

            CellStyle headerStyle = createHeaderStyle(workbook);
            CellStyle dateStyle = createDateStyle(workbook);

            Row headerRow = sheet.createRow(0);
            String[] headers = {"ID", "操作人", "操作模块", "请求方法", "请求参数", "执行结果", 
                    "IP地址", "耗时(ms)", "状态", "错误信息", "操作时间"};

            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.setColumnWidth(i, 20 * 256);
            }

            int rowNum = 1;
            for (OperationLog log : logs) {
                Row row = sheet.createRow(rowNum++);

                row.createCell(0).setCellValue(log.getId() != null ? log.getId() : 0);
                row.createCell(1).setCellValue(log.getUsername() != null ? log.getUsername() : "");
                row.createCell(2).setCellValue(log.getOperation() != null ? log.getOperation() : "");
                row.createCell(3).setCellValue(log.getMethod() != null ? log.getMethod() : "");
                row.createCell(4).setCellValue(truncateText(log.getParams(), 1000));
                row.createCell(5).setCellValue(truncateText(log.getResult(), 1000));
                row.createCell(6).setCellValue(log.getIp() != null ? log.getIp() : "");
                row.createCell(7).setCellValue(log.getDuration() != null ? log.getDuration() : 0);
                row.createCell(8).setCellValue("0".equals(log.getStatus()) ? "成功" : "失败");
                row.createCell(9).setCellValue(log.getErrorMsg() != null ? log.getErrorMsg() : "");

                Cell dateCell = row.createCell(10);
                if (log.getCreatedAt() != null) {
                    dateCell.setCellValue(log.getCreatedAt().format(DATE_TIME_FORMATTER));
                    dateCell.setCellStyle(dateStyle);
                }
            }

            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }

    private static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 12);
        style.setFont(font);

        return style;
    }

    private static CellStyle createDateStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    private static String truncateText(String text, int maxLength) {
        if (text == null) {
            return "";
        }
        if (text.length() <= maxLength) {
            return text;
        }
        return text.substring(0, maxLength) + "...";
    }
}
