package com.dayou.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import com.github.liangbaika.validate.utils.SpringContextHolder;
import com.dayou.annotation.Excel;
import com.dayou.annotation.Excel.Type;
import com.dayou.annotation.Excels;
import com.dayou.common.RestResponse;
import com.dayou.configuration.DfsConfig;
import com.dayou.exception.BusinessException;
import com.dayou.exception.ErrorCode;
import com.dayou.exception.file.ExcelParseException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;

/**
 * Excel相关处理
 *
 * @author wucl
 */
public class ExcelPlusUtil<T> {
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil.class);

    /**
     * Excel sheet最大行数，默认65536
     */
    public static final int sheetSize = 65536;

    //最大导入条数限制
    public static final int IMPORT_MAX_ROWS = 10000;

    /**
     * 工作表名称
     */
    private String sheetName;

    /**
     * 导出类型（EXPORT:导出数据；IMPORT：导入模板）
     */
    private Type type;

    /**
     * 工作薄对象
     */
    private Workbook wb;

    /**
     * 工作表对象
     */
    private Sheet sheet;

    /**
     * 样式列表
     */
    private Map<String, CellStyle> styles;

    /**
     * 导入导出数据列表
     */
    private List<T> list;

    /**
     * 注解列表
     */
    private List<Object[]> fields;

    /**
     * 实体对象
     */
    public Class<T> clazz;


    public ExcelPlusUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void init(List<T> list, String sheetName, Type type) {
        if (list == null) {
            list = new ArrayList<T>();
        }
        this.list = list;
        this.sheetName = sheetName;
        this.type = type;
        createExcelField();
        createWorkbook();
    }

    public static void createOriginWorkBook(Function<Workbook, Void> function, OutputStream outputStream) throws IOException {
        Workbook workbook = new SXSSFWorkbook(50000);
        try {
            function.apply(workbook);
            workbook.write(outputStream);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            workbook.close();
        }

    }

    /**
     * 对excel表单默认第一个索引名转换成list
     *
     * @param is 输入流
     * @return 转换后集合
     */
    public List<T> importExcel(InputStream is) throws Exception {
        List<T> datas = null;
        try {
            datas = importExcel(StringUtils.EMPTY, is);
        } catch (Throwable e) {
            if (e instanceof BusinessException) {
                throw e;
            } else {
                //也会被全局异常拦截处理
                throw new ExcelParseException("excel解析出错 请检查文件格式 错误信息: " + e.getMessage());
            }
        }
        return datas;
    }

    /**
     * 对excel表单指定表格索引名转换成list
     *
     * @param sheetName 表格索引名
     * @param is        输入流
     * @return 转换后集合
     */
    public List<T> importExcel(String sheetName, InputStream is) throws Exception {
        this.type = Type.IMPORT;
        this.wb = WorkbookFactory.create(is);
        List<T> list = new ArrayList<T>();
        Sheet sheet = null;
        if (StringUtils.isNotEmpty(sheetName)) {
            // 如果指定sheet名,则取指定sheet中的内容.
            sheet = wb.getSheet(sheetName);
        } else {
            // 如果传入的sheet名不存在则默认指向第1个sheet.
            sheet = wb.getSheetAt(0);
        }

        if (sheet == null) {
            throw new IOException("文件sheet不存在");
        }

        int rows = sheet.getPhysicalNumberOfRows();

        if (rows > 0) {
            // 不能超过最大导入条数 不算表头数据
            if (rows > IMPORT_MAX_ROWS + 1) {
                ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR, String.format("抱歉 数据过多,excel导入失败 条数不能超过 %d 条", IMPORT_MAX_ROWS));
            }
            // 定义一个map用于存放excel列的序号和field.
            Map<String, Integer> cellMap = new HashMap<String, Integer>();
            // 获取表头
            Row heard = sheet.getRow(0);
            for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
                Cell cell = heard.getCell(i);
                if (cell != null) {
                    String value = this.getCellValue(heard, i).toString();
                    cellMap.put(value, i);
                } else {
                    cellMap.put(null, i);
                }
            }
            // 有数据时才处理 得到类的所有field.
            Field[] allFields = clazz.getDeclaredFields();
            // 定义一个map用于存放列的序号和field.
            Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
            for (int col = 0; col < allFields.length; col++) {
                Field field = allFields[col];
                Excel attr = field.getAnnotation(Excel.class);
                if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
                    // 设置类的私有字段属性可访问.
                    field.setAccessible(true);
                    Integer column = cellMap.get(attr.name());
                    if (column == null) {
                        ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR, MessageFormat.format("请检查模板表头[{0}]与实际导入表头名称是否一致", attr.name()));
                    }
                    fieldsMap.put(column, field);
                }
            }
            int continuationEmptyCount = 0;
            for (int i = 1; i < rows; i++) {
                // 从第2行开始取数据,默认第一行是表头.
                Row row = sheet.getRow(i);
                T entity = null;

                //预检查整行为空？则跳过
                int nullvalueCount = 0;
                for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()) {
                    Integer column = entry.getKey();
                    Object val = this.getCellValue(row, column);
                    if (val == null || StrUtil.isBlank(val.toString())) {
                        nullvalueCount += 1;
                    }
                }
                if (nullvalueCount >= fieldsMap.size()) {
                    log.info(String.format("第%d行全部为空,不解析,执行跳过", i + 1));
                    continuationEmptyCount += 1;
                    if (continuationEmptyCount > 100) {
                        log.info("空行过多 不再解析");
                        break;
                    }
                    continue;
                }

                // 支持 Byte  Float Double Char String Short Long Boolean Int  Date LocalDate LocalDateTime Bigdeciaml
                for (Map.Entry<Integer, Field> entry : fieldsMap.entrySet()) {
                    Integer column = entry.getKey();
                    Object val = this.getCellValue(row, column);

                    // 如果不存在实例则新建.
                    entity = (entity == null ? clazz.newInstance() : entity);
                    // 从map中得到对应列的field.
                    Field field = fieldsMap.get(column);
                    // 取得类型,并根据对象类型设置值.
                    Class<?> fieldType = field.getType();
                    if (String.class == fieldType) {
                        String s = Convert.toStr(val);
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = Convert.toStr(val);
                        }
                    } else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
                        val = Convert.toInt(val);
                    } else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
                        val = Convert.toLong(val);
                    } else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
                        val = Convert.toDouble(val);
                    } else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
                        val = Convert.toFloat(val);
                    } else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
                        val = Convert.toShort(val);
                    } else if ((Character.TYPE == fieldType) || (Character.class == fieldType)) {
                        val = Convert.toChar(val);
                    } else if ((Boolean.TYPE == fieldType) || (Boolean.class == fieldType)) {
                        val = Convert.toBool(val);
                    } else if ((Byte.TYPE == fieldType) || (Byte.class == fieldType)) {
                        val = Convert.toByte(val);
                    } else if ((LocalDate.class == fieldType)) {
                        val = DateUtils.parseLocalDate(val);
                    } else if ((LocalDateTime.class == fieldType)) {
                        val = DateUtils.parseLocalDateTime(val);
                    } else if (BigDecimal.class == fieldType) {
                        val = Convert.toBigDecimal(val);
                    } else if (Date.class == fieldType) {
                        if (val instanceof String) {
                            val = DateUtils.parseDate(val);
                        } else if (val instanceof Double) {
                            val = DateUtil.getJavaDate((Double) val);
                        }
                    } else {
                        log.error(String.format("  the type of  {%s}  can not be parsed  in excel parse row2bean ", fieldType.getName()));
                    }
                    if (fieldType != null) {
                        Excel attr = field.getAnnotation(Excel.class);
                        String propertyName = field.getName();
                        if (StringUtils.isNotEmpty(attr.targetAttr())) {
                            propertyName = field.getName() + "." + attr.targetAttr();
                        } else if (StringUtils.isNotEmpty(attr.readConverterExp())) {
                            val = reverseByExp(String.valueOf(val), attr.readConverterExp());
                        }
                        boolean required = attr.required();
                        if (required) {
                            if (val == null) {
                                String errorMsg = String.format("第%d行 第%d列  %s 不能为空", i + 1, column + 1, attr.name());
                                ErrorCode.throwBusinessException(ErrorCode.RAS_IMPORT_ERROR, errorMsg);
                            }
                            if (val instanceof CharSequence && StrUtil.isBlank((CharSequence) val)) {
                                String errorMsg = String.format("第%d行 第%d列  %s 不能为空", i + 1, column + 1, attr.name());
                                ErrorCode.throwBusinessException(ErrorCode.RAS_IMPORT_ERROR, errorMsg);
                            }
                        }
                        ReflectUtils.invokeSetter(entity, propertyName, val);
                    }
                }
                list.add(entity);
            }
        }
        return list;
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param list      导出数据集合
     * @param sheetName 工作表的名称
     * @return 结果
     */
    public RestResponse exportExcel(List<T> list, String sheetName) {
        this.init(list, sheetName, Type.EXPORT);
        return exportExcel();
    }

    public String exportExcel2File(List<T> list, String sheetName) {
        this.init(list, sheetName, Type.EXPORT);
        return exportExcel2File();
    }

    public void exportExcel2HttpResponse(List<T> list, String sheetName, ServletOutputStream outputStream) {
        this.init(list, sheetName, Type.EXPORT);
        exportExcel2HttpRrsponse(outputStream);
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param sheetName 工作表的名称
     * @return 结果
     */
    public RestResponse importTemplateExcel(String sheetName) {
        this.init(null, sheetName, Type.IMPORT);
        return exportExcel();
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @return 结果
     */
    public RestResponse exportExcel() {
        OutputStream out = null;
        try {
            // 取出一共有多少个sheet.
            double sheetNo = Math.ceil(list.size() / sheetSize);
            beforeExport(sheetNo);
            String filename = encodingFilename(sheetName);
            out = new FileOutputStream(getAbsoluteFile(filename));
            wb.write(out);
            return RestResponse.success(filename);
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new RuntimeException("导出Excel失败，请联系网站管理员！");
        } finally {
            afterExport(out);
        }
    }

    public String exportExcel2File() {
        OutputStream out = null;
        try {
            // 取出一共有多少个sheet.
            double sheetNo = Math.ceil(list.size() / sheetSize);
            beforeExport(sheetNo);
            String filename = encodingFilename(sheetName);
            out = new FileOutputStream(getAbsoluteFile(filename));
            wb.write(out);
            return filename;
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new RuntimeException("导出Excel失败，请联系网站管理员！");
        } finally {
            afterExport(out);
        }
    }

    private void beforeExport(double sheetNo) {
        for (int index = 0; index <= sheetNo; index++) {
            createSheet(sheetNo, index);
            // 产生一行
            Row row = sheet.createRow(0);

            int column = 0;
            // 写入各个字段的列头名称
            for (Object[] os : fields) {
                Field field = (Field) os[0];
                Excel excel = (Excel) os[1];
                Cell cell = this.createCell(excel, row, field, column++);

            }
            if (Type.EXPORT.equals(type)) {
                fillExcelData(index, row);
            }
        }
    }

    public void exportExcel2HttpRrsponse(ServletOutputStream servletOutputStream) {
        try {
            // 取出一共有多少个sheet.
            double sheetNo = Math.ceil(list.size() / sheetSize);
            beforeExport(sheetNo);
            wb.write(servletOutputStream);
            return;
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new RuntimeException("导出Excel失败，请联系网站管理员！");
        } finally {
            afterExport(servletOutputStream);
        }
    }


    private void afterExport(OutputStream servletOutputStream) {
        if (wb != null) {
            try {
                wb.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        if (servletOutputStream != null) {
            try {
                servletOutputStream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }


    /**
     * 设置有效性
     *
     * @param offset 主影响单元格所在列，即此单元格由哪个单元格影响联动
     * @param sheet
     * @param rowNum 行数
     * @param colNum 列数
     */
    public static void setDataValidation(String offset, XSSFSheet sheet, int rowNum, int colNum) {
        XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
        DataValidation data_validation_list;
        data_validation_list = getDataValidationByFormula(
                "INDIRECT($" + offset + (rowNum) + ")", rowNum, colNum, dvHelper);
        sheet.addValidationData(data_validation_list);
    }

    /**
     * 加载下拉列表内容
     *
     * @param formulaString
     * @param naturalRowIndex
     * @param naturalColumnIndex
     * @param dvHelper
     * @return
     */
    private static DataValidation getDataValidationByFormula(
            String formulaString, int naturalRowIndex, int naturalColumnIndex, XSSFDataValidationHelper dvHelper) {
        // 加载下拉列表内容
        // 举例：若formulaString = "INDIRECT($A$2)" 表示规则数据会从名称管理器中获取key与单元格 A2 值相同的数据，
        //如果A2是江苏省，那么此处就是江苏省下的市信息。
        XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createFormulaListConstraint(formulaString);
        // 设置数据有效性加载在哪个单元格上。
        // 四个参数分别是：起始行、终止行、起始列、终止列
        int firstRow = naturalRowIndex - 1;
        int lastRow = naturalRowIndex - 1;
        int firstCol = naturalColumnIndex - 1;
        int lastCol = naturalColumnIndex - 1;
        CellRangeAddressList regions = new CellRangeAddressList(firstRow,
                lastRow, firstCol, lastCol);
        // 数据有效性对象
        // 绑定
        XSSFDataValidation data_validation_list = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, regions);
        data_validation_list.setEmptyCellAllowed(false);
        if (data_validation_list instanceof XSSFDataValidation) {
            data_validation_list.setSuppressDropDownArrow(true);
            data_validation_list.setShowErrorBox(true);
        } else {
            data_validation_list.setSuppressDropDownArrow(false);
        }
        // 设置输入信息提示信息
        data_validation_list.createPromptBox("下拉选择提示", "请使用下拉方式选择合适的值！");
        // 设置输入错误提示信息
        //data_validation_list.createErrorBox("选择错误提示", "你输入的值未在备选列表中，请下拉选择合适的值！");
        return data_validation_list;
    }

    /**
     * @param offset   偏移量，如果给0，表示从A列开始，1，就是从B列
     * @param rowId    第几行
     * @param colCount 一共多少列
     * @return 如果给入参 1,1,10. 表示从B1-K1。最终返回 $B$1:$K$1
     * @author denggonghai 2016年8月31日 下午5:17:49
     */
    public String getRange(int offset, int rowId, int colCount) {
        char start = (char) ('A' + offset);
        if (colCount <= 25) {
            char end = (char) (start + colCount - 1);
            return "$" + start + "$" + rowId + ":$" + end + "$" + rowId;
        } else {
            char endPrefix = 'A';
            char endSuffix = 'A';
            if ((colCount - 25) / 26 == 0 || colCount == 51) {// 26-51之间，包括边界（仅两次字母表计算）
                if ((colCount - 25) % 26 == 0) {// 边界值
                    endSuffix = (char) ('A' + 25);
                } else {
                    endSuffix = (char) ('A' + (colCount - 25) % 26 - 1);
                }
            } else {// 51以上
                if ((colCount - 25) % 26 == 0) {
                    endSuffix = (char) ('A' + 25);
                    endPrefix = (char) (endPrefix + (colCount - 25) / 26 - 1);
                } else {
                    endSuffix = (char) ('A' + (colCount - 25) % 26 - 1);
                    endPrefix = (char) (endPrefix + (colCount - 25) / 26);
                }
            }
            return "$" + start + "$" + rowId + ":$" + endPrefix + endSuffix + "$" + rowId;
        }
    }

    /**
     * 填充excel数据
     *
     * @param index 序号
     * @param row   单元格行
     */
    public void fillExcelData(int index, Row row) {
        int startNo = index * sheetSize;
        int endNo = Math.min(startNo + sheetSize, list.size());
        for (int i = startNo; i < endNo; i++) {
            row = sheet.createRow(i + 1 - startNo);
            // 得到导出对象.
            T vo = (T) list.get(i);
            int column = 0;
            for (Object[] os : fields) {
                Field field = (Field) os[0];
                Excel excel = (Excel) os[1];
                // 设置实体类私有属性可访问
                field.setAccessible(true);
                this.addCell(excel, row, vo, field, column++);
            }
        }

        //说明数据为空 或者 为导入模板 此时设置单元格类型 避免数字溢出
        if (startNo == endNo) {
            CellStyle textStyle = wb.createCellStyle();
            DataFormat format = wb.createDataFormat();
            textStyle.setDataFormat(format.getFormat("@"));
            boolean hasNumberString = false;
            for (Object[] os : fields) {
                Excel excel = (Excel) os[1];
                if (excel.isNumberString()) {
                    hasNumberString = true;
                    break;
                }
            }
            if (!hasNumberString) {
                return;
            }

            for (int i = startNo + 1; i <= IMPORT_MAX_ROWS + startNo; i++) {
                row = sheet.createRow(i);
                int column = 0;
                for (Object[] os : fields) {
                    Excel excel = (Excel) os[1];
                    if (excel.isNumberString()) {
                        //设置单元格格式为"文本"
                        Cell cell = row.createCell(column);
                        cell.setCellStyle(textStyle);
                    }
                    column++;
                }
            }
        }
    }

    public static CellStyle getStyle(Workbook wb) {
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setBorderRight(BorderStyle.THIN);
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderLeft(BorderStyle.THIN);
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderTop(BorderStyle.THIN);
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setBorderBottom(BorderStyle.THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        return style;
    }

    /**
     * 创建表格样式
     *
     * @param wb 工作薄对象
     * @return 样式列表
     */
    private Map<String, CellStyle> createStyles(Workbook wb) {
        // 写入各条记录,每条记录对应excel表中的一行
        Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
        CellStyle style = getStyle(wb);
        Font dataFont = wb.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        style.setFont(dataFont);
        styles.put("data", style);


        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("data"));
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font headerFont = wb.createFont();
        headerFont.setFontName("Arial");
        headerFont.setFontHeightInPoints((short) 10);
        headerFont.setBold(true);
        headerFont.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(headerFont);
        styles.put("header", style);

        style = wb.createCellStyle();
        style.cloneStyleFrom(styles.get("header"));
        Font headerFontrequired = wb.createFont();
        headerFontrequired.setFontName("Arial");
        headerFontrequired.setFontHeightInPoints((short) 10);
        headerFontrequired.setBold(true);
        headerFontrequired.setColor(IndexedColors.LIGHT_YELLOW.getIndex());
//        style.setFillPattern(FillPatternType.FINE_DOTS);
        style.setFont(headerFontrequired);
        styles.put("requiredHeader", style);

        return styles;
    }

    /**
     * 创建单元格
     */
    public Cell createCell(Excel attr, Row row, Field field, int column) {
        String callBack = attr.exportCallBack();
        if (StrUtil.isNotBlank(callBack)) {
            ExcelColmunRender dynamicRender = SpringContextHolder.getBean("dynamicRender");
            Boolean renderWhenExport = dynamicRender.renderWhenExport(attr, row, null, field, column);
            if (!renderWhenExport) {
                return null;
            }
        }
        // 创建列
        Cell cell = row.createCell(column);
        // 写入列信息
        cell.setCellValue(attr.name());
        setDataValidation(attr, row, column);
        if (attr.required()) {
            cell.setCellStyle(styles.get("requiredHeader"));
        } else {
            cell.setCellStyle(styles.get("header"));
        }
        return cell;
    }

    /**
     * 设置单元格信息
     *
     * @param value 单元格值
     * @param attr  注解相关
     * @param cell  单元格信息
     */
    public void setCellVo(Object value, Excel attr, Cell cell) {
        if (Excel.ColumnType.STRING == attr.cellType()) {
            cell.setCellType(CellType.STRING);
            cell.setCellValue(value == null ? attr.defaultValue() : value + attr.suffix());
        } else if (Excel.ColumnType.NUMERIC == attr.cellType()) {
            cell.setCellType(CellType.NUMERIC);
            cell.setCellValue(Integer.parseInt(value + ""));
        }
    }

    /**
     * 创建表格样式
     */
    public void setDataValidation(Excel attr, Row row, int column) {
        if (attr.name().indexOf("注：") >= 0) {
            sheet.setColumnWidth(column, 6000);
        } else {
            // 设置列宽
            sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
            row.setHeight((short) (attr.height() * 20));
        }
        // 如果设置了提示信息则鼠标放上去提示.
        if (StringUtils.isNotEmpty(attr.prompt())) {
            // 这里默认设了2-101列提示.
            setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column);
        }
//        if (StringUtils.isNotBlank(attr.dynamic())) {
//            SysDictDataMapper bean = SpringContextHolder.getBean(SysDictDataMapper.class);
//            List<SysDictData> sysDictData = bean.selectDictDataByType(attr.dynamic());
//            if (CollUtil.isNotEmpty(sysDictData)) {
//                List<String> datas = sysDictData.stream().map(e -> e.getDictValue()).collect(Collectors.toList());
//                String dicts = CollUtil.join(datas, Constants.SPLITER);
//                setXSSFValidation(sheet, dicts.split(Constants.SPLITER), 1, 100, column, column);
//            }
//        }

        // 如果设置了combo属性则本列只能选择不能输入
        if (attr.combo().length > 0) {
            // 这里默认设了2-101列只能选择不能输入.
            setXSSFValidation(sheet, attr.combo(), 1, 100, column, column);
        }

        if (StringUtils.isNotBlank(attr.combos())) {
            // 这里默认设了2-101列只能选择不能输入.
            setXSSFValidation(sheet, attr.combos().split(","), 1, 100, column, column);
        }
    }

    /**
     * 添加单元格
     */
    public Cell addCell(Excel attr, Row row, T vo, Field field, int column) {
        Cell cell = null;
        try {
            // 设置行高
            boolean export = attr.isExport();
            row.setHeight((short) (attr.height() * 20));
            // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
            if (export) {
                // 创建cell
                cell = row.createCell(column);
                cell.setCellStyle(styles.get("data"));

                // 用于读取对象中的属性
                Object value = getTargetValue(vo, field, attr);
                String dateFormat = attr.dateFormat();
                String readConverterExp = attr.readConverterExp();
                if (StringUtils.isNotEmpty(dateFormat) && value != null) {
                    cell.setCellValue(DateUtils.parseDateToStr(dateFormat, (Date) value));
                } else if (StringUtils.isNotEmpty(readConverterExp) && value != null) {
                    cell.setCellValue(convertByExp(String.valueOf(value), readConverterExp));
                } else {
                    // 设置列类型
                    setCellVo(value, attr, cell);
                }
            }
        } catch (Exception e) {
            log.error("导出Excel失败{}", e);
        }
        return cell;
    }

    /**
     * 设置 POI XSSFSheet 单元格提示
     *
     * @param sheet         表单
     * @param promptTitle   提示标题
     * @param promptContent 提示内容
     * @param firstRow      开始行
     * @param endRow        结束行
     * @param firstCol      开始列
     * @param endCol        结束列
     */
    public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow,
                              int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = helper.createCustomConstraint("DD1");
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        dataValidation.createPromptBox(promptTitle, promptContent);
        dataValidation.setShowPromptBox(true);
        sheet.addValidationData(dataValidation);
    }

    /**
     * 设置某些列的值只能输入预制的数据,显示下拉框.
     *
     * @param sheet    要设置的sheet.
     * @param textlist 下拉框显示的内容
     * @param firstRow 开始行
     * @param endRow   结束行
     * @param firstCol 开始列
     * @param endCol   结束列
     * @return 设置好的sheet.
     */
    public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        // 加载下拉列表内容
        DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是：起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        // 数据有效性对象
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        // 处理Excel兼容性问题
        if (dataValidation instanceof XSSFDataValidation) {
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }

        sheet.addValidationData(dataValidation);
    }

    /**
     * 解析导出值 0=男,1=女,2=未知
     *
     * @param propertyValue 参数值
     * @param converterExp  翻译注解
     * @return 解析后值
     * @throws Exception
     */
    public static String convertByExp(String propertyValue, String converterExp) throws Exception {
        try {
            String[] convertSource = converterExp.split(",");
            for (String item : convertSource) {
                String[] itemArray = item.split("=");
                if (itemArray[0].equals(propertyValue)) {
                    return itemArray[1];
                }
            }
        } catch (Exception e) {
            throw e;
        }
        return propertyValue;
    }

    /**
     * 反向解析值 男=0,女=1,未知=2
     *
     * @param propertyValue 参数值
     * @param converterExp  翻译注解
     * @return 解析后值
     * @throws Exception
     */
    public static String reverseByExp(String propertyValue, String converterExp) throws Exception {
        try {
            String[] convertSource = converterExp.split(",");
            for (String item : convertSource) {
                String[] itemArray = item.split("=");
                if (itemArray[1].equals(propertyValue)) {
                    return itemArray[0];
                }
            }
        } catch (Exception e) {
            throw e;
        }
        return propertyValue;
    }

    /**
     * 编码文件名
     */
    public String encodingFilename(String filename) {
        filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx";
        return filename;
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    public String getAbsoluteFile(String filename) {
        String downloadPath = SpringContextHolder.getBean(DfsConfig.class).getPath() + "/" + filename;
        //String downloadPath = "D:\\" + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    /**
     * 获取bean中的属性值
     *
     * @param vo    实体对象
     * @param field 字段
     * @param excel 注解
     * @return 最终的属性值
     * @throws Exception
     */
    private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
        Object o = field.get(vo);
        if (StringUtils.isNotEmpty(excel.targetAttr())) {
            String target = excel.targetAttr();
            if (target.indexOf(".") > -1) {
                String[] targets = target.split("[.]");
                for (String name : targets) {
                    o = getValue(o, name);
                }
            } else {
                o = getValue(o, target);
            }
        }
        return o;
    }

    /**
     * 以类的属性的get方法方法形式获取值
     *
     * @param o
     * @param name
     * @return value
     * @throws Exception
     */
    private Object getValue(Object o, String name) throws Exception {
        if (StringUtils.isNotEmpty(name)) {
            Class<?> clazz = o.getClass();
            String methodName = "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
            Method method = clazz.getMethod(methodName);
            o = method.invoke(o);
        }
        return o;
    }

    /**
     * 得到所有定义字段
     */
    private void createExcelField() {
        this.fields = new ArrayList<Object[]>();
        List<Field> tempFields = new ArrayList<>();
        tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
        tempFields.addAll(Arrays.asList(clazz.getDeclaredFields()));
        for (Field field : tempFields) {
            // 单注解
            if (field.isAnnotationPresent(Excel.class)) {
                putToField(field, field.getAnnotation(Excel.class));
            }

            // 多注解
            if (field.isAnnotationPresent(Excels.class)) {
                Excels attrs = field.getAnnotation(Excels.class);
                Excel[] excels = attrs.value();
                for (Excel excel : excels) {
                    putToField(field, excel);
                }
            }
        }
    }

    /**
     * 放到字段集合中
     */
    private void putToField(Field field, Excel attr) {
        if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
            this.fields.add(new Object[]{field, attr});
        }
    }

    /**
     * 创建一个工作簿
     */
    public void createWorkbook() {
        this.wb = new SXSSFWorkbook();
//        this.wb = new XSSFWorkbook();
    }

    /**
     * 创建工作表
     *
     * @param sheetNo sheet数量
     * @param index   序号
     */
    public void createSheet(double sheetNo, int index) {
        this.sheet = wb.createSheet();
        this.styles = createStyles(wb);
        // 设置工作表的名称.
        if (sheetNo == 0) {
            wb.setSheetName(index, sheetName);
        } else {
            wb.setSheetName(index, sheetName + index);
        }
    }

    public Sheet createSpecialSheet(String name, int index) {
        Sheet sheet = wb.createSheet();
        // 设置工作表的名称.
        wb.setSheetName(index, name);
        return sheet;
    }

    /**
     * 获取单元格值
     *
     * @param row    获取的行
     * @param column 获取单元格列号
     * @return 单元格值
     */
    public Object getCellValue(Row row, int column) {
        if (row == null) {
            return row;
        }
        Object val = "";
        try {
            Cell cell = row.getCell(column);
            if (cell != null) {
                if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) {
                    val = cell.getNumericCellValue();
                    if (DateUtil.isCellDateFormatted(cell)) {
                        val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换
                    } else {
                        if ((Double) val % 1 > 0) {
                            val = new DecimalFormat("0.00").format(val);
                        } else {
                            val = new DecimalFormat("0").format(val);
                        }
                    }
                } else if (cell.getCellType() == CellType.STRING) {
                    val = cell.getStringCellValue();
                } else if (cell.getCellType() == CellType.BOOLEAN) {
                    val = cell.getBooleanCellValue();
                } else if (cell.getCellType() == CellType.ERROR) {
                    val = cell.getErrorCellValue();
                }

            }
        } catch (Exception e) {
            return val;
        }
        return val;
    }

    /**
     * 创建XSSFWorkbook
     */
    public void createXSSFWorkbook() {
        this.wb = new XSSFWorkbook();
    }

    public void exportExcel2HttpResponse(List<T> list, String sheetName, ServletOutputStream outputStream, String[] options) {
        if (list == null) {
            list = new ArrayList<T>();
        }
        this.list = list;
        this.sheetName = sheetName;
        this.type = Type.EXPORT;
        createExcelField();
        createXSSFWorkbook();
        try {
            double sheetNo = Math.ceil(list.size() / sheetSize);
            beforeExport(sheetNo);
            XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
            XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
                    .createExplicitListConstraint(options);
            CellRangeAddressList addressList = null;
            XSSFDataValidation validation = null;
            for (int i = 0; i < list.size(); i++) {
                addressList = new CellRangeAddressList(i + 1, i + 1, fields.size() - 1, fields.size() - 1);
                validation = (XSSFDataValidation) dvHelper.createValidation(
                        dvConstraint, addressList);
                sheet.addValidationData(validation);
            }
            wb.write(outputStream);
            return;
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("导出Excel失败，请联系网站管理员！");
        } finally {
            afterExport(outputStream);
        }
    }

    /**
     * @param in        Excel表格二进制输入流
     * @param sheetName 需要读取的工作薄名称
     * @param columns   需要读取的列数
     * @return
     * @throws IOException
     * @method readXlsx(InputStream in, String sheetName, Integer column)
     * @Description 读取Excel表格2007/2010版本
     * @author dy
     * @date 2016年11月1日
     */
    public static ArrayList<String[]> readXlsx(InputStream in, String sheetName, Integer columns, Integer row)
            throws IOException {

        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);
        ArrayList<String[]> list = new ArrayList<String[]>();
        // Read the Sheet 1
        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
        if (row == null || row < 0) {
            row = 1;
        }
        // Read the Row 2
        for (int rowNum = row; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
            XSSFRow xssfRow = xssfSheet.getRow(rowNum);
            String[] strs = new String[columns];
            if (xssfRow != null) {
                for (int i = 0; i < columns; i++) {
                    if (xssfRow.getCell(i) != null && (xssfRow.getCell(i)).toString() != null) {
                        XSSFCell cell = xssfRow.getCell(i);
                        if(cell.getCellType() != CellType.STRING){
                            cell.setCellType(CellType.STRING);
                        }
                        strs[i] = cell.toString();
                        if (strs[i] != null) {
                            strs[i] = strs[i].trim();
                        }
                    }
                }
                if (strs != null) {
                    list.add(strs);
                }
            }
        }
//        xssfWorkbook.close();
        return list;
    }

    /**
     * @param in        Excel表格二进制输入流
     * @param index 需要读取的工作薄的下表
     * @param columns   需要读取的列数
     * @return
     * @throws IOException
     * @method readXlsx(InputStream in, String sheetName, Integer column)
     * @Description 读取Excel表格2007/2010版本
     * @author dy
     * @date 2016年11月1日
     */
    public static ArrayList<String[]> readXlsx(InputStream in, int index, Integer columns, Integer row)
            throws IOException {

        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(in);
        ArrayList<String[]> list = new ArrayList<String[]>();
        XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(index);
        if (row == null || row < 0) {
            row = 1;
        }
        for (int rowNum = row; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
            XSSFRow xssfRow = xssfSheet.getRow(rowNum);
            String[] strs = new String[columns];
            if (xssfRow != null) {
                for (int i = 0; i < columns; i++) {
                    if (xssfRow.getCell(i) != null && (xssfRow.getCell(i)).toString() != null) {
                        XSSFCell cell = xssfRow.getCell(i);
                        if(cell.getCellType() != CellType.STRING){
                            cell.setCellType(CellType.STRING);
                        }
                        strs[i] = cell.toString();
                        if (strs[i] != null) {
                            strs[i] = strs[i].trim();
                        }
                    }
                }
                if (strs != null) {
                    list.add(strs);
                }
            }
        }
        return list;
    }

    public static void setBorderStyle(BorderStyle border, CellRangeAddress region, Sheet sheet) {
        RegionUtil.setBorderBottom(border, region, sheet);      //下边框
        RegionUtil.setBorderLeft(border, region, sheet);     //左边框
        RegionUtil.setBorderRight(border, region, sheet);    //右边框
        RegionUtil.setBorderTop(border, region, sheet);      //上边框
    }
}