package com.ruoyi.kaohe.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.*;

public class JsonDeepMerge {
    /**
     * 深度合并json对象
     * @param target
     * @param source
     */
    private static void deepMerge(JSONObject target, JSONObject source) {
        Iterator<String> keys = source.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            Object sourceValue = source.get(key);
            if (target.has(key)) {
                Object targetValue = target.get(key);
                if (sourceValue instanceof JSONObject && targetValue instanceof JSONObject) {
                    deepMerge((JSONObject) targetValue, (JSONObject) sourceValue);
                } else if (!targetValue.equals(sourceValue)) {
                    target.put(key, sourceValue);
                }
            } else {
                target.put(key, sourceValue);
            }
        }
    }
    //根据某个相同key值，整合其他相同层级的key数据到一起，然后返回新的JSONArray数据
    public static JSONArray mergeByKey(JSONArray array, String mergeKey) {
        JSONArray result = new JSONArray();
        for (int i = 0; i < array.length(); i++) {
            JSONObject current = array.getJSONObject(i);
            String keyValue = current.getString(mergeKey);
            boolean merged = false;

            for (int j = 0; j < result.length(); j++) {
                JSONObject existing = result.getJSONObject(j);
                if (existing.getString(mergeKey).equals(keyValue)) {
                    deepMerge(existing, current);
                    merged = true;
                    break;
                }
            }

            if (!merged) {
                result.put(current);
            }
        }
        return result;
    }
    public static void main(String[] args) {
        String jsonStr = "[{\"khdx\":\"生命科学系\",\"jxdwldbzkhzf\":{\"ejdwmbglyjxkhcj\":{\"djyxzmbrw\":{\"khx1\":100,\"khx1_zb\":0.2,\"khx2\":0,\"khx2_zb\":0.1,\"khx3\":0,\"khx3_zb\":0.1,\"khx4\":0,\"khx4_zb\":0.1,\"khx5\":0,\"khx5_zb\":0.1,\"khx6\":0,\"khx6_zb\":0.1,\"khx7\":0,\"khx7_zb\":0.1,\"khx8\":0,\"khx8_zb\":0.1,\"khx9\":0,\"khx9_zb\":0.05,\"khx10\":97,\"khx10_zb\":0.1,\"khx11\":0,\"khx11_zb\":0.1},\"djyxzmbrw_df\":29.7,\"djyxzmbrw_zb\":0.1,\"djyxzmbrw_zsfs\":2.97}}},{\"khdx\":\"生命科学系\",\"jxdwldbzkhzf\":{\"ejdwmbglyjxkhcj\":{\"syfz\":{\"khx1\":0,\"khx1_zb\":0.3,\"khx2\":0,\"khx2_zb\":0.3,\"khx3\":0,\"khx3_zb\":0.4},\"syfz_df\":0,\"syfz_zb\":0.9,\"syfz_zsfs\":0}}},{\"khdx\":\"生命科学系\",\"jxdwldbzkhzf\":{\"mzcp\":{\"khx1\":{\"avgScore\":0,\"optionA\":0,\"optionB\":0,\"optionC\":0,\"optionD\":0,\"percentage\":0.3},\"khx2\":{\"avgScore\":0,\"optionA\":0,\"optionB\":0,\"optionC\":0,\"optionD\":0,\"percentage\":0.3},\"khx3\":{\"avgScore\":0,\"optionA\":0,\"optionB\":0,\"optionC\":0,\"optionD\":0,\"percentage\":0.4}},\"mzcp_df\":0,\"mzcp_zb\":0.3,\"mzcp_zsfs\":0}},{\"khdx\":\"生命科学系\",\"jxdwldbzkhzf\":{\"cx\":{\"khx1\":0},\"cx_df\":0}}]";
        JSONArray array = new JSONArray(jsonStr);
        JSONArray merged = mergeByKey(array, "khdx");
        System.out.println(merged.toString(2));
    }

    public static String jsonGroupSum(JSONArray jsonInput,String groupKey,String sumKey) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        // 解析JSON数组为List<Map>
        List<Map<String, Object>> inputList = mapper.readValue(jsonInput.toString(), List.class);

        // 使用Map按khdx分组并累加值
        Map<String, BigDecimal> sumMap = new HashMap<>();
        for (Map<String, Object> item : inputList) {
            String khdx = (String) item.get(groupKey);
            BigDecimal value=BigDecimal.ZERO;
            if(item.get(sumKey)!=null){   //非空判断
                value =  new BigDecimal(item.get(sumKey).toString());
            }
            sumMap.merge(khdx, value, BigDecimal::add);
        }

        // 转换为目标结构List<Map>
        List<Map<String, Object>> result = new ArrayList<>();
        sumMap.forEach((khdx, sum) -> {
            Map<String, Object> entry = new HashMap<>();
            entry.put(groupKey, khdx);
            entry.put(sumKey, sum);
            result.add(entry);
        });

        // 输出结果JSON
        String jsonOutput = mapper.writeValueAsString(result);
      //  System.out.println(jsonOutput);
        return jsonOutput;
    }
}
