package cn.util.china;

import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import cn.component.context.JsonFile;
import cn.util.core.IsKit;

public class CityUtil 
{
    /**依据城市名获取其所属的省名称*/
	public static String getProvinceByCity(String dir, String city)
	{
		if (IsKit.isNullOrEmpty(city) || city.length()< 2) { 
			return null;
		}
		JSONObject jsonObject = null;
		String jsonStr = JsonFile.readJSON(dir);
		if (IsKit.isNullOrEmpty(jsonStr)) { 
			return null;
		}
		jsonObject = JSONObject.parseObject(jsonStr);
		for (String item : jsonObject.keySet())
		{
			JSONArray jsonArray = jsonObject.getJSONArray(item);
			for (int i = 0,loop=jsonArray.size(); i < loop; ++i) {
				if (jsonArray.getString(i).contains(city) || item.contains(city)){
					if (jsonArray.getString(i).length() <= city.length()) {
						return item;
					}
				}
			}
		}
		return null;
	}   
	/**依据省名称获取该省的所有城市名称*/
	public static List<String> getCityByProvince(String dir, String province)
	{
		if (IsKit.isNullOrEmpty(province) || province.length()< 2) { 
			return null;
		}
		List<String> cityList = new ArrayList<String>();
		JSONObject jsonObject = null;
		String jsonStr = JsonFile.readJSON(dir);
		if (IsKit.isNullOrEmpty(jsonStr)) { 
			return null;
		}
		jsonObject = JSONObject.parseObject(jsonStr);
		for (String item : jsonObject.keySet()) {
			JSONArray jsonArray = jsonObject.getJSONArray(item);
			if (item.contains(province)) {
				for (int i = 0,loop=jsonArray.size(); i < loop; ++i) {
					cityList.add(jsonArray.getString(i));
				}
			}
		}
		return cityList;
	}
	/**返回各省的名称 */
	public static List<String> getAllProvince(String dir)
	{
		if (IsKit.isNullOrEmpty(dir)) { 
			return null;
		}	
		List<String> cityList = new ArrayList<String>();
		JSONObject jsonObject = null;
        	
		String jsonStr = JsonFile.readJSON(dir);
		if (IsKit.isNullOrEmpty(jsonStr)) { 
			return null;
		}		
		jsonObject = JSONObject.parseObject(jsonStr);
		for (String item : jsonObject.keySet()) {
			cityList.add(item);
		}
		return cityList;
	}

	public static void main(String[] args) {
		System.out.println(getAllProvince("D:/city.json"));
		//System.out.println(getCityByProvince("D:/city.json","河南"));
		//System.out.println(getProvinceByCity("D:/city.json","漯河"));
	}

}
