package com.ruoyi.postCheck.util.excel.create;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.postCheck.domain.PostChecked;
import com.ruoyi.postCheck.domain.PostCheckedItems;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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


@Component
public class PostCheckedCreateExcel {

    @Autowired
    private RuoYiConfig ruoYiConfig;

//    @Value("${ruoyi.profile}")
//    public String url; //profile: c:/gnhz/uploadPath
//    String filePath = path + File.separator + "exportFiles" + File.separator + fileName + ".xls";

    /**
     * 获取文件磁盘路径 含最后的斜杠
     *
     * @return
     */
//    private String getPathDisk() {
//        String profile = ruoYiConfig.getProfile();
//        String path = profile + File.separator + "exportFiles" + File.separator;
//        System.out.println("文件磁盘路径 = " + path);
//        return path;
//    }


    /**
     * 相对路径
     *
     * @return
     */
//    private String getPathDiskRelative() {
//        String path = File.separator + "exportFiles" + File.separator;
//        System.out.println("文件相对路径 = " + path);
//        return path;
//    }

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

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

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

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

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

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

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

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

    /**
     * 岗检表导出 Excel
     * <p>
     *
     * @param children 需要要导出的数据
     * @return 文件名称含后缀不含路径 例如：xxx岗位检查表.xls
     */
    public String createExcel(PostChecked postChecked, List<PostCheckedItems> children) {
        String checkedDeptName = postChecked.getCheckedDeptName();
        String checkedPostName = postChecked.getCheckedPostName();
        String fileName = checkedDeptName + "-" + checkedPostName + "-岗位检查表" + "_" + DateUtils.dateTimeNow() + new Random().nextInt(100000);

        String sheetName = "岗位检查表";


        /** 第一步，创建一个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-办公室主任");
                tempCellOne.setCellValue(checkedDeptName + "-" + checkedPostName);
            } else if (i == 5) {
                tempCellOne.setCellStyle(headerStyleOne);
                tempCellOne.setCellValue("被检查人签字");
            } else if (i == 6) {
                tempCellOne.setCellStyle(headerStyleOneContent);
//                tempCellOne.setCellValue("data-周三");
                tempCellOne.setCellValue("");
            } 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-张三丰");
                tempCell.setCellValue("");
            }
        }
        // 合并
        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<>();
//        System.out.println("=========================");
//        for (PostCheckedItems data : getselectTo) {
//            System.out.println("data.getSerialNumber() = " + data.getSerialNumber());
//        }

        Collections.sort(children, new Comparator<PostCheckedItems>() {
            @Override
            public int compare(PostCheckedItems o1, PostCheckedItems o2) {
                Integer s1 = o1.getSerialNumber() != null ? o1.getSerialNumber() : 0;
                Integer s2 = o2.getSerialNumber() != null ? o2.getSerialNumber() : 0;
                return s1 - s2;
            }
        });

//        System.out.println("=========================");
//        for (PostCheckedItems data : getselectTo) {
//            System.out.println("data.getSerialNumber() = " + data.getSerialNumber());
//        }

        for (PostCheckedItems data : children) {
            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() != null ? data.getSerialNumber().toString() : "";
                }
                // 检查项目
                else if (j == 1) {
                    tempValue = data.getTypeView() != null ? data.getTypeView() : "";
                }
                // 检查内容
                else if (j == 2) {
                    tempValue = data.getPostCheckedContent() != null ? data.getPostCheckedContent() : "";
                }
                // 检查标准
                else if (j == 3) {
                    tempValue = data.getPostCheckedStandard() != null ? data.getPostCheckedStandard() : "";
                    sheet.addMergedRegion(new CellRangeAddress(rowStartIndex, rowStartIndex++, 3, 4));
                }
                // 检查方法
                else if (j == 5) {
                    tempValue = data.getPostCheckedMethod() != null ? data.getPostCheckedMethod() : "";
                }
                // 检查结果
                else if (j == 6) {
                    tempValue = data.getPostCheckedResult() != null ? 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));
                if (lastValue > 1)
                    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));
        if (lastValue > 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 (Exception e) {
            e.printStackTrace();
        }
//        return File.separator + "download" + File.separator + fileName + ".xls";
        return fileName + ".xls";
    }

    //把文件写到磁盘上
    public void downloadExcel(HSSFWorkbook wb, String fileName) throws IOException {
        OutputStream out = null;
        try {
            String downloadPath = ruoYiConfig.getDownloadPath();
            File downloadPathFile = new File(downloadPath);
            if (!downloadPathFile.exists()) {
                downloadPathFile.mkdirs();
            }
            out = new FileOutputStream(new File(downloadPath + fileName));
            wb.write(out);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                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;
    }


}
