package com.hotent.util.wordexcelutils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * Excel处理工具类 - 增强版
 */
public class ExcelProcessor {

    /**
     * 在Excel中替换占位符文本并插入图片
     * @param templatePath 模板文件路径
     * @param outputPath 输出文件路径
     * @param textReplacements 文本替换映射
     * @param imageMappings 图片位置映射（key: 单元格位置如"A1", value: 图片路径）
     */
    public static void processExcelWithPlaceholders(String templatePath, String outputPath,
                                                    Map<String, String> textReplacements,
                                                    Map<String, String> imageMappings) {
        try (FileInputStream fis = new FileInputStream(templatePath);
             Workbook workbook = createWorkbook(fis, templatePath);
             FileOutputStream fos = new FileOutputStream(outputPath)) {

            // 处理所有工作表
            for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                Sheet sheet = workbook.getSheetAt(i);
                replaceTextInSheet(sheet, textReplacements);

                // 插入图片到指定位置
                for (Map.Entry<String, String> entry : imageMappings.entrySet()) {
                    String cellReference = entry.getKey();
                    String imagePath = entry.getValue();

                    // 解析单元格位置
                    CellAddress address = new CellAddress(cellReference);
                    int rowNum = address.getRow();
                    int colNum = address.getColumn();

                    // 获取或创建行和单元格
                    Row row = sheet.getRow(rowNum);
                    if (row == null) {
                        row = sheet.createRow(rowNum);
                    }

                    Cell cell = row.getCell(colNum);
                    if (cell == null) {
                        cell = row.createCell(colNum);
                    }

                    // 插入图片
                    insertImageToCell(workbook, sheet, cell, imagePath);
                }
            }

            workbook.write(fos);
        } catch (IOException e) {
            throw new RuntimeException("处理Excel文件时出错", e);
        }
    }

    /**
     * 替换工作表中的文本占位符
     */
    private static void replaceTextInSheet(Sheet sheet, Map<String, String> textReplacements) {
        for (Row row : sheet) {
            for (Cell cell : row) {
                if (cell.getCellType() == CellType.STRING) {
                    String cellValue = cell.getStringCellValue();
                    if (cellValue != null && !cellValue.isEmpty()) {
                        String newValue = replacePlaceholders(cellValue, textReplacements);
                        if (!newValue.equals(cellValue)) {
                            cell.setCellValue(newValue);
                        }
                    }
                }
            }
        }
    }

    /**
     * 替换字符串中的占位符
     */
    private static String replacePlaceholders(String original, Map<String, String> replacements) {
        String result = original;
        for (Map.Entry<String, String> entry : replacements.entrySet()) {
            result = result.replace(entry.getKey(), entry.getValue());
        }
        return result;
    }

    /**
     * 创建Workbook实例
     */
    private static Workbook createWorkbook(FileInputStream fis, String filePath) throws IOException {
        if (filePath.toLowerCase().endsWith(".xlsx")) {
            return new XSSFWorkbook(fis);
        } else if (filePath.toLowerCase().endsWith(".xls")) {
            return new HSSFWorkbook(fis);
        } else {
            throw new IllegalArgumentException("不支持的文件格式");
        }
    }

    /**
     * 在指定单元格插入图片
     */
    private static void insertImageToCell(Workbook workbook, Sheet sheet, Cell cell, String imagePath) {
        try (FileInputStream imageStream = new FileInputStream(imagePath)) {
            byte[] imageBytes = IOUtils.toByteArray(imageStream);

            // 创建图片数据
            int pictureIdx = workbook.addPicture(imageBytes, getPictureType(imagePath));

            // 创建绘图对象
            CreationHelper helper = workbook.getCreationHelper();
            Drawing<?> drawing = sheet.createDrawingPatriarch();

            // 设置图片位置
            ClientAnchor anchor = helper.createClientAnchor();
            anchor.setCol1(cell.getColumnIndex());
            anchor.setRow1(cell.getRowIndex());
            anchor.setCol2(cell.getColumnIndex() + 1);
            anchor.setRow2(cell.getRowIndex() + 1);

            // 插入图片
            drawing.createPicture(anchor, pictureIdx);
        } catch (IOException e) {
            throw new RuntimeException("插入图片到Excel时出错", e);
        }
    }

    /**
     * 根据文件扩展名获取图片类型
     */
    private static int getPictureType(String imagePath) {
        String extension = imagePath.substring(imagePath.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "png": return Workbook.PICTURE_TYPE_PNG;
            case "jpg":
            case "jpeg": return Workbook.PICTURE_TYPE_JPEG;
            default:
                throw new IllegalArgumentException("不支持的图片格式: " + extension);
        }
    }

    /**
     * 在Excel中插入图片到指定单元格（原有方法保持不变）
     */
    public static void insertImagesToExcel(String templatePath, String outputPath,
                                           Map<String, String> imageMappings) {
        try (FileInputStream fis = new FileInputStream(templatePath);
             Workbook workbook = createWorkbook(fis, templatePath);
             FileOutputStream fos = new FileOutputStream(outputPath)) {

            Sheet sheet = workbook.getSheetAt(0); // 默认处理第一个工作表

            for (Map.Entry<String, String> entry : imageMappings.entrySet()) {
                String cellReference = entry.getKey();
                String imagePath = entry.getValue();

                // 解析单元格位置
                CellAddress address = new CellAddress(cellReference);
                int rowNum = address.getRow();
                int colNum = address.getColumn();

                // 获取或创建行和单元格
                Row row = sheet.getRow(rowNum);
                if (row == null) {
                    row = sheet.createRow(rowNum);
                }

                Cell cell = row.getCell(colNum);
                if (cell == null) {
                    cell = row.createCell(colNum);
                }

                // 插入图片
                insertImageToCell(workbook, sheet, cell, imagePath);
            }

            workbook.write(fos);
        } catch (IOException e) {
            throw new RuntimeException("处理Excel文件时出错", e);
        }
    }
}
