package com.bonus.hn.bearing.capacity.backstage.manager.utils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;


/**
 * 导出表格工具类
 *
 * @author lvjilong
 */
public class MergeExcelUtils {

    /**
     * excel默认宽度；
     */
    private static int width = 256 * 14;
    /**
     * 默认字体
     */
    private static String excelfont = "微软雅黑";



    /**
     * 当前行号
     */
    private static int rownum;
    /**
     * 样式列表
     */
    private static Map<String, CellStyle> styles;

    /**
     * 标题
     */
    private String title;

    /**
     * @param excelName 导出的EXCEL名字
     * @param sheetName 导出的SHEET名字  当前sheet数目只为1
     * @param headers   导出的表格的表头
     * @param ds_titles 导出的数据 map.get(key) 对应的 key
     * @param ds_format 导出数据的样式
     *                  1:String left;
     *                  2:String center
     *                  3:String right
     *                  4 int  right
     *                  5:float ###,###.## right
     *                  6:number: #.00% 百分比 right
     * @param widths    表格的列宽度  默认为 256*14
     * @param data      数据集  List<Map>
     * @param response
     * @throws IOException
     */
    public static void export(String excelName, String sheetName, String[] headers, String[] ds_titles, int[] ds_format, int[] widths, List<Map<String, Object>> data, HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
        session.setAttribute("state", null);
        if (widths == null) {
            widths = new int[ds_titles.length];
            for (int i = 0; i < ds_titles.length; i++) {
                widths[i] = width;
            }
        }
        if (ds_format == null) {
            ds_format = new int[ds_titles.length];
            for (int i = 0; i < ds_titles.length; i++) {
                ds_format[i] = 1;
            }
        }
        //设置文件名
        String fileName = "";
        if (StringHelper.isNotEmpty(excelName)) {
            fileName = excelName;
        }
        //创建一个工作薄
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建一个sheet
        HSSFSheet sheet = wb.createSheet(StringHelper.isNotEmpty(sheetName) ? sheetName : "excel");
        //创建表头，如果没有跳过
        Row titleRow = sheet.createRow(rownum == 0 ? rownum++ : 0);
        titleRow.setHeightInPoints(30);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue(sheetName);
        CellRangeAddress cra =new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), headers.length-1);
        titleCell.setCellStyle(getStyleTitle(wb));
        sheet.addMergedRegion(cra);
        int headerrow = 1;
        if (headers != null) {
            HSSFRow row = sheet.createRow(headerrow);
            //表头样式
            HSSFCellStyle style = wb.createCellStyle();
            HSSFFont font = wb.createFont();
            font.setBold(true);
            font.setFontName(excelfont);
            font.setFontHeightInPoints((short) 11);
            style.setFont(font);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setWrapText(true);
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            style.setBorderTop(BorderStyle.THIN);
            for (int i = 0; i < headers.length; i++) {
                sheet.setColumnWidth((short) i, (short) widths[i]);
                HSSFCell cell = row.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(style);
            }
            headerrow++;
        }
        //表格主体  解析list
        if (data != null) {
            // 根据工程名称对数据进行分组
            Map<String, List<Map<String, Object>>> groupedData = new LinkedHashMap<>();
            for (Map<String, Object> entry : data) {
                String projectName = (String) entry.get("工程名称");
                groupedData.computeIfAbsent(projectName, k -> new ArrayList<>()).add(entry);
            }
            // 如果有表头则从第二行开始，否则从第一行开始
             headerrow = headers != null ? 2 : 1;

            List<HSSFCellStyle> styleList = new ArrayList<>();
            // ... 创建单元格样式逻辑 ...

            // 遍历分组后的数据，合并同类项
            for (String projectName : groupedData.keySet()) {
                List<Map<String, Object>> projectDataList = groupedData.get(projectName);
                // 计算该工程名称下的行数
                int projectRowCount = projectDataList.size();

                for (int i = 0; i < projectRowCount; i++) {
                    HSSFRow row = sheet.createRow(headerrow);
                    Map<String, Object> projectData = projectDataList.get(i);

                    for (int j = 0; j < ds_titles.length; j++) {
                        HSSFCell cell = row.createCell(j);
                        Object value = projectData.get(ds_titles[j]);

                        // 根据不同的数据格式设置单元格值
                        if (value instanceof String) {
                            cell.setCellValue((String) value);
                        } else if (value instanceof Integer && ds_format[j] == 4) {
                            cell.setCellValue((Integer) value);
                        } else if (value instanceof Double) {
                            if (ds_format[j] == 5 || ds_format[j] == 6){
                                cell.setCellValue((Double) value);
                            }
                        } else if (value != null) {
                            cell.setCellValue(value.toString());
                        } else {
                            cell.setCellValue("");
                        }

                        // 应用预先创建的单元格样式
                        cell.setCellStyle(styleList.get(j));
                    }

                    // 如果是第一行数据，则合并工程名称单元格
                    if (i == 0 && projectRowCount > 1) {
                        // 获取工程名称的列索引
                        int projectIndex = Arrays.asList(ds_titles).indexOf("工程名称");
                        // 如果找到了工程名称的列
                        if(projectIndex >= 0) {
                            sheet.addMergedRegion(new CellRangeAddress(headerrow, headerrow + projectRowCount - 1, projectIndex, projectIndex));
                        }
                    }
                    headerrow++;
                }
            }
        }

        fileName = fileName + ".xls";
        String filename = "";
        try {
            filename = encodeChineseDownloadFileName(request, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition", filename);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + filename);
        response.setHeader("Pragma", "No-cache");
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
        wb.close();
    }

    /**
     * 对文件流输出下载的中文文件名进行编码 屏蔽各种浏览器版本的差异性
     *
     * @throws UnsupportedEncodingException
     */
    public static String encodeChineseDownloadFileName(
            HttpServletRequest request, String pFileName) throws Exception {
        String filename = null;
        String agent = request.getHeader("USER-AGENT");
        if (null != agent) {
            //IE浏览器
            if (StringHelper.contains(agent, "MSIE") || StringHelper.contains(agent, "like Gecko")) {
                filename = URLEncoder.encode(pFileName, "UTF-8");
            } else if (StringHelper.contains(agent, "Mozilla")) {
                //google,火狐浏览器
                filename = new String(pFileName.getBytes(), "ISO8859-1");
            } else {
                //其他
                filename = URLEncoder.encode(pFileName, "UTF-8");
            }
        } else {
            filename = pFileName;
        }
        return filename;
    }
    /**
     * 标题样式
     */
    public static HSSFCellStyle getStyleTitle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short)15);
        //字体加粗
        font.setBold(true);
        //设置字体名字
        font.setFontName(excelfont);
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();

        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setWrapText(true);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        return style;

    }

}  