package com.fkzy.warn.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.IgnoredErrorType;


import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author zhangjing
 * @date 2024/08/06 14:42
 * @description
 */
public class Demo {
        public static void main(String[] args) {
        LawResearchUtil law = new LawResearchUtil();
        law.querySxx(null, null);
//        law.queryDishonest(null, null,null,null);
//        law.queryLimitConsumption(null, null,null,null);
//        law.monitorQuery(null, null);
//        law.delcompany(null);
        law.queryMonitorCases(null,null,null);
//            law.addpublic(null);

    }



//    public static void main(String[] args) {
//        String filePath = "司法.txt";
//        String jsonOutput = convertTextToJson(filePath);
//
//        if (jsonOutput != null) {
//            JSONObject jsonObject = new JSONObject().parseObject(jsonOutput);
//            JSONArray arr = jsonObject.getJSONArray("data");
//            JSONObject data = arr.getJSONObject(0);
//            JSONObject detail = data.getJSONObject("detail");
////            JSONObject detail = data.getJSONObject("sx");
//                        JSONObject civil = detail.getJSONObject("civil");
////            JSONObject civil = detail.getJSONObject("civil");
//////            JSONObject civil = detail.getJSONObject("implement");
//            JSONArray jsonArray = civil.getJSONArray("cases");
////            JSONArray jsonArray = detail.getJSONArray("sxbzxr_current");
//            c_dsrxx(jsonArray);
//
//
////            getCaseNum(jsonArray);
////            getMaxValue(jsonArray);
////             getCaseYearNum(jsonArray);
////            getNowYear(jsonArray);
////            getImplementInfo(jsonArray);
////            getCaseSlcx(jsonArray);
//        } else {
//            System.out.println("转换失败，JSON 字符串为空");
//        }
//    }
       static void getSX(JSONArray jsonArray){
          //qyfr 企业法人
          //pjje_gj  被执行金额
          //fbrq 发布日期
          //ah 案号
          //打印 企业法人 案号 发布日期 被执行金额
           // 遍历 JSON 数组
           for (int i = 0; i < jsonArray.size(); i++) {
               try {
                   JSONObject caseObj = jsonArray.getJSONObject(i);

                   // 提取字段值
                   String qyfr = caseObj.getString("qyfr"); // 企业法人
                   String pjjeGj = caseObj.getString("pjje_gj"); // 被执行金额
                   String fbrq = caseObj.getString("fbrq"); // 发布日期
                   String ah = caseObj.getString("ah"); // 案号

                   // 打印信息
                   System.out.println("企业法人: " + qyfr + ", 案号: " + ah + ", 发布日期: " + fbrq + ", 被执行金额: " + pjjeGj);
               } catch (Exception e) {
                   System.out.println("Error processing JSON object at index " + i + ": " + e.getMessage());
               }
           }
       }



