package thyyxxk.webserver.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

@Slf4j
public class BaiduMapGeocoderUtil {

    /**
     * 百度地图 Api调用相关的百度AK
     */
    public final static String BAIDU_MAP_AK = "10rlflGd5szufZSPSrn59FYYxBkl2voy";

    public static JSONObject getAddressInfoByLngAndLat(String rawAddress) {
        String[] points = getlocation(rawAddress);
        if (null == points) {
            return null;
        }
        JSONObject obj;
        String location = points[1] + "," + points[0];
        String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + BAIDU_MAP_AK + "&output=json&coordtype=wgs84ll&location=" + location;
        try {
            String json = loadJSON(url);
            obj = JSONObject.parseObject(json);
            String success = "0";
            String status = String.valueOf(obj.get("status"));
            if (success.equals(status)) {
                JSONObject result = obj.getJSONObject("result");
                return result.getJSONObject("addressComponent");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String loadJSON(String url) {
        StringBuilder json = new StringBuilder();
        try {
            URL oracle = new URL(url);
            URLConnection yc = oracle.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), StandardCharsets.UTF_8));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (IOException ignored) {
        }
        return json.toString();
    }

    public static String[] getlocation(String rawAddress) {
        rawAddress = rawAddress.replaceAll(" ", "").replaceAll("\u007F", "");
        String url = "http://api.map.baidu.com/geocoding/v3/?address=" + rawAddress +
                "&output=xml&ak=" + BAIDU_MAP_AK + "&callback=showLocation";
        Document doc;
        java.net.HttpURLConnection conn = null;
        InputStream ins = null;
        SAXReader reader;
        String[] result = new String[2];
        try {
            URL conURL = new URL(null, url);
            conn = (HttpURLConnection) conURL.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            ins = conn.getInputStream();
            reader = new SAXReader();
            doc = reader.read(ins);
            Element root = doc.getRootElement();
            Element e = root.element("result");
            Element location = e.element("location");
            Element lng = location.element("lng");
            Element lat = location.element("lat");
            String lng1 = lng.asXML();
            String lat1 = lat.asXML();
            lng1 = lng1.substring(lng1.indexOf("<lng>") + 5, lng1.indexOf("</lng>"));
            lat1 = lat1.substring(lat1.indexOf("<lat>") + 5, lat1.indexOf("</lat>"));

            result[0] = lng1;
            result[1] = lat1;

            ins.close();
            conn.disconnect();
        } catch (Exception e) {
            log.info("地址转化报错信息:{}", rawAddress);
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (ins != null) {
                    ins.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return result;
    }

    public static String getlocationString(String rawAddress) {
        return StringUtil.stringArrayToCharacter(getlocation(rawAddress));
    }


}

