package com.ruoyi.common.core.utils;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class CustomExcelImportUtil {
    public static <T> List<T> importExcel(InputStream inputStream, Class<?> pojoClass, ImportParams params, int cellMaxLength) throws Exception {
        try (Workbook workbook = WorkbookFactory.create(inputStream)) {
            // 预处理工作簿，将空字符串转为 CellType.BLANK，并校验单元格内容长度
            preprocessWorkbook(workbook, cellMaxLength);

            // 将预处理后的工作簿转换为新的输入流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            workbook.write(bos);
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            List<T> list = ExcelImportUtil.importExcel(bis, pojoClass, params);

            // 过滤掉全空行
            return filterEmptyRows(list, pojoClass);
        }
    }

    private static void preprocessWorkbook(Workbook workbook, int cellMaxLength) {
        for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
            Sheet sheet = workbook.getSheetAt(i);
            for (Row row : sheet) {
                if (row == null) {
                    continue;
                }
                for (Cell cell : row) {
                    if (cell == null) {
                        continue;
                    }
                    DataFormatter formatter = new DataFormatter();
                    String cellValue = formatter.formatCellValue(cell).trim();
                    if (StringUtils.isBlank(cellValue)) {
                        cell.setCellType(CellType.BLANK);
                    } else if (cellValue.length() > cellMaxLength) {
                        throw new ServiceException("单元格内容长度不可超过" + cellMaxLength);
                    }
                }
            }
        }
    }

    private static <T> List<T> filterEmptyRows(List<T> list, Class<?> clazz) {
        List<T> filteredList = new ArrayList<>();
        for (T item : list) {
            boolean isEmpty = true;
            for (java.lang.reflect.Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                try {
                    Object value = field.get(item);
                    if (value != null && !value.toString().trim().isEmpty()) {
                        isEmpty = false;
                        break;
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            if (!isEmpty) {
                filteredList.add(item);
            }
        }
        return filteredList;
    }
}
