package com.fkzy.warn.common.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fkzy.warn.common.constants.ReportConstants;
import com.fkzy.warn.model.*;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhangjing
 * @date 2024/12/15 19:42
 * @description
 */
public class ReportUtil {
    static final String[] stages = {"一审", "二审", "再审审查", "再审", "执行", "审结"};
    public static void createReport(ReportModel reportModel) {
        // 指定现有Word文档的路径
        String inputFilePath = "司法风险报告demo.docx";
        // 指定保存修改后文档的路径
        String outputFilePath = "司法风险报告.docx";
        ZipSecureFile.setMinInflateRatio(0.001);
        OPCPackage opcPackage;
        try {
            opcPackage = POIXMLDocument.openPackage(inputFilePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        XWPFDocument xwpfDocument;
        try {
            xwpfDocument = new XWPFDocument(opcPackage);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        List<XWPFParagraph> xwpfParas = xwpfDocument.getParagraphs();
        for (int i = 0; i < xwpfParas.size(); i++) {
            XWPFParagraph xwpfParagraph = xwpfParas.get(i);
            String text = xwpfParagraph.getText();
            switch (text) {
                case ReportConstants.BACKGROUND_JUDICIAL:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getBackgroundJudicial());
                    break;
                case ReportConstants.BASIC_ENTERPRISE:
                    tableBasicEnterprise(xwpfParagraph, xwpfDocument, reportModel.getBasicEnterprise());
                    break;
                case ReportConstants.THREE_MONTHS_TEXT1:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getThreeMonthsText1());
                    break;
                case ReportConstants.THREE_MONTHS_TABLE1:
                    threeMonthsTable1(xwpfParagraph, xwpfDocument, reportModel.getThreeMonthsCases());
                    break;
                case ReportConstants.THREE_MONTHS_TEXT2:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getThreeMonthsText2());
                    break;
                case ReportConstants.THREE_MONTHS_TEXT3:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getThreeMonthsText3());
                    break;
                case ReportConstants.THREE_MONTHS_TABLE3:
                    threeMonthsTable3(xwpfParagraph, xwpfDocument, reportModel.getThreeMonthsCases());
                    break;
                case ReportConstants.CASE_STAGE_TEXT1:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getCaseStageText1());
                    break;
                case ReportConstants.LOCATION_TEXT:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getLocationText());
                    break;
                case ReportConstants.CASE_ACTION_TEXT1:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getCaseActionText1());
                    break;
                case ReportConstants.CASE_ACTION_TABLE1:
                    caseActionTable1(xwpfParagraph, xwpfDocument, reportModel.getThreeYearsCases());
                    break;
                case ReportConstants.CASE_ACTION_TEXT2:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getCaseActionText2());
                    break;
                case ReportConstants.AMOUNT_INVOLVED_TEXT:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getAmountInvolvedText());
                    break;
                case ReportConstants.LITIGATION_STATUS_TEXT:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getLitigationStatusText());
                    break;
                case ReportConstants.MAJOR_CASE_TEXT:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getMajorCaseText());
                    break;
                case ReportConstants.HIGH_FREQUENCY_TEXT:
                    paragraph(xwpfParagraph, xwpfDocument, reportModel.getHighFrequencyText());
                    break;
            }
            //插入图片
