package com.sagacloud.dict;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sagacloud.utils.OssUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * Created by wo on 10/14/19.
 */
public class TlStaticInfo {
    private static final Logger log = LoggerFactory.getLogger(TlStaticInfo.class);
    //code -> name
    private static Map<String, String> code2name = new HashMap<>();
    //code -> children codes
    private static Map<String, Set<String>> toChildren = new HashMap<>();

    static {
        try {
            JSONArray arr = JSONObject.parseObject(OssUtils.getFileAsString("property/Dictionary/toolRel.json")).getJSONArray("all");
            for (int i = 0; i < arr.size(); i++) {
                JSONObject item = arr.getJSONObject(i);
                code2name.put(item.getString("code"), item.getString("name"));
                if(item.get("content") != null){
                    JSONArray children = item.getJSONArray("content");
                    Set<String> subSet = new HashSet<>();
                    for (int j = 0; j < children.size(); j++) {
                        JSONObject child = children.getJSONObject(j);
                        code2name.put(child.getString("code"), child.getString("name"));
                        subSet.add(child.getString("code"));
                        if (child.get("content") != null) {
                            JSONArray grChildren = child.getJSONArray("content");
                            Set<String> childSet = new HashSet<>();
                            for (int k = 0; k < grChildren.size(); k++) {
                                JSONObject grChild = grChildren.getJSONObject(k);
                                code2name.put(grChild.getString("code"), grChild.getString("name"));
                                childSet.add(grChild.getString("code"));
                            }
                            toChildren.put(child.getString("code"), childSet);
                        }
                    }
                    toChildren.put(item.getString("code"), subSet);
                }
            }
        } catch (Exception e) {
            log.error("",e);
        }
    }

    public static Map<String, String> getCode2name() {
        return code2name;
    }

    public static Map<String, Set<String>> getToChildren() {
        return toChildren;
    }
}
