package com.ssyf.plugs.poi;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class ExcelUtil {

    /**
     * 创建一个Excel Workbook对象
     *
     * @param data     数据列表
     * @param fieldMap 字段名和中文名的映射
     * @param <T>      泛型对象类型
     * @return Workbook对象
     * @throws IOException 如果发生IO错误
     */
    public static <T> Workbook createWorkbook(List<T> data, Map<String, String> fieldMap) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        int headerCellIndex = 0;
        for (String fieldName : fieldMap.keySet()) {
            Cell cell = headerRow.createCell(headerCellIndex++);
            cell.setCellValue(fieldMap.get(fieldName));
        }

        // 填充数据
        int rowIndex = 1;
        for (T item : data) {
            Row row = sheet.createRow(rowIndex++);
            headerCellIndex = 0;
            for (String fieldName : fieldMap.keySet()) {
                Cell cell = row.createCell(headerCellIndex++);
                try {
                    Field field = item.getClass().getDeclaredField(fieldName);
                    field.setAccessible(true);
                    Object value = field.get(item);
                    if (value instanceof LocalDateTime) {
                        cell.setCellValue(((LocalDateTime) value).toString());
                    } else {
                        cell.setCellValue(value != null ? value.toString() : "");
                    }
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    //e.printStackTrace();
                    //不做处理
                }
            }
        }

        return workbook;
    }

    public static <T> Workbook createWorkbookAndSetColumnDropdown(List<T> data, Map<String, String> fieldMap, Map<String, List<String>> columnDropdownListMap) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1");

        // 创建表头
        Row headerRow = sheet.createRow(0);
        int headerCellIndex = 0;
        for (String fieldName : fieldMap.keySet()) {
            Cell cell = headerRow.createCell(headerCellIndex++);
            String column = fieldMap.get(fieldName);
            cell.setCellValue(column);

            //设置列的条件约束，下拉可选项
            List<String> columnDropdownList = columnDropdownListMap.get(column);
            if (CollectionUtil.isNotEmpty(columnDropdownList)) {
                setColumnDropdown(workbook, sheet, headerCellIndex - 1, columnDropdownList);
            }
        }

        // 填充数据
        int rowIndex = 1;
        for (T item : data) {
            Row row = sheet.createRow(rowIndex++);
            headerCellIndex = 0;
            for (String fieldName : fieldMap.keySet()) {
                Cell cell = row.createCell(headerCellIndex++);
                try {
                    Field field = item.getClass().getDeclaredField(fieldName);
                    field.setAccessible(true);
                    Object value = field.get(item);
                    if (value instanceof LocalDateTime) {
                        cell.setCellValue(((LocalDateTime) value).toString());
                    } else {
                        cell.setCellValue(value != null ? value.toString() : "");
                    }
                } catch (NoSuchFieldException | IllegalAccessException e) {
                    //e.printStackTrace();
                    //不做处理
                }
            }
        }

        return workbook;
    }

    /**
     * 为某一列设置可选值（下拉列表）
     *
     * @param workbook    Workbook对象
     * @param sheet       工作表
     * @param columnIndex 列索引（从0开始）
     * @param options     可选值列表
     */
    public static void setColumnDropdown(Workbook workbook, Sheet sheet, int columnIndex, List<String> options) {
        DataValidationHelper validationHelper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = validationHelper.createExplicitListConstraint(options.toArray(new String[0]));

        // 设置数据验证的范围（整列）
        CellRangeAddressList addressList = new CellRangeAddressList(1, 65535, columnIndex, columnIndex);

        // 创建数据验证
        DataValidation validation = validationHelper.createValidation(constraint, addressList);

        // 设置验证提示
        validation.createPromptBox("提示", "请从下拉列表中选择一个值");

        // 添加验证到工作表
        sheet.addValidationData(validation);
    }

    /**
     * 反解析 Excel 文件，将每一行数据解析为泛型对象集合
     *
     * @param inputStream Excel 文件输入流
     * @param fieldMap    字段名和中文名的映射（key: 字段名, value: 中文名）
     * @param clazz       泛型类型
     * @param <T>         泛型对象类型
     * @return 解析后的对象集合
     * @throws IOException 如果发生 IO 错误
     */
    public static <T> List<T> parseExcel(InputStream inputStream, Map<String, String> fieldMap, Class<T> clazz) throws IOException {
        List<T> result = new ArrayList<>();
        Workbook workbook = new XSSFWorkbook(inputStream);
        Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表

        // 获取表头行
        Row headerRow = sheet.getRow(0);
        if (headerRow == null) {
            throw new IllegalArgumentException("Excel 文件没有表头行");
        }

        // 创建字段名和列索引的映射
        Map<String, Integer> columnIndexMap = new java.util.HashMap<>();
        for (Cell cell : headerRow) {
            String headerValue = cell.getStringCellValue();
            for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
                if (entry.getValue().equals(headerValue)) {
                    columnIndexMap.put(entry.getKey(), cell.getColumnIndex());
                    break;
                }
            }
        }

        // 遍历数据行
        for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
            Row row = sheet.getRow(rowIndex);
            if (row == null) continue;

            T instance;
            try {
                instance = clazz.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                throw new RuntimeException("无法创建泛型对象实例", e);
            }

            // 填充对象字段
            for (Map.Entry<String, Integer> entry : columnIndexMap.entrySet()) {
                String fieldName = entry.getKey();
                int columnIndex = entry.getValue();
                Cell cell = row.getCell(columnIndex);
                if (cell == null) continue;

                try {
                    Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    Object value = getCellValueAndFormat(cell, field.getType());
                    field.set(instance, value);
                } catch (Exception e) {
                    // 忽略无法解析的字段
                    e.printStackTrace();
                }
            }

            result.add(instance);
        }

        workbook.close();
        return result;
    }

    /**
     * 获取值并格式化处理
     *
     * @param cell
     * @param fieldType
     * @return
     */
    private static Object getCellValueAndFormat(Cell cell, Class<?> fieldType) {
        Object value = getCellValue(cell, fieldType);
        if (value == null || !(value instanceof String)) {
            return value;
        }
        String valueString = value.toString();
        valueString = valueString.trim();
        if (valueString.endsWith(".0")) {
            valueString = valueString.substring(0, valueString.length() - 2);
        }
        return valueString;
    }

    /**
     * 根据字段类型获取单元格的值
     *
     * @param cell      单元格
     * @param fieldType 字段类型
     * @return 解析后的值
     */
    private static Object getCellValue(Cell cell, Class<?> fieldType) {
        try {
            switch (cell.getCellType()) {
                case STRING:
                    String stringValue = cell.getStringCellValue();
                    if (fieldType == String.class) {
                        return stringValue;
                    } else if (fieldType == Integer.class || fieldType == int.class) {
                        return Integer.parseInt(stringValue);
                    } else if (fieldType == Long.class || fieldType == long.class) {
                        return Long.parseLong(stringValue);
                    } else if (fieldType == Double.class || fieldType == double.class) {
                        return Double.parseDouble(stringValue);
                    } else if (fieldType == Boolean.class || fieldType == boolean.class) {
                        return Boolean.parseBoolean(stringValue);
                    } else if (fieldType == LocalDateTime.class) {
                        //日期反解析，匹配常用的中文格式
                        return com.ssyf.common.core.util.DateUtil.parseDateTime(stringValue);
                    } else if (fieldType == LocalDate.class) {
                        return com.ssyf.common.core.util.DateUtil.parseDate(stringValue);
                    }
                    break;
                case NUMERIC:
                    if (DateUtil.isCellDateFormatted(cell)) {
                        LocalDateTime localDateTime = cell.getLocalDateTimeCellValue();
                        if (fieldType == String.class) {
                            return com.ssyf.common.core.util.DateUtil.formatDateTime(localDateTime);
                        } else if (fieldType == Integer.class || fieldType == int.class) {
                            //返回秒
                            return localDateTime.toEpochSecond(ZoneOffset.UTC);
                        } else if (fieldType == Long.class || fieldType == long.class) {
                            //返回秒
                            return localDateTime.toEpochSecond(ZoneOffset.UTC);
                        } else if (fieldType == Double.class || fieldType == double.class) {
                            //返回秒
                            return localDateTime.toEpochSecond(ZoneOffset.UTC);
                        } else if (fieldType == Boolean.class || fieldType == boolean.class) {
                            //返回秒
                            return localDateTime.toEpochSecond(ZoneOffset.UTC) > 0;
                        } else if (fieldType == LocalDateTime.class) {
                            //日期反解析，匹配常用的中文格式
                            return localDateTime;
                        } else if (fieldType == LocalDate.class) {
                            return localDateTime.toLocalDate();
                        }
                    } else {
                        double numericValue = cell.getNumericCellValue();

                        if (fieldType == String.class) {
                            // 判断是否为整数
                            if (numericValue == Math.floor(numericValue)) {
                                // 转换为 long 并转成字符串，避免科学计数法
                                return String.valueOf((long) numericValue);
                            } else {
                                // 非整数，保留小数位
                                return String.format("%.15f", numericValue).replaceAll("0*$", "").replaceAll("\\.$", "");
                            }
                        } else if (fieldType == Integer.class || fieldType == int.class) {
                            return (int) numericValue;
                        } else if (fieldType == Long.class || fieldType == long.class) {
                            return (long) numericValue;
                        } else if (fieldType == Double.class || fieldType == double.class) {
                            return numericValue;
                        }

                    }
                    break;
                case BOOLEAN:
                    return cell.getBooleanCellValue();
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            //不做处理
            log.warn("单元格的值与目标格式的值不匹配，不能解析：" + cell.getStringCellValue());
        }
        return null;
    }
}
