package com.yeejoin.amos.boot.module.jyjc.biz.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;

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

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

    private static String getNextKey(String startKey, String targetKey) {
        if (Strings.isNullOrEmpty(targetKey)) {
            return null;
        }
        String[] keys = targetKey.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 targetKey) {
        try {
            Integer integer = Integer.valueOf(startKey);
            JSONObject jsonObject = originObject.getJSONObject(integer);
            Object targetObject = getValueFromJSONObjectByKey(jsonObject, getNextKey(startKey, targetKey),
                    targetKey);
            if (targetObject != null) {
                return targetObject;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return null;
    }

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