package com.jianshui.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Set;

/**
 * @Description 通用工具类
 * @Author 巩权林
 * @Date 2021/4/17 13:27
 **/
public class ElephantCommonUtils {


    /**
     * 将key的大写字母全部转为小写，大象返回的值第一个是小写后面的都是大写，极其坑
     *
     * @param data
     * @return
     */
    public static JSONArray changeEleKeyToLower(JSONArray data) {
        JSONArray tempJSONArray = new JSONArray();
        if(data == null || data.size() == 0){
            return tempJSONArray;
        }
        for (Object tempObject : data) {
            JSONObject tempJSONObject = (JSONObject) tempObject;
            tempJSONObject = changeEleJSONObjectKeyToLower(tempJSONObject);
            tempJSONArray.add(tempJSONObject);
        }
        return tempJSONArray;
    }

    /**
     * 处理大象的jsonobject Key为小写
     *
     * @param data
     * @return
     */
    public static JSONObject changeEleJSONObjectKeyToLower(JSONObject data) {
        JSONObject rtJson = new JSONObject();
        Set<String> keys = data.keySet();
        for (String k : keys) {
            // 单独处理大象的detailList
            if (k.equals("detailList")) {
                JSONArray detailArray = data.getJSONArray(k);
                detailArray = changeEleKeyToLower(detailArray); // 递归查询处理detailList的问题
                rtJson.put(k, detailArray);
                continue;
            }
            rtJson.put(k.toLowerCase(), data.get(k));
        }
        return rtJson;
    }

    /**
     * 将JSONObject的key转为小写
     *
     * @param data
     * @return
     */
    public static JSONObject changeJSONObjectKeyToLower(JSONObject data) {
        JSONObject rtJson = new JSONObject();
        Set<String> keys = data.keySet();
        for (String k : keys) {
            rtJson.put(k.toLowerCase(), data.get(k));
        }
        return rtJson;
    }

    /**
     * 将JsonArray的key转为小写
     *
     * @param jsonArray
     * @return
     */
    public static JSONArray changeJSONArrayKeyToLower(JSONArray jsonArray) {
        JSONArray tempJSONArray = new JSONArray();
        for (Object tempObject : jsonArray) {
            JSONObject tempJSONObject = (JSONObject) tempObject;
            tempJSONObject = changeJSONObjectKeyToLower(tempJSONObject);
            tempJSONArray.add(tempJSONObject);
        }
        return tempJSONArray;
    }
}
