package com.yeejoin.amos.boot.biz.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Strings;

/**
 * @Author: xl
 * @Description: json快速取值
 * @Date: 2022/5/12 11:11
 */
public class JsonValueUtils {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static Object getValueByKey(Object originObject, String startKey,
                               String targetKeyExpression) {
        if (Strings.isNullOrEmpty(startKey)) {
            return originObject;
        }
        if (originObject instanceof JSONObject) {
            return getValueFromJSONObjectByKey((JSONObject) originObject, startKey,
                    targetKeyExpression);
        }
        if (originObject instanceof JSONArray) {
            return getValueFromJSONArrayByKey((JSONArray) originObject, startKey,
                    targetKeyExpression);
        }
        return null;
    }

    private static String getNextKey(String startKey, String targetKeyExpression) {
        if (Strings.isNullOrEmpty(targetKeyExpression)) {
            return null;
        }
        String[] keys = targetKeyExpression.split("\\.");
        for (int i = 0; i < keys.length; i++) {
            if (keys[i].equals(startKey) && (i < keys.length - 1)) {
                return keys[i + 1];
            }
        }
        return null;
    }

    private static Object getValueFromJSONArrayByKey(JSONArray originObject,
                                                               String startKey,
                                                               String targetKeyExpression) {
        try {
            Integer integer = Integer.valueOf(startKey);
            JSONObject jsonObject = originObject.getJSONObject(integer);
            Object targetObject = getValueFromJSONObjectByKey(jsonObject, getNextKey(startKey, targetKeyExpression),
                    targetKeyExpression);
            if (targetObject != null) {
                return targetObject;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Object getValueFromJSONObjectByKey(JSONObject originObject,
                                                                String startKey,
                                                                String targetKeyExpression) {
        Object object = originObject.get(startKey);
        return object != null
                ? getValueByKey(object, getNextKey(startKey, targetKeyExpression),
                targetKeyExpression)
                : null;
    }

    public static void main(String[] args) {
        String a = "{\"agencyCode\":\"jcs\",\"agencyUserType\":\"NORMAL\",\"appCodes\":[\"AMOS_ADMIN\",\"studio_normalapp_3144441\",\"studio_normalapp_3157169\",\"studio_normalapp_3168830\",\"studio_normalapp_3206513\",\"studio_normalapp_3230377\"],\"companyDepartments\":{},\"companys\":[{\"agencyCode\":\"jcs\",\"companyName\":\"咸阳机场\",\"companyOrgCode\":49,\"level\":\"headquarter\",\"orgCode\":\"49\",\"parentId\":0,\"sequenceNbr\":1397143494413381633}],\"createTime\":1625058001000,\"lockStatus\":\"UNLOCK\",\"orgNames\":\"咸阳机场(admin\\\\idx_report_data\\\\idx_report_audit\\\\Safety_Supervision_Instruct_Report\\\\Safety_Supervision_Rectify_Report\\\\Safety_Supervision_Rectify_Affirm)\",\"orgRoleName\":{1397143494413381633:\"咸阳机场(admin\\\\idx_report_data\\\\idx_report_audit\\\\Safety_Supervision_Instruct_Report\\\\Safety_Supervision_Rectify_Report\\\\Safety_Supervision_Rectify_Affirm)\"},\"orgRoleSeqs\":{1397143494413381633:[1397143493910065153,1484425579646689281,1484425839416713217,1536242867071119362,1536243072738816002,1536243348623355905]},\"orgRoles\":{1397143494413381633:[{\"agencyCode\":\"jcs\",\"roleDesc\":\"admin\",\"roleName\":\"admin\",\"roleType\":\"admin\",\"sequenceNbr\":1397143493910065153},{\"agencyCode\":\"jcs\",\"roleDesc\":\"指标系统-数据填报\",\"roleName\":\"idx_report_data\",\"roleType\":\"admin\",\"sequenceNbr\":1484425579646689281},{\"agencyCode\":\"jcs\",\"roleDesc\":\"指标系统-数据审核\",\"roleName\":\"idx_report_audit\",\"roleType\":\"admin\",\"sequenceNbr\":1484425839416713217},{\"agencyCode\":\"jcs\",\"roleDesc\":\"安全监察-填报指令书\",\"roleName\":\"Safety_Supervision_Instruct_Report\",\"roleType\":\"admin\",\"sequenceNbr\":1536242867071119362},{\"agencyCode\":\"jcs\",\"roleDesc\":\"安全监察-企业整改\",\"roleName\":\"Safety_Supervision_Rectify_Report\",\"roleType\":\"admin\",\"sequenceNbr\":1536243072738816002},{\"agencyCode\":\"jcs\",\"roleDesc\":\"安全监察-整改确认\",\"roleName\":\"Safety_Supervision_Rectify_Affirm\",\"roleType\":\"admin\",\"sequenceNbr\":1536243348623355905}]},\"password\":\"1CABE8C68B956573D0709013FD61CA5F\",\"passwordReset\":false,\"realName\":\"邢磊\",\"sequenceNbr\":1410417876975759361,\"userId\":\"3187681\",\"userName\":\"jcs_xl\"}";
        System.out.println(getValueByKey(JSONObject.parse(a), "companys", "companys.0.sequenceNbr"));
    }

    /**
     * JSON字段添加
     *
     * @param jsonString JSON字符串 示例 {"a":{"b":{"c":1}}}
     * @param keyPath    字段路径 示例 "a.b.c"
     * @param field      字段名 示例 "name"
     * @param value      字段值 示例 "张三"
     * @return 修改后的JSON字符串 {"a":{"b":{"c":1,"name":"张三"}}}
     */
    public String jsonFieldAdd(String jsonString, String keyPath, String field, String value) throws JsonProcessingException {
        JsonNode rootNode = objectMapper.readTree(jsonString);

        // 修复路径格式（添加前导/）
        JsonNode targetNode = rootNode.at('/' + keyPath.replace(".", "/"));

        if (targetNode.isArray()) {
            ArrayNode arrayNode = (ArrayNode) targetNode;
            // 替换现有字段或添加新字段
            boolean replaced = false;
            for (JsonNode node : arrayNode) {
                if (node.has("key") && node.get("key").asText().equals(field)) {
                    ((ObjectNode) node).put("label", value);
                    replaced = true;
                    break;
                }
            }
            if (!replaced) {
                addNewArrayField(arrayNode, field, value);
            }
        } else if (targetNode.isObject()) {
            boolean replaced = false;
            if (targetNode.has("key") && targetNode.get("key").asText().equals(field)) {
                ((ObjectNode) targetNode).put("label", value);
                replaced = true;
            }
            if (!replaced) {
                ((ObjectNode) targetNode).put(field, value);
            }
        }

        // 修复返回值：序列化修改后的rootNode
        return objectMapper.writeValueAsString(rootNode);
    }

    // 添加新的 key-value 字段
    private static void addNewArrayField(ArrayNode arrayNode, String newKey, String newLabel) {
        ObjectNode newField = objectMapper.createObjectNode();
        newField.put("key", newKey);
        newField.put("label", newLabel);
        arrayNode.add(newField);
    }
}
