package com.liquidnet.service.kylin.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.liquidnet.commons.lang.util.JsonUtils;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 读取城市
 * </p>
 *
 * @author jiangxiulong
 * @since 2022-01-06
 */
public class CityJsonUtils {
    private static final Map<String, Integer> cityMap;
    static {
        cityMap = reload();
    }


    public static Map<String, Integer> reload() {
        Map<String, Integer> cityMap = new HashMap<>();
        String jsonStr = "";
        Reader reader = null;
        try {
            reader = new InputStreamReader(CityJsonUtils.class.getClassLoader().getResourceAsStream("city_2021.json"));
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            jsonStr = sb.toString();
        } catch (IOException e) {
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
        JsonNode jsonNode = JsonUtils.fromJson(jsonStr, JsonNode.class);
        String name = "name", adcode = "adcode";
        for (JsonNode node : jsonNode) {
            cityMap.put(node.get(name).asText(), node.get(adcode).asInt());
        }
        return cityMap;
    }

    public static Integer get(String cityName) {
        return cityMap.get(cityName);
    }

    public static void main(String[] args) {
        Integer integer = CityJsonUtils.get("新竹市");
        System.out.println(integer);
    }
}