package com.post.excel.create;

import com.ruoyi.common.utils.DateUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 原文：https://blog.csdn.net/qq_42612200/article/details/105860179
 * https://www.cnblogs.com/luckyang/p/14637076.html
 * 样式：https://www.cnblogs.com/fqfanqi/p/6172223.html
 */
public class PostCheckedExcelUtil {

    public static void main(String[] args) throws Exception {
        List<PostCheckBean> getselectTo = new ArrayList<>();

        int index = 1;
        for (int i = 0; i <= 2; i++) {
            PostCheckBean data = new PostCheckBean(index++, 6);
            getselectTo.add(data);
        }

        for (int i = 0; i <= 2; i++) {
            PostCheckBean data = new PostCheckBean(index++, 5);
            getselectTo.add(data);
        }

        for (int i = 0; i <= 2; i++) {
            PostCheckBean data = new PostCheckBean(index++, 1);
            getselectTo.add(data);
        }

        for (int i = 0; i <= 2; i++) {
            PostCheckBean data = new PostCheckBean(index++, 2);
            getselectTo.add(data);
        }

        for (int i = 0; i <= 2; i++) {
            PostCheckBean data = new PostCheckBean(index++, 3);
            getselectTo.add(data);
        }

        for (int i = 0; i <= 2; i++) {
            PostCheckBean data = new PostCheckBean(index++, 4);
            getselectTo.add(data);
        }

        run("人力资源部岗位经理检查表-" + DateUtils.dateTimeNow(), "岗位检查表", getselectTo);
    }

    /**
     * 导出 Excel
     *
     * @param fileName    导出时的文件名称
     * @param sheetName   工作簿名字
     * @param getselectTo 需要要导出的数据
     */

    public static void run(String fileName, String sheetName, List<PostCheckBean> getselectTo) {

        /** 第一步，创建一个Workbook，对应一个Excel文件  */
        HSSFWorkbook wb = new HSSFWorkbook();

        /** 第二步，在Workbook中添加一个sheet,对应Excel文件中的sheet  */
        HSSFSheet sheet = wb.createSheet(sheetName);

        /** 第三步，设置样式以及字体样式*/
        //标题样式
        HSSFCellStyle titleStyleOne = createTitleCellStyleOne(wb);

        HSSFCellStyle titleStyle = createTitleCellStyle(wb);
        //创建表头样式
        HSSFCellStyle headerStyleOne = createHeadCellStyleOne(wb);
        HSSFCellStyle headerStyleOneContent = createHeadCellStyleOneContent(wb);
        HSSFCellStyle headerStyle = createHeadCellStyle(wb);
        //内容样式
        HSSFCellStyle contentStyle = createContentCellStyle(wb);
        //		日期格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        //设置全局 单元格  默认 宽度
        sheet.setDefaultColumnWidth(12);

        /** 第四步，创建标题 ,合并标题单元格 */
        // 行号
        int rowNum = 0;
        // 创建第一页的第一行，索引从0开始
        HSSFRow row0 = sheet.createRow(rowNum++);
        row0.setHeight((short) 800);// 设置行高


        HSSFCell c00 = row0.createCell(0);
        c00.setCellStyle(titleStyleOne);
        c00.setCellValue("岗位责任制检查表");
        // 合并单元格，参数依次为：起始行，结束行，起始列，结束列 （索引0开始）
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));//标题合并单元格操作，17为总列数


        // 第二行
        HSSFRow row1 = sheet.createRow(rowNum++);
        row1.setHeight((short) 800);
        for (int i = 0; i < 7; i++) {
            HSSFCell tempCellOne = row1.createCell(i);
            if (i == 0) {
                tempCellOne.setCellStyle(headerStyleOne);
                tempCellOne.setCellValue("检查时间");
            } else if (i == 2) {
                tempCellOne.setCellStyle(headerStyleOneContent);
                tempCellOne.setCellValue("     年   月   日");
            } else if (i == 3) {
                tempCellOne.setCellStyle(headerStyleOne);
                tempCellOne.setCellValue("检查部门及岗位");
            } else if (i == 4) {
                tempCellOne.setCellStyle(headerStyleOneContent);
                tempCellOne.setCellValue("data-办公室主任");
            } else if (i == 5) {
                tempCellOne.setCellStyle(headerStyleOne);
                tempCellOne.setCellValue("被检查人签字");
            } else if (i == 6) {
                tempCellOne.setCellStyle(headerStyleOneContent);
                tempCellOne.setCellValue("data-周三");
            } else {
                tempCellOne.setCellStyle(headerStyleOne);
            }
        }
        // 合并
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 1));


        // 第三行
        HSSFRow row2 = sheet.createRow(rowNum++);
        row2.setHeight((short) 800);
        for (int i = 0; i < 7; i++) {

            HSSFCell tempCell = row2.createCell(i);
            tempCell.setCellStyle(headerStyleOne);

            if (i == 0) {
                tempCell.setCellValue("检查人签字：");
            }
            if (i == 1) {
                tempCell.setCellValue("data-张三丰");
            }
        }
        // 合并
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 1));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 2, 6));


        // 第4行：标题
        HSSFRow rowData = sheet.createRow(rowNum++);
        rowData.setHeight((short) 560);
        for (int i = 0; i <= 6; i++) {
            HSSFCell tempCell = rowData.createCell(i);
            tempCell.setCellStyle(headerStyle);
            if (i == 0) {
                tempCell.setCellValue("序号");
            } else if (i == 1) {
                tempCell.setCellValue("检查项目");
            } else if (i == 2) {
                tempCell.setCellValue("检查内容");
            } else if (i == 3) {
                tempCell.setCellValue("检查标准");
                sheet.addMergedRegion(new CellRangeAddress(i, i, 3, 4));
            } else if (i == 5) {
                tempCell.setCellValue("检查方法");
            } else if (i == 6) {
                tempCell.setCellValue("检查结果");
            }
        }

        // 第5行+：数据
        //B列纵向合并单元格
        //C列纵向合并单元格
        int rowStartIndex = 4;

        //检查项目：记录上一次的，合并单元格
