package com.sino.publicclass.mapService;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Decoder;
import com.alibaba.fastjson.JSON;
import com.sino.publicclass.common.HttpClientDownload;

public class PoiAddress {
	private static Log log = LogFactory.getLog(PoiAddress.class);
	
	public static String getWeixinAddress(String lon,String lat){
		String convertGps = convertGps(lon,lat);
		String[] lonlat = convertGps.split("&");
		String address = getPoiAddress(lonlat[0],lonlat[1]);
		if(address!=null && !address.equals("")){
			address.replace("-", "").replace(" ", "").replace("-", "");
		}
		return address;
	}
	
	
	private static String convertGps(String lon,String lat){
		try {
			if (lon != null && lat != null) {
				
				String urlString = "http://api.map.baidu.com/ag/coord/convert?from=0&to=4&x="+lon+"&y="+lat;

				HttpClientDownload httpDown = new HttpClientDownload();
				httpDown.setFileUrl(urlString);
				if (httpDown.download()) {
					byte[] httpb = httpDown.getData();
					String data = new String(httpb, "utf-8");

					Map map = (Map) JSON.parse(data);
					
					String x = (String)map.get("x");
					String y = (String)map.get("y");
					
					BASE64Decoder decoder = new BASE64Decoder();   
					String lonX =new String(decoder.decodeBuffer(x),"UTF-8");
					String latY =new String(decoder.decodeBuffer(y),"UTF-8");
					//log.error(lonX+"&"+latY);
					return lonX+"&"+latY;
					
				}
			}
		} catch (Exception ee) {
			log.error(ee.getMessage());
		}
		return "";
	}
	
	private static String getPoiAddress(String lon,String lat){
		try {
			if (lon != null && lat != null) {
			
				String urlString = "http://api.map.baidu.com/geocoder/v2/?" +
						"ak=UbOsORKwX7HCIbmaBxrEzg0D" +
						"&callback=renderReverse" +
						"&location="+lat+","+lon +
						"&output=json&pois=1";

				HttpClientDownload httpDown = new HttpClientDownload();
				httpDown.setFileUrl(urlString);
				if (httpDown.download()) {
					byte[] httpb = httpDown.getData();
					String data = new String(httpb, "utf-8");
					String jsonStr = data.substring(data.indexOf("{"), data.length()-1);
					Map map = (Map) JSON.parse(jsonStr);
					Map resultMap = (Map)map.get("result");
					String address = (String)resultMap.get("formatted_address");
					return address;
				}
			}
		} catch (Exception ee) {
			log.error(ee.getMessage());
		}
		return "";
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException, IOException{
		String dd = PoiAddress.getPoiAddress("121.494867", "31.205209");
		System.out.println(dd);

		
	}

}
