package com.sino.publicclass.mapService;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.alibaba.fastjson.JSON;

public class SpatialInfoCenter {
	private static Log log = LogFactory.getLog(SpatialInfoCenter.class);
	
	/**
	 * 根据经纬度，查询当前点的地理位置信息
	 * @param lon
	 * @param lat
	 * @return
	 */
	public static String getSpatialInfo(String lon,String lat){
		String address = "";
		try{
			Map<String,String> spatialMap = null;
			SpatialInfo info = SpatialInfoCenter.getSpatialMessage(lon, lat);
			if(info != null){
				Map<String,String> poiMap=info.getPoiMap();
				Map<String,String> crossMap=info.getCrossMap();
				Map<String,String> roadMap=info.getRoadMap();
				if(poiMap!=null && !"".equals(poiMap.get("name")) ){
					spatialMap = poiMap;
				}else if(crossMap!=null && !"".equals(crossMap.get("name"))){
					spatialMap = crossMap;
				}else if(roadMap!=null && !"".equals(roadMap.get("name"))){
					spatialMap = roadMap;
				}else{
					
				}
			}
			
			if(spatialMap.get("address")!=null){
				address = spatialMap.get("address");
			}
			if(spatialMap.get("name")!=null && !spatialMap.get("name").equals("")){
				address = address + "(" + spatialMap.get("name") + ")";
			}
		}catch (Exception ee) {
			
		}
		return address;
	}
	
	
	public static SpatialInfo getSpatialMessage(String x,String y){
		SpatialInfo info = null;
		//String a_k = "9777c99f8e963972429e689974a35b0bd9ee35a5c8306ae139ac98f432932286151dc0ec55580eca";
		String a_k = "8ba7c38d14da8249f144e8505c49278c2476d8f994db5243eb32207e56ac9d44cb5faf15e2e2a132";
		String urlString = null;
		String spXml = null;
		String postParam = null;
		try {
			if (x != null && y != null) {
				spXml = "<?xml version=\"1.0\" encoding=\"GB2312\"?><spatial_request method=\"searchPoint\"><x>"
						+ String.valueOf(x)
						+ "</x><y>"
						+ String.valueOf(y)
						+ "</y><poiNumber>10</poiNumber><range>300</range><pattern>0</pattern><roadLevel>0</roadLevel></spatial_request>";

				spXml = URLEncoder.encode(spXml, "GB2312");
				postParam = "highLight=false&config=SPAS&ver=2.0&resType=json&enc=GB2312&a_k="+ a_k + "&spatialXml=" + spXml;

				
				//urlString = "http://www.sino-assist.net:8081/sisserver";
				urlString = "http://search1.mapabc.com/sisserver";

				URL url = new URL(urlString);
				URLConnection urlc = url.openConnection();
				HttpURLConnection httpConnection = (HttpURLConnection) urlc;
				httpConnection.setRequestMethod("POST");
				httpConnection.setDoInput(true);
				httpConnection.setDoOutput(true);
				httpConnection.connect();

				OutputStreamWriter osw = new OutputStreamWriter(
						new BufferedOutputStream(
								httpConnection.getOutputStream()));
				osw.write(postParam);
				osw.flush();
				osw.close();

				BufferedReader br = new BufferedReader(
						new InputStreamReader(
								httpConnection.getInputStream()));
				String line = null;
				StringBuffer sb = new StringBuffer("");
				while ((line = br.readLine()) != null)
					sb.append(line);
				httpConnection.disconnect();
				//System.out.println(sb.toString());
				info = parseMessage(sb.toString());
			}
		} catch (Exception ee) {
			log.error("exception", ee);
		}
		return info;
	}
	
	private static SpatialInfo parseMessage(String message){
		SpatialInfo info =new SpatialInfo();
		Map<String,String> crossMap = null;
		Map<String,String> roadMap = null;
		Map<String,String> poiMap = null;
		String province = "";
		String city = "";
		Map map = (Map) JSON.parse(message);
		Map spatialMap=(Map)map.get("SpatialBean");
		if(spatialMap.get("Province")!=null && !spatialMap.get("Province").equals("")){
			province=(String)((Map)spatialMap.get("Province")).get("name");
			province = province==null?"":province;
		}
		if(spatialMap.get("District")!=null && !spatialMap.get("District").equals("")){
			city=(String)((Map)spatialMap.get("District")).get("name");
			city = city==null?"":city;
		}
		if(spatialMap.get("crossPoiList")!=null && !spatialMap.get("crossPoiList").equals("")){
			List crossList=(List)spatialMap.get("crossPoiList");
			if(crossList!=null&&crossList.size()>0){
				crossMap=new HashMap<String,String>();
				String crossName=(String)((Map)crossList.get(0)).get("name");
				crossMap.put("name", crossName);
			}
		}
		
		if(spatialMap.get("roadList")!=null && !spatialMap.get("roadList").equals("")){
			List roadList = (List)spatialMap.get("roadList");
			if(roadList.size()>0){
				roadMap = new HashMap<String,String>();
				String roadName=(String)((Map)roadList.get(0)).get("name");
				roadMap.put("name", roadName);
			}
		}
		
		if(spatialMap.get("poiList")!=null && !spatialMap.get("poiList").equals("")){
			List poiList = (List)spatialMap.get("poiList");
			if(poiList.size()>0){
				Map pMap = (Map)poiList.get(0);
				String poiName=(String)pMap.get("name");
				String address = (String)pMap.get("address");
				String tel = (String)pMap.get("tel");
				poiMap = new HashMap<String,String>();
				poiMap.put("name", poiName);
				poiMap.put("address", province+city+address);
				poiMap.put("tel", tel);
			}
		}
		
		info.setCrossMap(crossMap);
		info.setRoadMap(roadMap);
		info.setPoiMap(poiMap);
        return info;
	}
	

	
	
	
	public static void main(String[] args){
       String name = SpatialInfoCenter.getSpatialInfo("121.49879196221", "31.213175825735");
       
       
       
	   System.out.println(name);
	}

}