//        Integer typeLast = null;

        LinkedHashMap<Integer, Integer> typeLastMap = new LinkedHashMap<>();

        for (PostCheckBean data : getselectTo) {
            HSSFRow tempRow = sheet.createRow(rowNum++);
//            tempRow.setHeight((short) 2000);
            // 循环单元格填入数据
            for (int j = 0; j <= 6; j++) {
                HSSFCell tempCell = tempRow.createCell(j);
                tempCell.setCellStyle(contentStyle);


                String tempValue = null;
                //序号
                if (j == 0) {
                    tempValue = data.getSerialNumber().toString();
                }
                // 检查项目
                else if (j == 1) {
                    tempValue = data.getTypeView();
                }
                // 检查内容
                else if (j == 2) {
                    tempValue = data.getPostCheckedContent() + "";
                }
                // 检查标准
                else if (j == 3) {
                    tempValue = data.getPostCheckedStandard() + "";
                    sheet.addMergedRegion(new CellRangeAddress(rowStartIndex, rowStartIndex++, 3, 4));
                }
                // 检查方法
                else if (j == 5) {
                    tempValue = data.getPostCheckedMethod() + "";
                }
                // 检查结果
                else if (j == 6) {
                    tempValue = data.getPostCheckedResult() + "";
                }
                tempCell.setCellValue(tempValue);
            }

            //当前记录的检查项目
            Integer type = data.getType();
            //第一行
            if (typeLastMap.isEmpty()) {
                typeLastMap.put(type, 1);//该分类的行数 = 1
            }
            //同类型
            else if (typeLastMap.containsKey(type)) {
                typeLastMap.put(type, typeLastMap.get(type) + 1);//该分类的行数 + 1
            }
            //新的分类
            else {
                // 获取最后一个元素
                Integer lastKey = null;
                Integer lastValue = null;
                for (Map.Entry<Integer, Integer> entry : typeLastMap.entrySet()) {
                    lastKey = entry.getKey();
                    lastValue = entry.getValue();
                }
//                System.out.println("上个分类 -> " + lastKey + " 上个分类的行数 -> " + lastValue);
//                System.out.println("开始行 -> " + ((rowStartIndex - 1) - lastValue) + " 结束行 -> " + (rowStartIndex - 2));
                sheet.addMergedRegion(new CellRangeAddress((rowStartIndex - 1) - lastValue, rowStartIndex - 2, 1, 1));//纵向合并单元格
                typeLastMap.put(type, 1);//该分类的行数 = 1
            }
        }

        // 获取最后一个元素
        Integer lastKey = null;
        Integer lastValue = null;
        for (Map.Entry<Integer, Integer> entry : typeLastMap.entrySet()) {
            lastKey = entry.getKey();
            lastValue = entry.getValue();
        }
//        System.out.println("上个分类 -> " + lastKey + " 上个分类的行数 -> " + lastValue);
//        System.out.println("开始行 -> " + ((rowStartIndex - 0) - lastValue) + " 结束行 -> " + (rowStartIndex - 1));
        sheet.addMergedRegion(new CellRangeAddress((rowStartIndex - 0) - lastValue, rowStartIndex - 1, 1, 1));//纵向合并单元格

