package com.yami.shop.utils;

import com.google.common.collect.Maps;
import com.yami.shop.common.exception.GlobalException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * 导出工具类
 * @author zx
 * @date 2015-12-12 00:00:00
 */
public class ExportUtils {

    /**
     * 创建合并单元格的表头（模拟模板中的"正常订单"标题）
     */
    public static void createMergedHeader(Sheet sheet, CellStyle headerStyle,String headerName) {
        // 第一行：主标题
        Row titleRow = sheet.createRow(0);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue(headerName);
        titleCell.setCellStyle(headerStyle);

        // 合并A1到R1单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 17));

        // 设置行高
        titleRow.setHeightInPoints(25);
    }

    /**
     * 设置HTTP响应头
     */
    public static void setupResponse(HttpServletResponse response, String fileName) {
        try {
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8")
                    .replaceAll("\\+", "%20");

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition",
                    "attachment; filename*=UTF-8''" + encodedFileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");

        } catch (Exception e) {
            throw new RuntimeException("设置响应头失败", e);
        }
    }
    /**
     * 创建列标题行
     */
    public static  void createColumnHeaders(Sheet sheet, CellStyle headerStyle,String[] headers) {
        Row headerRow = sheet.createRow(1);
        headerRow.setHeightInPoints(20);

//        String[] headers = {
//                "订单编号", "下单时间", "付款时间", "订单状态", "订单类型",
//                "商品名称", "规格", "单价(元)", "数量", "小计(元)",
//                "商品总数量", "商品总额(元)", "运费(元)", "积分抵扣(元)",
//                "实付金额", "所属企业", "买家姓名", "买家电话"
//        };

        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }
    }

    /**
     * 创建单元格（字符串类型）
     */
    public static void createCell(Sheet sheet,Row row,int col, int size,int rowNum, String value, CellStyle style) {
        int lastRow = rowNum + size - 1;
        if (lastRow > rowNum) {
            if (!isMergeRegionOverlap(sheet, rowNum-1, lastRow-1, col)){ //因为索引是从0开始的  所以开始行和结束行都需要减1
                CellRangeAddress cellAddresses = new CellRangeAddress(rowNum - 1, lastRow - 1, col, col);
                sheet.addMergedRegion(cellAddresses);
                setMergedRegionBorder(sheet,cellAddresses);
            }
        }
        Cell cell = row.createCell(col);
        cell.setCellValue(value != null ? value : "");
        cell.setCellStyle(style);

    }

    /**
     * 创建单元格（数字类型）
     */
    public static void createCell(Sheet sheet, Row row, int col, int size, int rowNum, BigDecimal value, CellStyle style) {
        int lastRow = rowNum + size - 1;
        if (lastRow > rowNum) {
            if (!isMergeRegionOverlap(sheet, rowNum-1, lastRow-1, col)){
                CellRangeAddress cellAddresses = new CellRangeAddress(rowNum - 1, lastRow - 1, col, col);
                sheet.addMergedRegion(cellAddresses);
                setMergedRegionBorder(sheet,cellAddresses);
            }
        }
        Cell cell = row.createCell(col);
        if (value != null) {
            cell.setCellValue(value.doubleValue());
        } else {
            cell.setCellValue(0);
        }
        cell.setCellStyle(style);
    }
    /**
     * 创建单元格（数字类型）
     */
    public static void createCell(Sheet sheet,Row row,int col, int size,int rowNum, double value, CellStyle style) {
        int lastRow = rowNum + size - 1;
        if (lastRow > rowNum) {
            if (!isMergeRegionOverlap(sheet, rowNum-1, lastRow-1, col)){
                CellRangeAddress cellAddresses = new CellRangeAddress(rowNum - 1, lastRow - 1, col, col);
                sheet.addMergedRegion(cellAddresses);
                setMergedRegionBorder(sheet,cellAddresses);
            }
        }
        Cell cell = row.createCell(col);
        cell.setCellValue(value);
        cell.setCellStyle(style);
    }

    /**
     * 创建单元格（整数类型）
     */
    public static void createCell(Sheet sheet,Row row,int col, int size,int rowNum,  Integer value, CellStyle style) {
        int lastRow = rowNum + size - 1;
        if (lastRow > rowNum) {
            if (!isMergeRegionOverlap(sheet, rowNum-1, lastRow-1, col)){
                CellRangeAddress cellAddresses = new CellRangeAddress(rowNum - 1, lastRow - 1, col, col);
                sheet.addMergedRegion(cellAddresses);
                setMergedRegionBorder(sheet,cellAddresses);
            }
        }
        Cell cell = row.createCell(col);
        if (value != null) {
            cell.setCellValue(value);
        } else {
            cell.setCellValue(0);
        }
        cell.setCellStyle(style);
    }

    /**
     * 创建表头样式
     */
    public static CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        // 字体设置
        Font font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 11);
        font.setColor(IndexedColors.WHITE.getIndex());
        style.setFont(font);

        // 背景色 - 深蓝色
        style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 对齐方式
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 边框
        setBorderStyle(style);

        return style;
    }

    /**
     * 创建数据样式
     */
    public static CellStyle createDataStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 10);
        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        setBorderStyle(style);

        return style;
    }

    /**
     * 创建数字样式
     */
    public static CellStyle createNumberStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 10);
        style.setFont(font);

        style.setAlignment(HorizontalAlignment.RIGHT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 数字格式：保留2位小数
        DataFormat format = workbook.createDataFormat();
        style.setDataFormat(format.getFormat("0.00"));
        setBorderStyle(style);

        return style;
    }

    /**
     * 创建日期样式
     */
    public static CellStyle createDateStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();

        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 10);
        style.setFont(font);

        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        // 日期格式
        DataFormat format = workbook.createDataFormat();
        style.setDataFormat(format.getFormat("yyyy-MM-dd HH:mm"));
        setBorderStyle(style);

        return style;
    }

    /**
     * 设置边框样式
     */
    public static void setBorderStyle(CellStyle style) {
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
        style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
    }
    /**
     * 为合并区域设置边框样式
     */
    public static void setMergedRegionBorder(Sheet sheet, CellRangeAddress mergedRegion) {
        int firstRow = mergedRegion.getFirstRow();
        int lastRow = mergedRegion.getLastRow();
        int firstCol = mergedRegion.getFirstColumn();
        int lastCol = mergedRegion.getLastColumn();

        // 为合并区域的每个单元格设置特定边框
        for (int row = firstRow; row <= lastRow; row++) {
            for (int col = firstCol; col <= lastCol; col++) {
                Row sheetRow = sheet.getRow(row);
                if (sheetRow == null) {
                    sheetRow = sheet.createRow(row);
                }
                Cell cell = sheetRow.getCell(col);
                if (cell == null) {
                    cell = sheetRow.createCell(col);
                }

                CellStyle borderStyle = sheet.getWorkbook().createCellStyle();

                // 设置左边框（只有最左侧单元格）
                if (col == firstCol) {
                    borderStyle.setBorderLeft(BorderStyle.THIN);
                    borderStyle.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
                }

                // 设置右边框（只有最右侧单元格）
                if (col == lastCol) {
                    borderStyle.setBorderRight(BorderStyle.THIN);
                    borderStyle.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
                }

                // 设置上边框（只有最上方单元格）
                if (row == firstRow) {
                    borderStyle.setBorderTop(BorderStyle.THIN);
                    borderStyle.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
                }

                // 设置下边框（只有最下方单元格）
                if (row == lastRow) {
                    borderStyle.setBorderBottom(BorderStyle.THIN);
                    borderStyle.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
                }
                // 如果是左上角单元格，设置居中
                if (row == firstRow && col == firstCol) {
                    setCenterAlignment(borderStyle);
                    // 可选：设置自动换行
//                    borderStyle.setWrapText(true);
                }

                cell.setCellStyle(borderStyle);
            }
        }
    }
    /**
     * 设置居中对齐
     */
    public static void setCenterAlignment(CellStyle style) {
        // 水平居中
        style.setAlignment(HorizontalAlignment.CENTER);
        // 垂直居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
    }
    /**
     * 格式化日期
     */
    public static String formatDate(Date date) {
        if (date == null) return "";

        // 使用java.time格式化（Java 8+）
        return java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
                .format(date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime());
    }
    /**
     * 检查合并区域是否重叠
     */
    public static boolean isMergeRegionOverlap(Sheet sheet, int startRow, int endRow, int column) {
        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
            CellRangeAddress existingRegion = sheet.getMergedRegion(i);
            if (existingRegion.getFirstColumn() == column &&
                    existingRegion.getLastColumn() == column) {
                // 检查行重叠
                if (!(endRow < existingRegion.getFirstRow() || startRow > existingRegion.getLastRow())) {
                    return true; // 存在重叠
                }
            }
        }
        return false;
    }

}