//            if(text.equals("${mark_newPicture}")){
//
//                XmlCursor cursor = xwpfParagraph .getCTP().newCursor();
//                XWPFParagraph newPara = xwpfDocument.insertNewParagraph(cursor);
//                newPara.setAlignment(ParagraphAlignment.CENTER);//居中
//                XWPFRun newParaRun = newPara.createRun();
//                newParaRun.addPicture(new FileInputStream("./doc/bus.png"),XWPFDocument.PICTURE_TYPE_PNG,"bus.png,",Units.toEMU(200), Units.toEMU(200));
//                xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));
//            }
        }

        write(xwpfDocument, outputFilePath);
    }

    private static void paragraph(XWPFParagraph xwpfParagraph, XWPFDocument xwpfDocument,
                                  String content) {
        XmlCursor cursor = xwpfParagraph.getCTP().newCursor();
        XWPFParagraph newPara = xwpfDocument.insertNewParagraph(cursor);
        //两端对齐
        newPara.setAlignment(ParagraphAlignment.BOTH);
        //首行缩进24磅
        newPara.setIndentationFirstLine(500);
        XWPFRun newParaRun = newPara.createRun();
        newParaRun.setText(content);
        newParaRun.setFontFamily("宋体");
        //四号字体
        newParaRun.setFontSize(15);
        newParaRun.setBold(false);
        xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));
    }


    /**
     * 一，司法体检背景
     *
     * @param enterpriseInfo
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/17
     **/
    public static String backgroundJudicial(EnterpriseInfo enterpriseInfo) {
        StringBuilder result = new StringBuilder();
        result.append("图灵高斯依托人民法院大数据管理服务平台与“供应链司法人工智能联合创新中心”，通过大数据挖掘，助力企业实时、全面掌握涉诉风险，为企业监管提供有力支撑。企业名称：")
            .append(enterpriseInfo.getENTNAME())
            .append("，社会统一信用代码：")
            .append(enterpriseInfo.getCREDITCODE())
            .append("。所采用的数据为生成本报告时（截止2024年7月23日9时）人民法院大数据管理和服务平台最新数据。本报告的统计口径为2024年1月1日0时至2024年7月23日9时期间的新发与结转案件。");
        return result.toString();
    }

    /**
     * 二、企业基本信息
     *
     * @param xwpfParagraph
     * @param xwpfDocument
     * @param enterpriseInfo
     * @return void
     * @author zhangjing
     * @create 2024/12/17
     **/
    private static void tableBasicEnterprise(XWPFParagraph xwpfParagraph, XWPFDocument xwpfDocument,
                                             EnterpriseInfo enterpriseInfo) {
        XmlCursor cursor = xwpfParagraph.getCTP().newCursor();
        XWPFTable table = xwpfDocument.insertNewTbl(cursor);
        XWPFTableRow tableRow1 = table.getRow(0);
        tableRow1.getCell(0).setText("公司名称");
        tableRow1.createCell().setText(enterpriseInfo.getENTNAME());
        tableRow1.createCell();
        tableRow1.createCell();
        XWPFTableRow tableRow2 = table.createRow();
        tableRow2.getCell(0).setText("成立日期");
        tableRow2.getCell(1).setText(TimeUtil.formatTimeStr(enterpriseInfo.getESDATE()));
        tableRow2.getCell(2).setText("营业期限");
        tableRow2.getCell(3).setText(TimeUtil.formatTimeStr(enterpriseInfo.getOPFROM()) + "至无固定期限");
        XWPFTableRow tableRow3 = table.createRow();
        tableRow3.getCell(0).setText("法定代表人");
        tableRow3.getCell(1).setText(enterpriseInfo.getFRNAME());
        tableRow3.getCell(2).setText("行业名称");
        tableRow3.getCell(3).setText(enterpriseInfo.getCEICATEGORYNAME1());
        XWPFTableRow tableRow4 = table.createRow();
        tableRow4.getCell(0).setText("统一社会信用代码");
        tableRow4.getCell(1).setText(enterpriseInfo.getCREDITCODE());
        tableRow4.getCell(2).setText("公司类型");
        tableRow4.getCell(3).setText(enterpriseInfo.getENTTYPE());
        XWPFTableRow tableRow5 = table.createRow();
        tableRow5.getCell(0).setText("注册资本");
        tableRow5.getCell(1).setText(enterpriseInfo.getREGCAP());
        tableRow5.getCell(2).setText("实缴资本");
        tableRow5.getCell(3).setText(enterpriseInfo.getCEIREALCAPITAL());
        XWPFTableRow tableRow6 = table.createRow();
        tableRow6.getCell(0).setText("所在省份");
        tableRow6.getCell(1).setText(enterpriseInfo.getREGORGPROVINCE());
        tableRow6.getCell(2).setText("登记机关");
        tableRow6.getCell(3).setText(enterpriseInfo.getREGORG());
        XWPFTableRow tableRow7 = table.createRow();
        tableRow7.getCell(0).setText("注册地址");
        tableRow7.getCell(1).setText(enterpriseInfo.getDOM());
        XWPFTableRow tableRow8 = table.createRow();
        tableRow8.getCell(0).setText("经营范围");
        tableRow8.getCell(1).setText(enterpriseInfo.getZSOPSCOPE());

        mergeCellsHorizontal(table, 0, 1, 3);
        mergeCellsHorizontal(table, 6, 1, 3);
        mergeCellsHorizontal(table, 7, 1, 3);

        setTableFont(table, "宋体", 15, false);
        ReportUtil.setTableLocation(table, "center");
        ReportUtil.setCellLocation(table, "CENTER", "center");

        xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));
    }

    /**
     * 四、近三月新发案件告警Text1
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/
    public static String threeMonthsText1(List<LawCase> caseList) {
        // 初始化统计数据
        int totalCases = 0;
        BigDecimal totalAmount = BigDecimal.ZERO;
        int plaintiffCases = 0;
        BigDecimal plaintiffAmount = BigDecimal.ZERO;
        int defendantCases = 0;
        BigDecimal defendantAmount = BigDecimal.ZERO;
        int thirdPartyCases = 0;
        BigDecimal thirdPartyAmount = BigDecimal.ZERO;

        // 遍历案件列表并统计
        for (LawCase lawCase : caseList) {
            totalCases++;
            if (lawCase.getNQsbdje() != null) {
                totalAmount = totalAmount.add(lawCase.getNQsbdje());
            }

            List<LitigantInfo> litigantList = lawCase.getLitigantInfoList();
            for (LitigantInfo litigantInfo : litigantList) {
                if ("原告".equals(litigantInfo.getNSsdw())) {
                    plaintiffCases++;
                    if (lawCase.getNQsbdje() != null) {
                        plaintiffAmount = plaintiffAmount.add(lawCase.getNQsbdje());
                    }
                } else if ("被告".equals(litigantInfo.getNSsdw())) {
                    defendantCases++;
                    if (lawCase.getNQsbdje() != null) {
                        defendantAmount = defendantAmount.add(lawCase.getNQsbdje());
                    }
                } else if ("第三人".equals(litigantInfo.getNSsdw())) {
                    thirdPartyCases++;
                    if (lawCase.getNQsbdje() != null) {
                        thirdPartyAmount = thirdPartyAmount.add(lawCase.getNQsbdje());
                    }
                }
            }
        }
        // 构建返回字符串
        StringBuilder result = new StringBuilder();
        result.append("近三个月新发案件").append(totalCases).append("件，涉案金额").append(totalAmount.divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP)).append("万元。");
        result.append("其中，原告案件").append(plaintiffCases).append("件，涉诉金额").append(plaintiffAmount.divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP)).append("万元；");
        result.append("被告案件").append(defendantCases).append("件，涉诉金额").append(defendantAmount.divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP)).append("万元；");
        result.append("第三人案件").append(thirdPartyCases).append("件，涉诉金额").append(thirdPartyAmount.divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP)).append("万元。");
        result.append("案件审理阶段分布如下：\n");

        return result.toString();
    }
    /**
     * 四、近三月新发案件告警Table1
     *
     * @param xwpfParagraph
     * @param xwpfDocument
     * @param caseList
     * @return void
     * @author zhangjing
     * @create 2024/12/17
     **/
    private static void threeMonthsTable1(XWPFParagraph xwpfParagraph, XWPFDocument xwpfDocument,
                                          List<LawCase> caseList) {
        Map<String, Integer> countMap = new HashMap<>();
        Map<String, BigDecimal> amountMap = new HashMap<>();
        // 初始化所有阶段的数量和金额为 0
        for (String stage : stages) {
            countMap.put(stage, 0);
            amountMap.put(stage, BigDecimal.ZERO);
        }
        // 遍历 caseList 统计数量和金额
        for (LawCase lawCase : caseList) {
            String stage = lawCase.getNSlcx();
            if (countMap.containsKey(stage)) {
                countMap.put(stage, countMap.get(stage) + 1);
                BigDecimal currentAmount = amountMap.get(stage);
                if (lawCase.getNQsbdje()!=null){
                    amountMap.put(stage, currentAmount.add(lawCase.getNQsbdje()));
                }
            }
        }

        XmlCursor cursor = xwpfParagraph.getCTP().newCursor();
        XWPFTable table = xwpfDocument.insertNewTbl(cursor);
        XWPFTableRow tableRow1 = table.getRow(0);
        tableRow1.getCell(0).setText("审理阶段");
        tableRow1.createCell().setText("案件数量（件）");
        tableRow1.createCell().setText("涉案金额（万元）");
        for (String stage : stages) {
            int count = countMap.get(stage);
            BigDecimal amount = amountMap.get(stage);
            // 在这里可以将统计结果添加到文档中
//            xwpfParagraph.createRun().setText(stage + " 数量: " + count + ", 金额: " + amount.toString());
//            xwpfDocument.createParagraph(); // 创建一个新的段落

            XWPFTableRow tableRow = table.createRow();
            tableRow.getCell(0).setText(stage);
            tableRow.getCell(1).setText(String.valueOf(count));
            tableRow.getCell(2).setText(String.valueOf(amount.divide(BigDecimal.valueOf(10000),2, RoundingMode.HALF_UP)));
        }
        setTableFont(table, "宋体", 15, false);
        ReportUtil.setTableLocation(table, "center");
        ReportUtil.setCellLocation(table, "CENTER", "center");

        xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));

        // 输出统计结果
    }
    /**
     * 四、近三月新发案件告警Text2
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/
    public static String threeMonthsText2(List<LawCase> caseList) {
        // 使用 Map 存储每个省份的案件数量
        Map<String, Integer> provinceCountMap = new HashMap<>();

        // 遍历案件列表并统计
        for (LawCase lawCase : caseList) {
            String province = lawCase.getCSsdy(); // 假设 LawCase 类有 getCSsdy() 方法获取所属省份
            provinceCountMap.put(province, provinceCountMap.getOrDefault(province, 0) + 1);
        }

        // 按数量排序，找出前三个省份
        List<Map.Entry<String, Integer>> sortedProvinces = new ArrayList<>(provinceCountMap.entrySet());
        sortedProvinces.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));

        // 构建返回字符串
        StringBuilder result = new StringBuilder();

        // 添加前三省份的统计信息
        if (!sortedProvinces.isEmpty()) {
            result.append("新发案件分布全国").append(provinceCountMap.size()).append("省，其中");
            for (int i = 0; i < Math.min(3, sortedProvinces.size()); i++) {
                Map.Entry<String, Integer> entry = sortedProvinces.get(i);
                result.append(entry.getKey()).append("案件数量位列第").append(i + 1).append("，为").append(entry.getValue()).append("件");
                if (i < 2 && i + 1 < sortedProvinces.size()) {
                    result.append("，");
                } else if (i == 2 && i + 1 < sortedProvinces.size()) {
                    result.append("。");
                }
            }
            result.append("案件分布详细情况如下：\n");
        }

        // 详细
//        for (Map.Entry<String, Integer> entry : sortedProvinces) {
//            result.append(entry.getKey()).append(": ").append(entry.getValue()).append("件\n");
//        }

        return result.toString();
    }
    /**
     * 四、近三月新发案件告警Text3
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/
    public static String threeMonthsText3(List<LawCase> caseList) {
        // 使用 Map 存储每种案件类型的数量
        Map<String, Integer> caseTypeCountMap = new HashMap<>();
        // 使用 Map 存储每种案件类型的总金额
        Map<String, BigDecimal> amountMap = new HashMap<>();

        // 案件类型名称映射
        Map<String, String> caseTypeNameMap = new HashMap<>();
        caseTypeNameMap.put("civil", "民事案件");
        caseTypeNameMap.put("criminal", "刑事案件");
        caseTypeNameMap.put("administrative", "行政案件");
        caseTypeNameMap.put("preservation", "非诉保全审查");
        caseTypeNameMap.put("implement", "执行案件");
        caseTypeNameMap.put("bankrupt", "强制清算与破产案件");
        caseTypeNameMap.put("jurisdict", "管辖案件");
        caseTypeNameMap.put("compensate", "赔偿案件");

        // 遍历案件列表并统计
        for (LawCase lawCase : caseList) {
            String caseType = lawCase.getCaseType(); // 假设 LawCase 类有 getCaseType() 方法获取案件类型
            caseTypeCountMap.put(caseType, caseTypeCountMap.getOrDefault(caseType, 0) + 1);
            if (lawCase.getNQsbdje() != null) {
                BigDecimal currentAmount = amountMap.getOrDefault(caseType, BigDecimal.ZERO);
                amountMap.put(caseType, currentAmount.add(lawCase.getNQsbdje()));
            }
        }

        // 按数量排序，找出前三个案件类型
        List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(caseTypeCountMap.entrySet());
        sortedList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));

        // 构建返回字符串
        StringBuilder result = new StringBuilder();
        if (!sortedList.isEmpty()) {
            result.append("新发案件类型：");
            for (int i = 0; i < Math.min(3, sortedList.size()); i++) {
                Map.Entry<String, Integer> entry = sortedList.get(i);
                String caseTypeName = caseTypeNameMap.getOrDefault(entry.getKey(), entry.getKey());
                result.append(caseTypeName).append(entry.getValue()).append("件");
                if (i < 2) {
                    result.append("，");
                } else {
                    result.append("。");
                }
            }
            result.append("案件分布详细情况如下：\n");

            // 添加详细分布情况
//            for (Map.Entry<String, Integer> entry : sortedList) {
//                String caseType = entry.getKey();
//                String caseTypeName = caseTypeNameMap.getOrDefault(caseType, caseType);
//                int count = entry.getValue();
//                BigDecimal totalAmount = amountMap.getOrDefault(caseType, BigDecimal.ZERO);
//                result.append(caseTypeName).append(count).append("件，总金额：").append(totalAmount).append("元\n");
//            }
        }

        return result.toString();
    }
    /**
     * 四、近三月新发案件告警Table3
     *
     * @param xwpfParagraph
     * @param xwpfDocument
     * @param caseList
     * @return void
     * @author zhangjing
     * @create 2024/12/17
     **/
    private static void threeMonthsTable3(XWPFParagraph xwpfParagraph, XWPFDocument xwpfDocument,
                                          List<LawCase> caseList) {
        // 使用 Map 存储每种案件类型的数量
        Map<String, Integer> caseTypeCountMap = new HashMap<>();
        // 使用 Map 存储每种案件类型的总金额
        Map<String, BigDecimal> amountMap = new HashMap<>();

        // 案件类型名称映射
        Map<String, String> caseTypeNameMap = new HashMap<>();
        caseTypeNameMap.put("civil", "民事案件");
        caseTypeNameMap.put("criminal", "刑事案件");
        caseTypeNameMap.put("administrative", "行政案件");
        caseTypeNameMap.put("preservation", "非诉保全审查");
        caseTypeNameMap.put("implement", "执行案件");
        caseTypeNameMap.put("bankrupt", "强制清算与破产案件");
        caseTypeNameMap.put("jurisdict", "管辖案件");
        caseTypeNameMap.put("compensate", "赔偿案件");

        // 遍历案件列表并统计
        for (LawCase lawCase : caseList) {
            String caseType = lawCase.getCaseType(); // 假设 LawCase 类有 getCaseType() 方法获取案件类型
            caseTypeCountMap.put(caseType, caseTypeCountMap.getOrDefault(caseType, 0) + 1);
            if (lawCase.getNQsbdje() != null) {
                BigDecimal currentAmount = amountMap.getOrDefault(caseType, BigDecimal.ZERO);
                amountMap.put(caseType, currentAmount.add(lawCase.getNQsbdje()));
            }
        }
        XmlCursor cursor = xwpfParagraph.getCTP().newCursor();
        XWPFTable table = xwpfDocument.insertNewTbl(cursor);
        XWPFTableRow tableRow1 = table.getRow(0);
        tableRow1.getCell(0).setText("案件类型");
        tableRow1.createCell().setText("案件数量（件）");
        tableRow1.createCell().setText("涉案金额（万元）");
        //map循环
        for (Map.Entry<String, String> entry : caseTypeNameMap.entrySet()) {
            XWPFTableRow tableRow = table.createRow();
            tableRow.getCell(0).setText(caseTypeNameMap.getOrDefault(entry.getKey(), entry.getKey()));
            tableRow.getCell(1).setText(String.valueOf(caseTypeCountMap.getOrDefault(entry.getKey(),0)));
            tableRow.getCell(2).setText(String.valueOf(amountMap.getOrDefault(entry.getKey(),BigDecimal.ZERO).divide(BigDecimal.valueOf(10000), 2, RoundingMode.HALF_UP)));
        }
        setTableFont(table, "宋体", 15, false);
        ReportUtil.setTableLocation(table, "center");
        ReportUtil.setCellLocation(table, "CENTER", "center");

        xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));

        // 输出统计结果
    }
    /**
     * 5.1 案件审理阶段Text1
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/
    public static String caseStageText1(List<LawCase> caseList) {

        // 统计变量
        int totalCases = 0;
        BigDecimal totalAmount = BigDecimal.ZERO;
        Map<String, Integer> roleCaseCountMap = new HashMap<>();
        Map<String, BigDecimal> roleAmountMap = new HashMap<>();
        Map<String, Integer> stageCaseCountMap = new HashMap<>();

        roleCaseCountMap.put("原告", 0);
        roleCaseCountMap.put("被告", 0);
        roleCaseCountMap.put("第三人", 0);

        for (String stage : stages) {
            stageCaseCountMap.put(stage, 0);
        }

        for (LawCase lawCase : caseList) {
            totalCases++;
            if (lawCase.getNQsbdje() != null) {
                totalAmount = totalAmount.add(lawCase.getNQsbdje());
            }

            List<LitigantInfo> litigantList = lawCase.getLitigantInfoList();
            for (LitigantInfo litigantInfo : litigantList) {
                String role = litigantInfo.getNSsdw();
                if (roleCaseCountMap.containsKey(role)) {
                    roleCaseCountMap.put(role, roleCaseCountMap.get(role) + 1);
                    if (lawCase.getNQsbdje() != null) {
                        BigDecimal currentRoleAmount = roleAmountMap.getOrDefault(role, BigDecimal.ZERO);
                        roleAmountMap.put(role, currentRoleAmount.add(lawCase.getNQsbdje()));
                    }
                }
            }

            // 统计阶段
            String stage = lawCase.getNSlcx();
            if (stageCaseCountMap.containsKey(stage)) {
                stageCaseCountMap.put(stage, stageCaseCountMap.get(stage) + 1);
            }
        }

        // 返回
        StringBuilder result = new StringBuilder();
        result.append("案件总数").append(totalCases).append("件，总涉案金额")
            .append(totalAmount.divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP)).append("万元");
        for (String role : roleCaseCountMap.keySet()) {
            int roleCaseCount = roleCaseCountMap.get(role);
            BigDecimal roleAmount = roleAmountMap.getOrDefault(role, BigDecimal.ZERO);
            roleAmount = roleAmount.divide(BigDecimal.valueOf(10000),2,RoundingMode.HALF_UP);
            result.append("，").append(role).append("案件").append(roleCaseCount).append("件，涉诉金额").append(roleAmount).append("万元");
        }
        result.append("。");
        for (String stage : stages) {
            int stageCaseCount = stageCaseCountMap.get(stage);
            if (stageCaseCount > 0) {
                result.append(stage).append("案件").append(stageCaseCount).append("件、");
            }
        }

        if (result.charAt(result.length() - 1) == '、') {
            result.setLength(result.length() - 1);
        }
        result.append("。");

        return result.toString();
    }
    /**
     * 5.2 案件发生地域与管辖法院
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/

    public static String locationText(List<LawCase> caseList) {
        // 统计变量
        Map<String, Integer> provinceCaseCountMap = new HashMap<>();

        // 遍历案件列表并统计
        for (LawCase lawCase : caseList) {
            String province = lawCase.getCSsdy(); // 假设 LawCase 类有 getCSSDY() 方法获取所属省
            if (province != null && !province.isEmpty()) {
                provinceCaseCountMap.put(province, provinceCaseCountMap.getOrDefault(province, 0) + 1);
            }
        }

        // 构建返回字符串
        StringBuilder result = new StringBuilder();
        result.append("涉诉案件分布全国").append(provinceCaseCountMap.size()).append("省，其中");

        // 获取案件数量最多的三个省份
        List<Map.Entry<String, Integer>> sortedProvinces = new ArrayList<>(provinceCaseCountMap.entrySet());
        sortedProvinces.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));

        for (int i = 0; i < Math.min(3, sortedProvinces.size()); i++) {
            Map.Entry<String, Integer> entry = sortedProvinces.get(i);
            result.append(entry.getKey()).append("案件数量位列第").append(i + 1).append("，共").append(entry.getValue()).append("起");
            if (i < Math.min(2, sortedProvinces.size() - 1)) {
                result.append("，");
            }
        }
        result.append("。各省涉诉案件分布情况如下图所示：");

        return result.toString();
    }
    /**
     * 5.3案件类型与案由Text1
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/
    public static String caseActionText1(List<LawCase> caseList) {
        // 使用 Map 存储每种案件类型的数量
        Map<String, Integer> caseTypeCountMap = new HashMap<>();
        // 使用 Map 存储每种案件类型的总金额
        Map<String, BigDecimal> amountMap = new HashMap<>();

        // 案件类型名称映射
        Map<String, String> caseTypeNameMap = new HashMap<>();
        caseTypeNameMap.put("civil", "民事案件");
        caseTypeNameMap.put("criminal", "刑事案件");
        caseTypeNameMap.put("administrative", "行政案件");
        caseTypeNameMap.put("preservation", "非诉保全审查");
        caseTypeNameMap.put("implement", "执行案件");
        caseTypeNameMap.put("bankrupt", "强制清算与破产案件");
        caseTypeNameMap.put("jurisdict", "管辖案件");
        caseTypeNameMap.put("compensate", "赔偿案件");

        // 遍历案件列表并统计
        for (LawCase lawCase : caseList) {
            String caseType = lawCase.getCaseType(); // 假设 LawCase 类有 getCaseType() 方法获取案件类型
            caseTypeCountMap.put(caseType, caseTypeCountMap.getOrDefault(caseType, 0) + 1);
            if (lawCase.getNQsbdje() != null) {
                BigDecimal currentAmount = amountMap.getOrDefault(caseType, BigDecimal.ZERO);
                amountMap.put(caseType, currentAmount.add(lawCase.getNQsbdje()));
            }
        }

        // 按数量排序，找出前三个案件类型
        List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(caseTypeCountMap.entrySet());
        sortedList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));

        // 构建返回字符串
        StringBuilder result = new StringBuilder();
        if (!sortedList.isEmpty()) {
            result.append("案件类型：");
            for (int i = 0; i < Math.min(3, sortedList.size()); i++) {
                Map.Entry<String, Integer> entry = sortedList.get(i);
                String caseTypeName = caseTypeNameMap.getOrDefault(entry.getKey(), entry.getKey());
                result.append(caseTypeName).append(entry.getValue()).append("件");
                if (i < 2) {
                    result.append("，");
                } else {
                    result.append("。");
                }
            }
            result.append("案件分布详细情况如下：\n");

            // 添加详细分布情况
//            for (Map.Entry<String, Integer> entry : sortedList) {
//                String caseType = entry.getKey();
//                String caseTypeName = caseTypeNameMap.getOrDefault(caseType, caseType);
//                int count = entry.getValue();
//                BigDecimal totalAmount = amountMap.getOrDefault(caseType, BigDecimal.ZERO);
//                result.append(caseTypeName).append(count).append("件，总金额：").append(totalAmount).append("元\n");
//            }
        }

        return result.toString();
    }
    /**
     * 5.3案件类型与案由Table1
     *
     * @param xwpfParagraph
     * @param xwpfDocument
     * @param caseList
     * @return void
     * @author zhangjing
     * @create 2024/12/17
     **/
    private static void caseActionTable1(XWPFParagraph xwpfParagraph, XWPFDocument xwpfDocument,
                                          List<LawCase> caseList) {
        // 使用 Map 存储每种案件类型的数量
        Map<String, Integer> caseTypeCountMap = new HashMap<>();
        // 使用 Map 存储每种案件类型的总金额
        Map<String, BigDecimal> amountMap = new HashMap<>();

        // 案件类型名称映射
        Map<String, String> caseTypeNameMap = new HashMap<>();
        caseTypeNameMap.put("civil", "民事案件");
        caseTypeNameMap.put("criminal", "刑事案件");
        caseTypeNameMap.put("administrative", "行政案件");
        caseTypeNameMap.put("preservation", "非诉保全审查");
        caseTypeNameMap.put("implement", "执行案件");
        caseTypeNameMap.put("bankrupt", "强制清算与破产案件");
        caseTypeNameMap.put("jurisdict", "管辖案件");
        caseTypeNameMap.put("compensate", "赔偿案件");

        // 遍历案件列表并统计
        for (LawCase lawCase : caseList) {
            String caseType = lawCase.getCaseType(); // 假设 LawCase 类有 getCaseType() 方法获取案件类型
            caseTypeCountMap.put(caseType, caseTypeCountMap.getOrDefault(caseType, 0) + 1);
            if (lawCase.getNQsbdje() != null) {
                BigDecimal currentAmount = amountMap.getOrDefault(caseType, BigDecimal.ZERO);
                amountMap.put(caseType, currentAmount.add(lawCase.getNQsbdje()));
            }
        }
        XmlCursor cursor = xwpfParagraph.getCTP().newCursor();
        XWPFTable table = xwpfDocument.insertNewTbl(cursor);
        XWPFTableRow tableRow1 = table.getRow(0);
        tableRow1.getCell(0).setText("案件类型");
        tableRow1.createCell().setText("案件数量（件）");
        tableRow1.createCell().setText("涉案金额（万元）");
        //map循环
        for (Map.Entry<String, String> entry : caseTypeNameMap.entrySet()) {
            XWPFTableRow tableRow = table.createRow();
            tableRow.getCell(0).setText(caseTypeNameMap.getOrDefault(entry.getKey(), entry.getKey()));
            tableRow.getCell(1).setText(String.valueOf(caseTypeCountMap.getOrDefault(entry.getKey(),0)));
            tableRow.getCell(2).setText(String.valueOf(amountMap.getOrDefault(entry.getKey(),BigDecimal.ZERO).divide(BigDecimal.valueOf(10000), 2, RoundingMode.HALF_UP)));
        }
        setTableFont(table, "宋体", 15, false);
        ReportUtil.setTableLocation(table, "center");
        ReportUtil.setCellLocation(table, "CENTER", "center");

        xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));

        // 输出统计结果
    }
    /**
     * 5.3案件类型与案由Text2
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/

    public static String caseActionText2(List<LawCase> caseList) {
        // 使用 Map 来统计每个案件原因的数量
        Map<String, Integer> causeCountMap = new HashMap<>();

        // 遍历案件列表并统计
        for (LawCase lawCase : caseList) {
            String cause = lawCase.getNLaay();
            causeCountMap.put(cause, causeCountMap.getOrDefault(cause, 0) + 1);
        }

        // 将 map 转换为 list 并排序，找出数量最多的三个案件案由
        List<Map.Entry<String, Integer>> sortedCauses = causeCountMap.entrySet()
            .stream()
            .sorted((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()))
            .limit(3)
            .collect(Collectors.toList());

        // 构建返回字符串
        StringBuilder result = new StringBuilder("民事案件中，数量最多的三个案件案由是：");
        for (int i = 0; i < sortedCauses.size(); i++) {
            Map.Entry<String, Integer> entry = sortedCauses.get(i);
            result.append(entry.getKey()).append("，涉案数量为：").append(entry.getValue()).append("件");
            if (i != sortedCauses.size() - 1) {
                result.append("，");
            }
        }
        result.append("。");
        return result.toString();
    }
    /**
     * 5.4 涉案金额
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/

    public static String amountInvolvedText(List<LawCase> caseList) {
        // 遍历案件列表并统计
        for (LawCase lawCase : caseList) {

        }
        // 构建返回字符串
        StringBuilder result = new StringBuilder();

        return result.toString();
    }
    /**
     * 5.5 诉讼地位
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/15
     **/

    public static String litigationStatusText(List<LawCase> caseList) {
        // 按照诉讼地位分类并统计数量
        Map<String, Long> statusCountMap = caseList.stream()
            .collect(Collectors.groupingBy(LawCase::getNSsdw, Collectors.counting()));

        // 按数量降序排序
        List<Map.Entry<String, Long>> sortedStatusList = new ArrayList<>(statusCountMap.entrySet());
        sortedStatusList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
        StringBuilder result = new StringBuilder("涉诉案件中，");
        for (int i = 0; i < sortedStatusList.size(); i++) {
            Map.Entry<String, Long> entry = sortedStatusList.get(i);
            result.append("作为").append(entry.getKey()).append("案件数量最多，共").append(entry.getValue()).append("件");
            if (i < sortedStatusList.size() - 1) {
                result.append("；");
            }
        }
        result.append("。");
        return result.toString();
    }
    /**
     * 重大法律纠纷案件
     *
     * @param caseList
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/16
     */
    public static String majorCase(List<LawCase> caseList) {
        int totalCaseCount = 0;
        BigDecimal totalAmount = BigDecimal.ZERO;
        int newCaseCount = 0;
        BigDecimal newCaseAmount = BigDecimal.ZERO;
        int oldCaseCount = 0;
        BigDecimal oldCaseAmount = BigDecimal.ZERO;

        Map<String, CaseStats> caseStatsMap = new HashMap<>();

        for (LawCase lawCase : caseList) {
            totalCaseCount++;
            BigDecimal amountInTenThousand = lawCase.getNSqzxbdje().divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP);
            totalAmount = totalAmount.add(amountInTenThousand);
            //转结案

//            if (lawCase.isNewCase()) {
//                newCaseCount++;
//                newCaseAmount = newCaseAmount.add(amountInTenThousand);
//            } else {
            oldCaseCount++;
            oldCaseAmount = oldCaseAmount.add(amountInTenThousand);
//            }

            List<LitigantInfo> litigantList = lawCase.getLitigantInfoList();
            for (LitigantInfo litigantInfo : litigantList) {
                String n_ssdw = litigantInfo.getNSsdw();
                caseStatsMap.putIfAbsent(n_ssdw, new CaseStats());
                CaseStats stats = caseStatsMap.get(n_ssdw);
                stats.caseCount++;
                stats.totalAmount = stats.totalAmount.add(amountInTenThousand);
            }
        }

        // 构建结果字符串
        StringBuilder result = new StringBuilder();
        result.append("2024年共有重大法律纠纷案件")
            .append(totalCaseCount)
            .append("件，涉诉金额")
            .append(totalAmount)
            .append("万元。\n")
            .append("其中新发案件")
            .append(newCaseCount)
            .append("件，涉诉金额")
            .append(newCaseAmount)
            .append("万元；\n")
            .append("往年结转案件")
            .append(oldCaseCount)
            .append("件，涉诉金额")
            .append(oldCaseAmount)
            .append("万元。\n");

        for (Map.Entry<String, CaseStats> entry : caseStatsMap.entrySet()) {
            String n_ssdw = entry.getKey();
            CaseStats stats = entry.getValue();
            result.append(n_ssdw)
                .append("案件")
                .append(stats.caseCount)
                .append("件，涉诉金额")
                .append(stats.totalAmount)
                .append("万元；\n");
        }

        return result.toString().trim();
    }
    /**
     * 6.3 执行案件
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/16
     **/
    public static String executionCases(List<LawCase> caseList) {
        //结转

        return "";
    }
    /**
     * 6.4 高频诉讼对手
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/16
     **/
    public static String highFrequencyText(List<LawCase> caseList) {
        Map<String, Integer> plaintiffCountMap = new HashMap<>();
        Map<String, Integer> defendantCountMap = new HashMap<>();

        for (LawCase lawCase : caseList) {
            List<LitigantInfo> litigantList = lawCase.getLitigantInfoList();
            for (LitigantInfo litigantInfo : litigantList) {
                String c_mc = litigantInfo.getCMc();
                if ("原告".equals(litigantInfo.getNSsdw())) {
                    plaintiffCountMap.put(c_mc, plaintiffCountMap.getOrDefault(c_mc, 0) + 1);
                } else if ("被告".equals(litigantInfo.getNSsdw())) {
                    defendantCountMap.put(c_mc, defendantCountMap.getOrDefault(c_mc, 0) + 1);
                }
            }
        }

        // 合并统计
        Map<String, Integer> combinedCountMap = new HashMap<>(plaintiffCountMap);
        defendantCountMap.forEach((key, value) ->
            combinedCountMap.merge(key, value, Integer::sum)
        );

        // 获取前五
        List<Map.Entry<String, Integer>> topFive = combinedCountMap.entrySet()
            .stream()
            .sorted(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder()))
            .limit(5)
            .collect(Collectors.toList());

        StringBuilder result = new StringBuilder();
        result.append("近三年涉诉案件中，");
        for (int i = 0; i < topFive.size(); i++) {
            Map.Entry<String, Integer> entry = topFive.get(i);
            result.append(entry.getKey());
            if (i < topFive.size() - 1) {
                result.append("、");
            }
        }
        result.append("等，多次向恒大集团有限公司发起诉讼。恒大集团有限公司与");
        for (int i = 0; i < topFive.size(); i++) {
            Map.Entry<String, Integer> entry = topFive.get(i);
            result.append(entry.getKey());
            if (i < topFive.size() - 1) {
                result.append("、");
            }
        }
        result.append("等频繁发生诉讼。");

        return result.toString();
    }
    /**
     * 案件金额
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/16
     **/
    public static BigDecimal getCaseAmount(List<LawCase> caseList) {
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (LawCase lawCase : caseList) {
             if (lawCase.getNQsbdje()!=null){
                 totalAmount = totalAmount.add(lawCase.getNQsbdje());
             }
        }
        return totalAmount.divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP);
    }
    /**
     * 设置案由，诉讼地位，审理阶段信息
     *
     * @return java.lang.String
     * @author zhangjing
     * @create 2024/12/16
     **/
    public static void setAlarmInfo(EnterpriseAlarmInfo data,List<LawCase> caseList,List<EnterpriseProvince> enterpriseProvinceList) {
        Map<String, Integer> roleCaseCountMap = new HashMap<>();
        Map<String, BigDecimal> roleCaseAmountMap = new HashMap<>();
        Map<String, Integer> slcxCaseCountMap = new HashMap<>();
        Map<String, BigDecimal> slcxCaseAmountMap = new HashMap<>();
        Map<String, Integer> caseReasonCountMap = new HashMap<>();
        Map<String, BigDecimal> caseReasonAmontMap = new HashMap<>();
        //省份

        Map<String, EnterpriseProvince> provinceMap = new HashMap<>();
        for(String name : ReportConstants.PROVINCE){
            provinceMap.put(name,new EnterpriseProvince(data.getCreditCode(), name,0,BigDecimal.ZERO));
        }






        BigDecimal totalAmount = BigDecimal.ZERO;
        slcxCaseCountMap.put("一审", 0);
        slcxCaseCountMap.put("二审", 0);
        slcxCaseCountMap.put("再审审查", 0);
        slcxCaseCountMap.put("再审", 0);
        slcxCaseAmountMap.put("一审", BigDecimal.ZERO);
        slcxCaseAmountMap.put("二审", BigDecimal.ZERO);
        slcxCaseAmountMap.put("再审审查", BigDecimal.ZERO);
        slcxCaseAmountMap.put("再审", BigDecimal.ZERO);


        roleCaseCountMap.put("原告", 0);
        roleCaseCountMap.put("被告", 0);
        roleCaseCountMap.put("第三人", 0);
        roleCaseCountMap.put("其他", 0);
        roleCaseAmountMap.put("原告", BigDecimal.ZERO);
        roleCaseAmountMap.put("被告", BigDecimal.ZERO);
        roleCaseAmountMap.put("第三人", BigDecimal.ZERO);
        roleCaseAmountMap.put("其他", BigDecimal.ZERO);

        if (!caseList.isEmpty()) {
            for (LawCase lawCase : caseList) {
                String slcx = lawCase.getNSlcx();
                String companyName = lawCase.getCompanyName();
                if (slcxCaseCountMap.containsKey(slcx)) {
                    slcxCaseCountMap.put(slcx, slcxCaseCountMap.get(slcx) + 1);
                    if (lawCase.getNQsbdje() != null) {
                        slcxCaseAmountMap.put(slcx, slcxCaseAmountMap.getOrDefault(slcx, BigDecimal.ZERO).add(lawCase.getNQsbdje()));
                    }
                }
                if (lawCase.getCSsdy() != null && provinceMap.containsKey(lawCase.getCSsdy())) {
                    EnterpriseProvince enterpriseProvince = provinceMap.get(lawCase.getCSsdy());
                    enterpriseProvince.setCount(enterpriseProvince.getCount() + 1);
                    if (lawCase.getNQsbdje() != null) {
                        enterpriseProvince.setAmount(enterpriseProvince.getAmount().add(lawCase.getNQsbdje()));
                    }
                    provinceMap.put(lawCase.getCSsdy(), enterpriseProvince);
                }

                for (LitigantInfo litigantInfo : lawCase.getLitigantInfoList()) {
                    String role = litigantInfo.getNSsdw();
                    if (companyName.equals(litigantInfo.getCMc()) && roleCaseCountMap.containsKey(role)) {
                        roleCaseCountMap.put(role, roleCaseCountMap.get(role) + 1);
                        if (lawCase.getNQsbdje() != null) {
                            roleCaseAmountMap.put(role, roleCaseAmountMap.get(role).add(lawCase.getNQsbdje()));
                        }
                    }
                }
                if (lawCase.getNQsbdje() != null) {
                    totalAmount = totalAmount.add(lawCase.getNQsbdje());
                }
                // 统计案由
                String caseReason = lawCase.getNLaay();
                if (caseReason != null && !caseReason.isEmpty()) {
                    caseReasonCountMap.put(caseReason, caseReasonCountMap.getOrDefault(caseReason, 0) + 1);
                    if (lawCase.getNQsbdje() != null) {
                        caseReasonAmontMap.put(caseReason, caseReasonAmontMap.getOrDefault(caseReason, BigDecimal.ZERO).add(lawCase.getNQsbdje()));
                    }
                }
            }
        }
        // 案由进行排序
        List<Map.Entry<String, Integer>> sortedCaseReasons = new ArrayList<>(caseReasonCountMap.entrySet());
        sortedCaseReasons.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
        // 案由金额进行排序
        List<Map.Entry<String, BigDecimal>> sortedCaseReasonAmonts = new ArrayList<>(caseReasonAmontMap.entrySet());
        sortedCaseReasonAmonts.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
        // 取出前三的案由金额
        if (!sortedCaseReasonAmonts.isEmpty()){
            // 检查是否有第1个元素
                data.setAyAmountTop1(sortedCaseReasonAmonts.get(0).getValue());
                data.setAyNameAmountTop1(sortedCaseReasonAmonts.get(0).getKey());

            // 检查是否有第2个元素
            if (sortedCaseReasonAmonts.size() > 1) {
                data.setAyAmountTop2(sortedCaseReasonAmonts.get(1).getValue());
                data.setAyNameAmountTop2(sortedCaseReasonAmonts.get(1).getKey());
            }

            // 检查是否有第3个元素
            if (sortedCaseReasonAmonts.size() > 2) {
                data.setAyAmountTop3(sortedCaseReasonAmonts.get(2).getValue());
                data.setAyNameAmountTop3(sortedCaseReasonAmonts.get(2).getKey());
            }
        }


        // 取出前三的案由
        if (!sortedCaseReasons.isEmpty()) {
// 检查并设置 Top1
                data.setAyCountTop1(sortedCaseReasons.get(0).getValue());
                data.setAyNameTop1(sortedCaseReasons.get(0).getKey());

            // 检查并设置 Top2
            if (sortedCaseReasons.size() > 1) {
                data.setAyCountTop2(sortedCaseReasons.get(1).getValue());
                data.setAyNameTop2(sortedCaseReasons.get(1).getKey());
            }

            // 检查并设置 Top3
            if (sortedCaseReasons.size() > 2) {
                data.setAyCountTop3(sortedCaseReasons.get(2).getValue());
                data.setAyNameTop3(sortedCaseReasons.get(2).getKey());
            }
        }
        //审理阶段
        data.setYsCount(slcxCaseCountMap.get("一审"));
        data.setEsCount(slcxCaseCountMap.get("二审"));
        data.setZsCount(slcxCaseCountMap.get("再审审查"));
        data.setZxCount(slcxCaseCountMap.get("再审"));
        data.setYsAmount(slcxCaseAmountMap.get("一审"));
        data.setEsAmount(slcxCaseAmountMap.get("二审"));
        data.setZsAmount(slcxCaseAmountMap.get("再审审查"));
        data.setZxAmount(slcxCaseAmountMap.get("再审"));
        //诉讼地位
        data.setYgCount(roleCaseCountMap.get("原告"));
        data.setBgCount(roleCaseCountMap.get("被告"));
        data.setDsrCount(roleCaseCountMap.get("第三人"));
        data.setQtCount(roleCaseCountMap.get("其他"));
        data.setYgAmount(roleCaseAmountMap.get("原告"));
        data.setBgAmount(roleCaseAmountMap.get("被告"));
        data.setDsrAmount(roleCaseAmountMap.get("第三人"));
        data.setQtAmount(roleCaseAmountMap.get("其他"));

        for(String k:provinceMap.keySet()) {
            enterpriseProvinceList.add(provinceMap.get(k));
        }
        enterpriseProvinceList.sort((o1, o2) -> o2.getAmount().compareTo(o1.getAmount()));
        List<EnterpriseProvince> topThree = enterpriseProvinceList.subList(0, Math.min(3, enterpriseProvinceList.size()));
        BigDecimal mapAmount = BigDecimal.ZERO;
        Integer mapCount = 0;
        for (EnterpriseProvince ep : topThree) {
            mapAmount= mapAmount.add(ep.getAmount());
            mapCount += ep.getCount();
        }
        data.setMapAmount(mapAmount);
        data.setMapCount(mapCount);
        data.setThreeYearsCount(caseList.size());
        data.setThreeYearsAmount(totalAmount);

    }

    /**
     * @Description: 跨列合并
     * table
     * row:行
     * fromCell:开始列
     * toCell:结束列
     */
    public static void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
        for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
            XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
            if (cellIndex == fromCell) {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
            } else {
                cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
            }
        }
    }

    /**
     * 设置表格内全部字体样式
     *
     * @param table    表格对象
     * @param fontName 字体名称
     * @param fontSize 字体大小
     * @param isBold   是否加粗
     */
    public static void setTableFont(XWPFTable table, String fontName, int fontSize, boolean isBold) {
        for (XWPFTableRow row : table.getRows()) {
            row.setHeight(600);
            for (XWPFTableCell cell : row.getTableCells()) {
                for (XWPFParagraph paragraph : cell.getParagraphs()) {
                    paragraph.setAlignment(ParagraphAlignment.CENTER);
                    paragraph.setVerticalAlignment(TextAlignment.CENTER);
                    for (XWPFRun run : paragraph.getRuns()) {
                        run.setFontFamily(fontName);
                        run.setFontSize(fontSize);
                        run.setBold(isBold);
                    }
                }
            }
        }
    }


    private static void write(XWPFDocument document, String filePath) {
        try (FileOutputStream out = new FileOutputStream(filePath)) {
            document.write(out);
        } catch (IOException e) {
            throw new RuntimeException("Failed to write document to file: " + filePath, e);
        }
    }




    /**
     * 董监高及法定代表人个人涉诉信息
     *
     * @param dishonestInfoList，limitationList
     * @return java.lang.String
     */
    public static String personalLitigation(List<DishonestInfo> dishonestInfoList, List<Limitation> limitationList) {
        // 统计失信数
        Map<String, Long> dishonestCountMap = dishonestInfoList.stream()
            .collect(Collectors.groupingBy(DishonestInfo::getQyfr, Collectors.counting()));


        // 合并统计数据
        Map<String, Map<String, Long>> combinedCountMap = new HashMap<>();
        for (String name : dishonestCountMap.keySet()) {
            combinedCountMap.putIfAbsent(name, new HashMap<>());
            combinedCountMap.get(name).put("dishonestCount", dishonestCountMap.get(name));
        }


        // 构建结果字符串
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, Map<String, Long>> entry : combinedCountMap.entrySet()) {
            String name = entry.getKey();
            long dishonestCount = entry.getValue().getOrDefault("dishonestCount", 0L);
            result.append("姓名: ").append(name)
                .append(", 失信数: ").append(dishonestCount)
                .append(", 限高数: ").append(limitationList.size())
                .append("\n");
        }
        return result.toString().trim();
    }




    static class CaseStats {
        int caseCount = 0;
        BigDecimal totalAmount = BigDecimal.ZERO;
    }





    /**
     * 设置单元格水平位置和垂直位置
     *
     * @param xwpfTable
     * @param verticalLoction    单元格中内容垂直上TOP，下BOTTOM，居中CENTER，BOTH两端对齐
     * @param horizontalLocation 单元格中内容水平居中center,left居左，right居右，both两端对齐
     */
    public static void setCellLocation(XWPFTable xwpfTable, String verticalLoction, String horizontalLocation) {
        List<XWPFTableRow> rows = xwpfTable.getRows();
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                CTTc cttc = cell.getCTTc();
                CTP ctp = cttc.getPList().get(0);
                CTPPr ctppr = ctp.getPPr();
                if (ctppr == null) {
                    ctppr = ctp.addNewPPr();
                }
                CTJc ctjc = ctppr.getJc();
                if (ctjc == null) {
                    ctjc = ctppr.addNewJc();
                }
                //水平居中
                ctjc.setVal(STJc.Enum.forString(horizontalLocation));
                //垂直居中
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf(verticalLoction));
            }
        }
    }

    /**
     * 设置表格位置
     *
     * @param xwpfTable
     * @param location  整个表格居中center,left居左，right居右，both两端对齐
     */
    public static void setTableLocation(XWPFTable xwpfTable, String location) {
        CTTbl cttbl = xwpfTable.getCTTbl();
        CTTblPr tblpr = cttbl.getTblPr() == null ? cttbl.addNewTblPr() : cttbl.getTblPr();
        CTJc cTJc = tblpr.addNewJc();
        cTJc.setVal(STJc.Enum.forString(location));
    }

}