//        A 5.63
//        B 10.75
//        C 21.13
//        D 22.38
//        E 18.75
//        F 27.63
//        G 28.88
        sheet.setColumnWidth(0, 5 * 256);
        sheet.setColumnWidth(1, 11 * 256);
        sheet.setColumnWidth(2, 21 * 256);
        sheet.setColumnWidth(3, 22 * 256);
        sheet.setColumnWidth(4, 19 * 256);
        sheet.setColumnWidth(5, 27 * 256);
        sheet.setColumnWidth(6, 29 * 256);

        try {
            //调用下载     导出
            downloadExcel(wb, fileName + ".xls");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    //下载
    public static void downloadExcel(HSSFWorkbook wb, String fileName) throws IOException {
//        response.reset();
//        response.setContentType("application/vnd.ms-excel;charset=utf-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName).getBytes(), "iso-8859-1"));

        OutputStream out = null;
        try {
            int index = fileName.lastIndexOf(".");

            String fileNamePrefix = "岗位检查表";
            String fileNameSuffix = ".xls";
            if (index > -1) {
                fileNamePrefix = fileName.substring(0, index);
                fileNameSuffix = fileName.substring(index);
            }

            out = new FileOutputStream(new File("C:\\test\\" + fileNamePrefix + fileNameSuffix));
            wb.write(out);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }

    }


    /**
     * 创建标题样式
     *
     * @param wb
     * @return
     */
    private static HSSFCellStyle createTitleCellStyleOne(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());//背景颜色

        HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont1.setBold(true); //字体加粗
        headerFont1.setFontName("黑体"); // 设置字体类型
        headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小
        cellStyle.setFont(headerFont1); // 为标题样式设置字体样式

        return cellStyle;
    }

    /**
     * 创建标题样式
     *
     * @param wb
     * @return
     */
    private static HSSFCellStyle createTitleCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//        cellStyle.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());//背景颜色

        HSSFFont headerFont1 = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont1.setBold(true); //字体加粗
        headerFont1.setFontName("黑体"); // 设置字体类型
        headerFont1.setFontHeightInPoints((short) 15); // 设置字体大小
        cellStyle.setFont(headerFont1); // 为标题样式设置字体样式

        return cellStyle;
    }


    /**
     * 创建表头样式
     *
     * @param wb
     * @return
     */
    private static HSSFCellStyle createHeadCellStyleOne(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setWrapText(true);// 设置自动换行
//        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//背景颜色
//        cellStyle.setAlignment(HorizontalAlignment.LEFT); //水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框

        HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont.setBold(true); //字体加粗
        headerFont.setFontName("宋体"); // 设置字体类型
        headerFont.setFontHeightInPoints((short) 12); // 设置字体大小
        cellStyle.setFont(headerFont); // 为标题样式设置字体样式

        return cellStyle;
    }

    /**
     * 创建表头样式
     *
     * @param wb
     * @return
     */
    private static HSSFCellStyle createHeadCellStyleOneContent(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setWrapText(true);// 设置自动换行
//        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//背景颜色
//        cellStyle.setAlignment(HorizontalAlignment.LEFT); //水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框

        HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont.setBold(false); //字体加粗
        headerFont.setFontName("宋体"); // 设置字体类型
        headerFont.setFontHeightInPoints((short) 12); // 设置字体大小
        cellStyle.setFont(headerFont); // 为标题样式设置字体样式


        return cellStyle;
    }

    /**
     * 创建表头样式
     *
     * @param wb
     * @return
     */
    private static HSSFCellStyle createHeadCellStyle(HSSFWorkbook wb) {
        //自定义背景颜色，覆盖POI的默认值
        HSSFPalette palette = wb.getCustomPalette();  //wb HSSFWorkbook对象
        palette.setColorAtIndex((short)22, (byte) (0xff & 231), (byte) (0xff & 230), (byte) (0xff & 230));


        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setWrapText(true);// 设置自动换行
        cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());//背景颜色

//        cellStyle.setAlignment(HorizontalAlignment.LEFT); //水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //垂直对齐
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.index);
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框

        HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
        headerFont.setBold(true); //字体加粗
        headerFont.setFontName("黑体"); // 设置字体类型
        headerFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellStyle.setFont(headerFont); // 为标题样式设置字体样式

        return cellStyle;
    }


    /**
     * 创建内容样式
     *
     * @param wb
     * @return
     */
    private static HSSFCellStyle createContentCellStyle(HSSFWorkbook wb) {
        HSSFCellStyle cellStyle = wb.createCellStyle();
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);// 垂直居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);// 水平居中
        cellStyle.setWrapText(true);// 设置自动换行
        cellStyle.setBorderBottom(BorderStyle.THIN); //下边框
        cellStyle.setBorderLeft(BorderStyle.THIN); //左边框
        cellStyle.setBorderRight(BorderStyle.THIN); //右边框
        cellStyle.setBorderTop(BorderStyle.THIN); //上边框


        // 生成12号字体
        HSSFFont font = wb.createFont();
        font.setColor((short) 8);
        font.setFontHeightInPoints((short) 12);
        cellStyle.setFont(font);

        return cellStyle;
    }


}