        static void c_dsrxx(JSONArray jsonArray) {
            Map<String, Integer> countMap = new HashMap<>();
            Map<String, BigDecimal> amountMap = new HashMap<>();
            Map<String, Integer> plaintiffCountMap = new HashMap<>();

            countMap.put("原告", 0);
            countMap.put("被告", 0);
            amountMap.put("原告", BigDecimal.ZERO);
            amountMap.put("被告", BigDecimal.ZERO);

            for (int i = 0; i < jsonArray.size(); i++) {
                try {
                    JSONObject caseObj = jsonArray.getJSONObject(i);
                    JSONArray c_dsrxx = caseObj.getJSONArray("c_dsrxx");
                    String larq = caseObj.getString("d_larq");
                    int year = Integer.parseInt(larq.substring(0, 4));
                    BigDecimal claimAmount = null;

                    if (caseObj.containsKey("n_qsbdje") && caseObj.getString("n_qsbdje")!=null) {
                        claimAmount = new BigDecimal(caseObj.getString("n_qsbdje"));
                    }

                    if (c_dsrxx != null && year >= 2022) {
                        for (int k = 0; k < c_dsrxx.size(); k++) {
                            JSONObject dsrxx = c_dsrxx.getJSONObject(k);
                            String key = dsrxx.getString("c_mc");

                            if (key != null && key.equals("恒大集团有限公司")) {
                                String role = k == 0 ? "原告" : "被告";
                                countMap.put(role, countMap.get(role) + 1);
                                if (claimAmount != null) {
                                    amountMap.put(role, amountMap.get(role).add(claimAmount));
                                }

                                if (role.equals("被告") && k > 0) {
                                    String plaintiffName = c_dsrxx.getJSONObject(0).getString("c_mc");
                                    plaintiffCountMap.put(plaintiffName, plaintiffCountMap.getOrDefault(plaintiffName, 0) + 1);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    System.out.println("Error processing JSON object at index " + i + ": " + e.getMessage());
                }
            }

            // 打印统计结果
            for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
                String role = entry.getKey();
                int count = entry.getValue();
                BigDecimal amount = amountMap.get(role);
                System.out.println("角色: " + role + ", 数量: " + count + ", 金额: " + amount);
            }

            // 获取前10个原告名字及其数量
            List<Map.Entry<String, Integer>> sortedPlaintiffs = new ArrayList<>(plaintiffCountMap.entrySet());
            sortedPlaintiffs.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));

            System.out.println("\n前10个原告名字及其数量:");
            for (int i = 0; i < Math.min(10, sortedPlaintiffs.size()); i++) {
                Map.Entry<String, Integer> entry = sortedPlaintiffs.get(i);
                System.out.println("名字: " + entry.getKey() + ", 数量: " + entry.getValue());
            }
        }







    //审理案件
    static void getCaseSlcx(JSONArray jsonArray){
        //n_slcx 审理程序
        //根据 审理程序 分类 并统计数量
        Map<String, Integer> slcxCountMap = new HashMap<>();
        int totalCount=0;
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        for (int i = 0; i < jsonArray.size(); i++) {
            try {

                String slcx = jsonArray.getJSONObject(i).getString("n_ssdw");
//                String closingDateStr = jsonArray.getJSONObject(i).getString("d_jarq");
                String closingDateStr = jsonArray.getJSONObject(i).getString("d_larq");
//                String slcx = jsonArray.getJSONObject(i).getString("c_ssdy");
//                String slcx = jsonArray.getJSONObject(i).getString("n_laay");

                LocalDate closingDate = closingDateStr != null ? LocalDate.parse(closingDateStr, formatter) : null;
                if (closingDate!=null&&closingDate.isAfter(LocalDate.of(2022, 1, 1))) {
                    slcxCountMap.put(slcx, slcxCountMap.getOrDefault(slcx, 0) + 1);
                }
//                if (closingDateStr==null) {
//                    totalCount = totalCount+1;
//                }
            } catch (Exception e) {
                System.out.println("Error==" + i + ": " + e.getMessage());
            }
        }

        // 打印分类结果
        for (Map.Entry<String, Integer> entry : slcxCountMap.entrySet()) {
            System.out.println("诉讼地位: " + entry.getKey() + ", 数量: " + entry.getValue());

        }
//        System.out.println("总数: " + totalCount);
        // 将 Map 转换为 List 并按数量排序
//        List<Map.Entry<String, Integer>> sortedList = new ArrayList<>(slcxCountMap.entrySet());
//        sortedList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
//
//        // 打印前10个审理程序及其数量
//        int topN = 10;
//        for (int i = 0; i < Math.min(topN, sortedList.size()); i++) {
//            Map.Entry<String, Integer> entry = sortedList.get(i);
//            System.out.println("立案案由: " + entry.getKey() + ", 数量: " + entry.getValue());
//        }
    }


        static void getCaseInfo(JSONArray jsonArray) {
            // 初始化统计变量
            Map<String, Integer> countMap = new HashMap<>();
            Map<String, BigDecimal> amountMap = new HashMap<>();

            countMap.put("案件总数", 0);
            countMap.put("新发案件", 0);
            countMap.put("结转案件", 0);
            countMap.put("主诉案件", 0);
            countMap.put("被诉案件", 0);
            countMap.put("处理终结案件", 0);
            countMap.put("尚未终结案件", 0);
            countMap.put("上诉期限内案件", 0);

            amountMap.put("案件总数", BigDecimal.ZERO);
            amountMap.put("新发案件", BigDecimal.ZERO);
            amountMap.put("结转案件", BigDecimal.ZERO);
            amountMap.put("主诉案件", BigDecimal.ZERO);
            amountMap.put("被诉案件", BigDecimal.ZERO);
            amountMap.put("处理终结案件", BigDecimal.ZERO);
            amountMap.put("尚未终结案件", BigDecimal.ZERO);
            amountMap.put("上诉期限内案件", BigDecimal.ZERO);

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            for (int i = 0; i < jsonArray.size(); i++) {
                try {
                    JSONObject caseObj = jsonArray.getJSONObject(i);
                    String filingDateStr = caseObj.getString("d_larq");
                    String closingDateStr = caseObj.getString("d_jarq");
                    String claimAmountStr = caseObj.getString("n_qsbdje");
                    JSONArray c_dsrxx = caseObj.getJSONArray("c_dsrxx");

                    LocalDate filingDate = LocalDate.parse(filingDateStr, formatter);
                    LocalDate closingDate = closingDateStr != null ? LocalDate.parse(closingDateStr, formatter) : null;
                    BigDecimal claimAmount = claimAmountStr != null && !claimAmountStr.isEmpty() ? new BigDecimal(claimAmountStr) : BigDecimal.ZERO;

                    // 检查是否为结转案件或上诉期限内案件
                    boolean isAppealPeriod = false;
                    boolean isCarryoverCase = false;

                    if (closingDate == null) {
                        // 尚未终结案件
                        countMap.put("尚未终结案件", countMap.get("尚未终结案件") + 1);
                        amountMap.put("尚未终结案件", amountMap.get("尚未终结案件").add(claimAmount));

                        // 检查是否处于上诉期限内
                        LocalDate appealEndDate = filingDate.plusMonths(6); // 假设上诉期限为6个月
                        if (LocalDate.now().isBefore(appealEndDate)) {
                            isAppealPeriod = true;
                            countMap.put("上诉期限内案件", countMap.get("上诉期限内案件") + 1);
                            amountMap.put("上诉期限内案件", amountMap.get("上诉期限内案件").add(claimAmount));
                        }
                    } else {
                        // 已经终结案件
                        if (closingDate.isAfter(LocalDate.of(2022, 1, 1))) {
                            countMap.put("处理终结案件", countMap.get("处理终结案件") + 1);
                            amountMap.put("处理终结案件", amountMap.get("处理终结案件").add(claimAmount));
                        } else {
                            isCarryoverCase = true;
                        }
                    }

                    if (!isCarryoverCase && !isAppealPeriod) {
                        // 统计案件总数
                        countMap.put("案件总数", countMap.get("案件总数") + 1);
                        amountMap.put("案件总数", amountMap.get("案件总数").add(claimAmount));

                        // 检查是否为新发案件
                        if (filingDate.isAfter(LocalDate.of(2022, 1, 1))) {
                            countMap.put("新发案件", countMap.get("新发案件") + 1);
                            amountMap.put("新发案件", amountMap.get("新发案件").add(claimAmount));
                        }

                        // 检查是否为主诉或被诉案件
                        if (c_dsrxx != null) {
                            for (int k = 0; k < c_dsrxx.size(); k++) {
                                JSONObject dsrxx = c_dsrxx.getJSONObject(k);
                                String name = dsrxx.getString("c_mc");

                                if (name != null && name.equals("恒大集团有限公司")) {
                                    String role = k == 0 ? "主诉案件" : "被诉案件";
                                    countMap.put(role, countMap.get(role) + 1);
                                    amountMap.put(role, amountMap.get(role).add(claimAmount));
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    System.out.println("Error processing JSON object at index " + i + ": " + e.getMessage());
                }
            }

            // 打印统计结果
            System.out.println("案件总数: " + countMap.get("案件总数") + "件，总涉案金额: " + amountMap.get("案件总数").divide(BigDecimal.valueOf(10000)) + "万元");
            System.out.println("新发案件: " + countMap.get("新发案件") + "件，涉案金额: " + amountMap.get("新发案件").divide(BigDecimal.valueOf(10000)) + "万元");
            System.out.println("结转案件: " + countMap.get("结转案件") + "件，涉案金额: " + amountMap.get("结转案件").divide(BigDecimal.valueOf(10000)) + "万元");
            System.out.println("主诉案件: " + countMap.get("主诉案件") + "件，涉诉金额: " + amountMap.get("主诉案件").divide(BigDecimal.valueOf(10000)) + "万元");
            System.out.println("被诉案件: " + countMap.get("被诉案件") + "件，涉诉金额: " + amountMap.get("被诉案件").divide(BigDecimal.valueOf(10000)) + "万元");
            System.out.println("处理终结案件: " + countMap.get("处理终结案件") + "件，涉案金额: " + amountMap.get("处理终结案件").divide(BigDecimal.valueOf(10000)) + "万元");
            System.out.println("尚未终结案件: " + countMap.get("尚未终结案件") + "件，涉案金额: " + amountMap.get("尚未终结案件").divide(BigDecimal.valueOf(10000)) + "万元");
            System.out.println("上诉期限内案件: " + countMap.get("上诉期限内案件") + "件，涉案金额: " + amountMap.get("上诉期限内案件").divide(BigDecimal.valueOf(10000)) + "万元");
        }




    static void getImplementInfo(JSONArray jsonArray){
        //立案时间 d_larq  2024 为新发
        //结案时间 d_jarq  2024 为执行完毕
        //申请执行标的金额 n_sqzxbdje
        //统计新发执行案件0件，金额0万元；往年结转案件0件、金额0万元；执行完毕（含执行终结0件、金额0万元）案件0件、金额0万元；正在执行（含终本执行0件、金额0万元）0件、金额0万元；被申请执行案件0件、金额0万元；申请人执行案件0件、金额0万元。

                // 初始化统计变量
                int newCaseCount = 0;
                BigDecimal newCaseAmount = BigDecimal.ZERO;

                int oldCaseCount = 0;
                BigDecimal oldCaseAmount = BigDecimal.ZERO;

                int completedCaseCount = 0;
                BigDecimal completedCaseAmount = BigDecimal.ZERO;

                int ongoingCaseCount = 0;
                BigDecimal ongoingCaseAmount = BigDecimal.ZERO;

                int appliedCaseCount = 0;
                BigDecimal appliedCaseAmount = BigDecimal.ZERO;

                int applicantCaseCount = 0;
                BigDecimal applicantCaseAmount = BigDecimal.ZERO;

                // 遍历 jsonArray 中的每个 JSON 对象
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject caseObj = jsonArray.getJSONObject(i);

                    // 获取相关字段
                    String filingDate = caseObj.getString("d_larq");
                    String closingDate = caseObj.getString("d_jarq");
                    BigDecimal claimAmount = caseObj.containsKey("n_sqzxbdje") ? new BigDecimal(caseObj.getString("n_sqzxbdje")) : BigDecimal.ZERO;

                    // 判断是否为新发案件
                    boolean isNewCase = filingDate != null && filingDate.startsWith("2024");
                    // 判断是否为执行完毕案件
                    boolean isCompletedCase = closingDate != null && closingDate.startsWith("2024");
                    // 判断是否为正在执行案件
                    boolean isOngoingCase = !isNewCase && !isCompletedCase && claimAmount.compareTo(BigDecimal.ZERO) > 0;

                    // 统计新发案件
                    if (isNewCase) {
                        newCaseCount++;
                        newCaseAmount = newCaseAmount.add(claimAmount);
                    } else if (!isNewCase) { // 往年结转案件
                        oldCaseCount++;
                        oldCaseAmount = oldCaseAmount.add(claimAmount);
                    }

                    // 统计执行完毕案件
                    if (isCompletedCase) {
                        completedCaseCount++;
                        completedCaseAmount = completedCaseAmount.add(claimAmount);
                    }

                    // 统计正在执行案件
                    if (isOngoingCase) {
                        ongoingCaseCount++;
                        ongoingCaseAmount = ongoingCaseAmount.add(claimAmount);
                    }

                    // 统计被申请执行案件
                    if (caseObj.containsKey("n_bsqzxbdje")) {
                        appliedCaseCount++;
                        appliedCaseAmount = appliedCaseAmount.add(new BigDecimal(caseObj.getString("n_bsqzxbdje")));
                    }

                    // 统计申请人执行案件
                    if (caseObj.containsKey("n_sqryzxbdje")) {
                        applicantCaseCount++;
                        applicantCaseAmount = applicantCaseAmount.add(new BigDecimal(caseObj.getString("n_sqryzxbdje")));
                    }
                }

                // 输出统计结果
                System.out.println("统计新发执行案件 " + newCaseCount + " 件，金额 " + newCaseAmount.divide(new BigDecimal("10000")) + " 万元；");
                System.out.println("往年结转案件 " + oldCaseCount + " 件，金额 " + oldCaseAmount.divide(new BigDecimal("10000")) + " 万元；");
                System.out.println("执行完毕（含执行终结）案件 " + completedCaseCount + " 件，金额 " + completedCaseAmount.divide(new BigDecimal("10000")) + " 万元；");
                System.out.println("正在执行（含终本执行）案件 " + ongoingCaseCount + " 件，金额 " + ongoingCaseAmount.divide(new BigDecimal("10000")) + " 万元；");
                System.out.println("被申请执行案件 " + appliedCaseCount + " 件，金额 " + appliedCaseAmount.divide(new BigDecimal("10000")) + " 万元；");
                System.out.println("申请人执行案件 " + applicantCaseCount + " 件，金额 " + applicantCaseAmount.divide(new BigDecimal("10000")) + " 万元；");





    }



    static void getNowYear(JSONArray jsonArray) {
        BigDecimal filingCount = BigDecimal.ZERO;
        BigDecimal filingAmount = BigDecimal.ZERO;
        BigDecimal closingCount = BigDecimal.ZERO;
        BigDecimal closingAmount = BigDecimal.ZERO;
        BigDecimal unclosedCount = BigDecimal.ZERO;
        BigDecimal unclosedAmount = BigDecimal.ZERO;

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject caseObj = jsonArray.getJSONObject(i);

            // 获取立案日期和起诉金额
            String filingDate = caseObj.getString("d_larq");
            BigDecimal claimAmount =null;
            if (caseObj.getString("n_qsbdje")!=null){
                 claimAmount = new BigDecimal(caseObj.getString("n_qsbdje"));
            }


            // 获取结案日期和结案金额
            String closingDate = caseObj.getString("d_jarq");
            BigDecimal closingAmountTemp = caseObj.containsKey("n_jabdje") ? new BigDecimal(caseObj.getString("n_jabdje")) : BigDecimal.ZERO;

            // 判断是否为2024年
            boolean isFiling2024 = filingDate.startsWith("2024");
            boolean isClosing2024 =closingDate!=null&& closingDate.startsWith("2024");

            // 判断是否未结案
            boolean isUnclosed = caseObj.containsKey("n_qsbdje") && caseObj.getString("n_qsbdje") != null && closingDate==null;

            // 判断金额是否大于50000000
            boolean isAmountGreaterThan50000000 =claimAmount!=null&& claimAmount.compareTo(new BigDecimal("50000000")) > 0;

            if (isFiling2024 && isAmountGreaterThan50000000) {
                filingCount = filingCount.add(BigDecimal.ONE);
                filingAmount = filingAmount.add(claimAmount);
            }

            if (isClosing2024 && isAmountGreaterThan50000000) {
                closingCount = closingCount.add(BigDecimal.ONE);
                closingAmount = closingAmount.add(closingAmountTemp);
            }

            if (isUnclosed && isFiling2024 && isAmountGreaterThan50000000) {
                unclosedCount = unclosedCount.add(BigDecimal.ONE);
                unclosedAmount = unclosedAmount.add(claimAmount);
            }
        }

        System.out.println("立案数量: " + filingCount);
        System.out.println("立案金额: " + filingAmount);
        System.out.println("结案数量: " + closingCount);
        System.out.println("结案金额: " + closingAmount);
        System.out.println("未结案数量: " + unclosedCount);
        System.out.println("未结案金额: " + unclosedAmount);
    }



    static void getMaxValue(JSONArray jsonArray) {
        // 用于统计每个立案案由的数量
        Map<String, Integer> laayCounts = new HashMap<>();
        // 用于统计每个立案案由的起诉金额总和
        Map<String, BigDecimal> laayAmounts = new HashMap<>();

        // 遍历 jsonArray 中的每个案件
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject caseObj = jsonArray.getJSONObject(i);

            // 获取立案案由
            String laay = caseObj.getString("n_laay");
            // 更新立案案由的数量
            laayCounts.put(laay, laayCounts.getOrDefault(laay, 0) + 1);

            // 获取起诉金额
            if (caseObj.containsKey("n_qsbdje") && caseObj.getString("n_qsbdje")!=null) {
                BigDecimal qsbdje = new BigDecimal(caseObj.getString("n_qsbdje"));
                // 更新立案案由的起诉金额总和
                laayAmounts.put(laay, laayAmounts.getOrDefault(laay, BigDecimal.ZERO).add(qsbdje));
            }
        }

        // 找出数量最多的3个立案案由
        List<Map.Entry<String, Integer>> countList = new ArrayList<>(laayCounts.entrySet());
        countList.sort(Map.Entry.<String, Integer>comparingByValue().reversed());
        List<Map.Entry<String, Integer>> top3ByCount = countList.subList(0, Math.min(3, countList.size()));

        // 找出金额最多的3个立案案由
        List<Map.Entry<String, BigDecimal>> amountList = new ArrayList<>(laayAmounts.entrySet());
        amountList.sort(Map.Entry.<String, BigDecimal>comparingByValue().reversed());
        List<Map.Entry<String, BigDecimal>> top3ByAmount = amountList.subList(0, Math.min(3, amountList.size()));

        // 输出结果
        System.out.println("数量最多的3个立案案由:");
        for (Map.Entry<String, Integer> entry : top3ByCount) {
            String laay = entry.getKey();
            int count = entry.getValue();
            BigDecimal amount = laayAmounts.get(laay);
            BigDecimal divisor = new BigDecimal("10000");
            BigDecimal result = amount.divide(divisor, 2, RoundingMode.HALF_UP);
            System.out.printf("立案案由: %s, 数量: %d, 金额: %s%n", laay, count, result);
        }

        System.out.println("金额最多的3个立案案由:");
        for (Map.Entry<String, BigDecimal> entry : top3ByAmount) {
            String laay = entry.getKey();
            int count = laayCounts.get(laay);
            BigDecimal amount = entry.getValue();
            BigDecimal divisor = new BigDecimal("10000");
            BigDecimal result = amount.divide(divisor, 2, RoundingMode.HALF_UP);
            System.out.printf("立案案由: %s, 数量: %d, 金额: %s%n", laay, count, result);
        }
    }



    static void getCaseYearNum(JSONArray jsonArray) {
        // 用于存储每年的统计数据
        Map<Integer, Map<String, BigDecimal>> yearStats = new HashMap<>();

        // 初始化每年的统计数据
        for (int year = 2022; year <= 2024; year++) {
            Map<String, BigDecimal> stats = new HashMap<>();
            stats.put("起诉金额", BigDecimal.ZERO);
            stats.put("结案金额", BigDecimal.ZERO);
            stats.put("总额", BigDecimal.ZERO);
            yearStats.put(year, stats);
        }

        // 遍历 jsonArray 中的每个案件
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject caseObj = jsonArray.getJSONObject(i);

            // 获取立案日期
            String larq = caseObj.getString("d_larq");
            int year = Integer.parseInt(larq.substring(0, 4));

            // 检查年份是否在 2022 到 2024 之间
            if (year >= 2022 && year <= 2024) {
                // 获取起诉金额
                BigDecimal qsbdje = caseObj.containsKey("n_qsbdje") && caseObj.getString("n_qsbdje")!=null ?
                    new BigDecimal(caseObj.getString("n_qsbdje")) : BigDecimal.ZERO;

                // 获取结案金额
                BigDecimal jabdje = caseObj.containsKey("n_jabdje") && caseObj.getString("n_jabdje")!=null ?
                    new BigDecimal(caseObj.getString("n_jabdje")) : BigDecimal.ZERO;

                // 更新统计数据
                Map<String, BigDecimal> stats = yearStats.get(year);
                stats.put("起诉金额", stats.get("起诉金额").add(qsbdje));
                stats.put("结案金额", stats.get("结案金额").add(jabdje));
                stats.put("总额", stats.get("总额").add(qsbdje).add(jabdje));
            }
        }

        // 计算年同比百分比
        for (int year = 2023; year <= 2024; year++) {
            Map<String, BigDecimal> currentYearStats = yearStats.get(year);
            Map<String, BigDecimal> previousYearStats = yearStats.get(year - 1);

            if (currentYearStats != null && previousYearStats != null) {
                Map<String, BigDecimal> additions = new HashMap<>();
                for (String key : currentYearStats.keySet()) {
                    BigDecimal currentYearValue = currentYearStats.get(key);
                    BigDecimal previousYearValue = previousYearStats.get(key);

                    // 计算同比增长率
                    BigDecimal yearOnYearPercentage = calculateYearOnYearPercentage(currentYearValue, previousYearValue);

                    additions.put(key + "同比增长%", yearOnYearPercentage);
                }
                currentYearStats.putAll(additions);
            }
        }

        // 输出结果
        for (int year = 2022; year <= 2024; year++) {
            Map<String, BigDecimal> stats = yearStats.get(year);
            if (stats != null) {
                System.out.println("年份: " + year);
                for (Map.Entry<String, BigDecimal> entry : stats.entrySet()) {
                    System.out.println(entry.getKey() + ": " + entry.getValue());
                }
                System.out.println();
            }
        }
    }
    private static BigDecimal calculateYearOnYearPercentage(BigDecimal currentYearValue, BigDecimal previousYearValue) {
        if (previousYearValue.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        return currentYearValue.subtract(previousYearValue)
            .divide(previousYearValue, 2, BigDecimal.ROUND_HALF_UP)
            .multiply(new BigDecimal("100"));
    }
    /**
     * 案件数量年份数量统计
     *
     * @param jsonArray
     * @return void
     * @author zhangjing
     * @create 2024/11/1
     **/
    static void getCaseNum(JSONArray jsonArray) {
        Map<String, Map<String, Integer>> statistics = new HashMap<>();

        // 初始化统计数据
        for (String year : new String[]{"2022", "2023", "2024"}) {
            Map<String, Integer> counts = new HashMap<>();
            counts.put("立案数", 0);
            counts.put("结案数", 0);
            statistics.put(year, counts);
        }
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject caseObj = jsonArray.getJSONObject(i);
            // 获取立案日期和结案日期
            String larq = caseObj.getString("d_larq");
            String jarq = null;
            try {
                jarq = caseObj.getString("d_jarq");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            // 统计
            updateStatistics(statistics, "立案数", larq);
            if (jarq != null) {
                updateStatistics(statistics, "结案数", jarq);
            }
        }
        System.out.println("案件数量统计: " + statistics.toString());
    }

    static void updateStatistics(Map<String, Map<String, Integer>> stats, String type, String date) {
        // 提取年份
        String year = date.substring(0, 4);
        // 检查年份是否在统计范围内
        if ("2022".equals(year) || "2023".equals(year) || "2024".equals(year)) {
            // 更新统计数据
            Map<String, Integer> counts = stats.get(year);
            int currentCount = counts.get(type);
            counts.put(type, currentCount + 1);
        }
    }

    /**
     * 金额计算
     *
     * @param jsonArray
     * @return void
     * @author zhangjing
     * @create 2024/11/1
     **/
    static void getJabdje(JSONArray jsonArray) {
        BigDecimal n_jabdje = BigDecimal.ZERO;
        LocalDate thresholdDate = LocalDate.parse("2021-01-01", DateTimeFormatter.ISO_LOCAL_DATE);
        int count = 0;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject cases = jsonArray.getJSONObject(i);
            //结案日期 d_jarq  立案日期 d_larq  统计出分三年 2022年 2023年 2024年 立案数 结案数 总数

            if (cases.containsKey("d_jarq") && cases.getString("d_jarq") != null) {
                String dateStr = cases.getString("d_jarq");
                LocalDate date = LocalDate.parse(dateStr, DateTimeFormatter.ISO_LOCAL_DATE);
                if (date.isAfter(thresholdDate)) {
                    if (cases.containsKey("n_jabdje") && cases.getString("n_jabdje") != null) {
                        BigDecimal amount = new BigDecimal(cases.getString("n_jabdje"));
                        n_jabdje = n_jabdje.add(amount);
                    }
                    count = count + 1;
                }
            }
//            if (cases.containsKey("n_jabdje") && cases.getString("n_jabdje")!=null) {
//                BigDecimal amount = new BigDecimal(cases.getString("n_jabdje"));
//                n_jabdje = n_jabdje.add(amount);
//            }
        }


        // 计算 n_jabdje / 10000
        BigDecimal divisor = new BigDecimal("10000");
        BigDecimal result = n_jabdje.divide(divisor, 2, RoundingMode.HALF_UP);

        System.out.println("案件数: " + count);
        System.out.println("总金额: " + n_jabdje.toPlainString());
        System.out.println("总金额 / 10000: " + result.toPlainString());
    }

    public static String convertTextToJson(String filePath) {
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String currentLine;
            while ((currentLine = br.readLine()) != null) {
                contentBuilder.append(currentLine).append("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return contentBuilder.toString();
    }
}
