package com.tykj.workflowcore.workflow_editer.util;

import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Set;

/**
 * ClassName:    MapUtils
 * Package:    com.tykj.workflowcore.workflow_editer.util
 * Description:
 * Datetime:    2021/3/30   16:15
 *
 * @Author: zsp
 */
public class MapUtils {
    public static void loopMap(Map m1, String p, Map m2) {
        m1.forEach((key, value) -> {
            Set mapKeySetByPath = getMapKeySetByPath(m2, p + "." + key);
            System.out.println(p + "." + key);
            System.out.println(mapKeySetByPath);
            if (mapKeySetByPath!=null){
                mapKeySetByPath.forEach( (keyStr)->{
                    if (!m1.containsKey(keyStr)){
                        m1.put(keyStr,getMapByPath(m2,p + "." + keyStr));
                    }
                });
            }
            if (value instanceof Map) {
                String path;
                if (StringUtils.isEmpty(p)) {
                    path =  (String) key;
                } else {
                    path = p + "." + key;
                }
                loopMap((Map) value, path, m2);
            } else {
                if (!StringUtils.isEmpty(p)) {
                    String path = p + "." + key;
                    Object result = getMapByPath(m2, path);
                    if (result != null) {
                        m1.put(key, result);
                    }
                }
            }
        });
    }

    public static Object getMapByPath(Map m2, String path) {
        int point = path.indexOf(".");
        if (point==0){
            //第一层
            Object r = m2.get(path.substring(1));
            return r;
        }
        if (point == -1) {
            //已经递归到最后一层了
            Object r = m2.get(path);
            return r;
        }
        String key = path.substring(0, point);
        String last = path.substring(point + 1);
        Object result = m2.get(key);
        if (result == null) {
            return null;
        } else {
            try {
                return getMapByPath((Map) result, last);
            } catch (Exception e) {
                return null;
            }
        }
    }

    public static Set getMapKeySetByPath(Map m2, String path) {
        int point = path.indexOf(".");
        if (point <= 0) {
            Set r = m2.keySet();
            return r;
        }
        String key = path.substring(0, point);
        String last = path.substring(point + 1);
        Object result = m2.get(key);
        if (result == null) {
            return null;
        } else {
            try {
                return getMapKeySetByPath((Map) result, last);
            } catch (Exception e) {
                return null;
            }
        }
    }
}
