package com.artfess.poi.util;

import com.artfess.poi.Excel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Description:
 * @Auther: min.wu
 * @Date: 2023/02/14
 */
@Slf4j
public class CustomHeader {

    /**
     * 合并表头导出方法
     *
     * @param headerNodes
     * @param response
     * @param fileName
     * @param sheetName
     * @throws IOException
     */
    public static void regionExport(List<HeaderNode> headerNodes, HttpServletResponse response, String fileName, String sheetName) throws IOException {
        Excel excel = new Excel();
        excel.sheet().sheetName(sheetName);
        // 产生工作薄对象
        HSSFWorkbook workbook = excel.getWorkBook();
        HSSFSheet sheet = workbook.getSheet(sheetName);

        HSSFCellStyle headStyle = workbook.createCellStyle();
        defaultHeadStyle(headStyle);
        //表头层级
//        int deep = headerNodes.stream().map(HeaderNode::getRow).reduce(Integer::max).orElse(1);
        for (int i = 0; i <= 1; i++) {
            sheet.createRow(i);
        }
        for (HeaderNode headerNode : headerNodes) {
            int row = headerNode.getRow();
            if (row <= 1) {
                int col = headerNode.getColumn();
                excel.cell(headerNode.getRow(), headerNode.getColumn()).value(headerNode.getHeaderName()).style(headStyle);
                CellRangeAddress region;
                //是否跨列
                if (headerNode.isOverNode()) {
                    region = new CellRangeAddress(row, 3, col, col);
                } else {
                    region = new CellRangeAddress(row, row, col, (col + headerNode.getOverNodeCount() - 1));
                }
                if (region.getNumberOfCells() > 1) {
                    sheet.addMergedRegionUnsafe(region);
                    //合并后设置下边框
                    RegionUtil.setBorderTop(BorderStyle.THIN, region, sheet);
                    RegionUtil.setBorderLeft(BorderStyle.THIN, region, sheet);
                    RegionUtil.setBorderBottom(BorderStyle.THIN, region, sheet);
                    RegionUtil.setBorderRight(BorderStyle.THIN, region, sheet);
                }
            } else {
                excel.cell(headerNode.getRow(), headerNode.getColumn()).value(headerNode.getHeaderName());
            }
        }
    }

    public static void export(List<HeaderNode> headerNodes, HttpServletResponse response, String fileName, String sheetName) throws IOException {
        // 产生工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();
        CellStyle percentCellStyle = workbook.createCellStyle();
        percentCellStyle.setDataFormat(workbook.createDataFormat().getFormat("0.00%"));
        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(0, sheetName);
        HSSFCellStyle headStyle = workbook.createCellStyle();
        defaultHeadStyle(headStyle);
        Set<Integer> rowList = new HashSet<>();
        Set<Integer> columnList = new HashSet<>();
        for (HeaderNode headerNode : headerNodes) {
            rowList.add(headerNode.getRow());
            columnList.add(headerNode.getColumn());
        }
        rowList.forEach(row -> {
            HSSFRow hssfRow = sheet.createRow(row);
            columnList.forEach(column -> {
                 hssfRow.createCell(column);
            });
        });

        for (HeaderNode headerNode : headerNodes) {
            HSSFRow row = sheet.getRow(headerNode.getRow());
            // 产生单元格
            HSSFCell cell = row.getCell(headerNode.getColumn());
            // 设置列中写入内容为String类型
            cell.setCellStyle(headStyle);
            cell.setCellType(CellType.STRING);
            if (StringUtils.isNotEmpty(headerNode.getHeaderName()) && null != headerNode.getHeaderName()) {
                String headerName = headerNode.getHeaderName();
                //判断data是否为数值型
                Boolean isNum = headerName.matches("^(-?\\d+)(\\.\\d+)?$");
                //判断data是否为整数（小数部分是否为0）
                Boolean isInteger = headerName.matches("^[-\\+]?[\\d]*$");

                if (isInteger) {
                    cell.setCellValue(Integer.parseInt(headerName));
                } else if (isNum) {
                    BigDecimal bc = new BigDecimal(headerName);
                    cell.setCellValue(bc.doubleValue());
                } else {
                    cell.setCellValue(headerName);
                }
            }
        }
        ExcelUtil.downloadExcel(workbook, fileName, response);
        //本地测试使用
        FileOutputStream fileOut = null;
        try {
            File file = new File("D:/excel/myExcel.xls");
            fileOut = new FileOutputStream(file);
            workbook.write(fileOut);
            System.out.println("----Excle文件已生成------");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOut != null) {
                try {
                    fileOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * 说明：判断是否为BigDecimal
     *
     * @param headerName
     * @return
     */
    public static boolean isBigDecimal(String headerName) {
        try {
            new BigDecimal(headerName);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }


    /**
     * 表头样式
     *
     * @param headStyle
     */
    private static void defaultHeadStyle(CellStyle headStyle) {
//        headStyle.setBorderTop(BorderStyle.THIN);
//        headStyle.setBorderLeft(BorderStyle.THIN);
//        headStyle.setBorderBottom(BorderStyle.THIN);
//        headStyle.setBorderRight(BorderStyle.THIN);
        headStyle.setAlignment(HorizontalAlignment.CENTER);
        headStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
        headStyle.setWrapText(true);
//        DefaultExcelStyle defaultExcelStyle = new DefaultExcelStyle();
//        headStyle.setFillPattern(defaultExcelStyle.getFillPattern());
        headStyle.setWrapText(true);

    }

}
