package com.foreverwin.mesnac.common.util;

import com.foreverwin.mesnac.common.model.ExcelColumn;
import com.foreverwin.modular.core.exception.BusinessException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.CharUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Excel工具类
 *
 * @author Leon
 * @date 2021-06-10
 */
public class ExcelUtils {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);

    private final static String EXCEL2003 = "xls";
    private final static String EXCEL2007 = "xlsx";

    public static <T> List<T> readExcel(String fileType, Class<T> tClass, MultipartFile multipartFile, FileItem fileItem){

        Workbook workbook = null;
        List<T> dataList = new ArrayList<>();
        try {
            InputStream inputStream = null;
            if (multipartFile != null && !multipartFile.isEmpty()) {
                inputStream = multipartFile.getInputStream();
            } else {
                inputStream = fileItem.getInputStream();
            }

            //分析文件格式
            if (EXCEL2003.equals(fileType)) {
                workbook = new HSSFWorkbook(inputStream);
            }
            if (EXCEL2007.equals(fileType)) {
                workbook = new XSSFWorkbook(inputStream);
            }

            if (workbook == null) {
                throw BusinessException.build("文件格式" + fileType + "不是Excel类型");
            }

            //类映射  注解 value-->bean columns
            Map<String, List<Field>> classMap = new HashMap<>();
            List<Field> fields = Stream.of(tClass.getDeclaredFields()).collect(Collectors.toList());
            fields.forEach(
                    field -> {
                        ExcelColumn annotation = field.getAnnotation(ExcelColumn.class);
                        if (annotation != null) {
                            String value = annotation.value();
                            if (StringUtils.isBlank(value)) {
                                return;//return起到的作用和continue是相同的 语法
                            }
                            if (!classMap.containsKey(value)) {
                                classMap.put(value, new ArrayList<>());
                            }
                            field.setAccessible(true);
                            classMap.get(value).add(field);
                        }
                    }
            );


            //默认读取第一个sheet
            Sheet sheet = workbook.getSheetAt(0);
            //索引-->columns
            Map<Integer, List<Field>> reflectionMap = new HashMap<>(16);

            boolean firstRow = true;
            for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);

                //首行  提取列名
                if (firstRow) {
                    for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                        Cell cell = row.getCell(j);
                        String cellValue = getCellValue(cell);
                        if (classMap.containsKey(cellValue)) {
                            reflectionMap.put(j, classMap.get(cellValue));
                        }
                    }
                    firstRow = false;

                } else {
                    //忽略空白行
                    if (row == null) {
                        continue;
                    }
                    T t = tClass.newInstance();

                    //判断是否为空白行
                    boolean allBlank = true;
                    for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
                        if (reflectionMap.containsKey(j)) {
                            Cell cell = row.getCell(j);
                            String cellValue = getCellValue(cell);
                            if (StringUtils.isNotBlank(cellValue)) {
                                allBlank = false;
                            }
                            List<Field> fieldList = reflectionMap.get(j);
                            fieldList.forEach(
                                    x -> {
                                        try {
                                            handleField(t, cellValue, x);
                                        } catch (Exception e) {
                                            logger.error(String.format("reflect field:%s value:%s exception!", x.getName(), cellValue), e);
                                        }
                                    }
                            );
                        }
                    }

                    if (!allBlank) {
                        dataList.add(t);
                    }
                }// end else
            }// end for
        } catch (Exception e) {
            throw BusinessException.build(e.getMessage());
        }



        return dataList;
    }


    private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(cell.getNumericCellValue()).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }

    }

    private static <T> void handleField(T t, String value, Field field) throws Exception {
        Class<?> type = field.getType();
        if (type == null || type == void.class || StringUtils.isBlank(value)) {
            return;
        }
        if (type == Object.class) {
            field.set(t, value);
        } else if (type.getSuperclass() == null || type.getSuperclass() == Number.class) {
            //数字类型
            if (type == int.class || type == Integer.class) {
                field.set(t, NumberUtils.toInt(value));
            } else if (type == long.class || type == Long.class) {
                field.set(t, NumberUtils.toLong(value));
            } else if (type == double.class || type == Double.class) {
                field.set(t, NumberUtils.toDouble(value));
            } else if (type == float.class || type == Float.class) {
                field.set(t, NumberUtils.toFloat(value));
            } else if (type == char.class || type == Character.class) {
                field.set(t, CharUtils.toChar(value));
            } else if (type == boolean.class) {
                field.set(t, BooleanUtils.toBoolean(value));
            } else if (type == BigDecimal.class) {
                field.set(t, new BigDecimal(value));
            }
        } else if (type == Boolean.class) {
            field.set(t, BooleanUtils.toBoolean(value));
        } else if (type == Date.class) {
            field.set(t, value);
        } else if (type == String.class) {
            field.set(t, value);
        } else if (type == LocalDateTime.class) {
            value = value.replace("T", " ");
            field.set(t, LocalDateTime.parse(value, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }else {
            Constructor<?> constructor = type.getConstructor(String.class);
            field.set(t, constructor.newInstance(value));
        }
    }
}
