package com.tuoheng.admin.utils;

import com.alibaba.fastjson.JSONObject;
import com.tuoheng.common.config.CommonConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Map;

@Slf4j
public class GaodeUtil {

    /**
     * 逆地理编码
     *
     * @param longitude 经度
     * @param latitude 纬度
     * @return
     */
    public static String getGaodeAddress(String longitude, String latitude) {
        String address = null;
        JSONObject json = new JSONObject();
        try {
            json.put("key", CommonConfig.gaodeKey);
            json.put("location", longitude + "," + latitude);
            log.info("调用高德逆地理编码API请求参数:" + json);
            String result = doGet("https://restapi.amap.com/v3/geocode/regeo", json, null);
            log.info("调用高德逆地理编码API成功:" + result);
            JSONObject resultJson = JSONObject.parseObject(result.trim());
            if("1".equals(resultJson.getString("status"))){
                address = resultJson.getJSONObject("regeocode").getString("formatted_address");
            }
        } catch (Exception e) {
            log.error("逆地理编码方法异常：", e);
        }

        return address;
    }



    /**
     * 高德坐标转换
     *
     * @param longitude 经度
     * @param latitude 纬度
     * @return
     */
    public static JSONObject getGaodeCoordinate(String longitude, String latitude) {
        JSONObject json = new JSONObject();
        JSONObject param = new JSONObject();
        try {
            //取六位小数
            DecimalFormat df = new DecimalFormat("0.000000");
            param.put("key", CommonConfig.gaodeKey);
            param.put("locations", df.format(Double.valueOf(longitude)) + "," + df.format(Double.valueOf(latitude)));
            param.put("coordsys", "gps");

            log.info("调用高德坐标转换API请求参数:" + param);
            String result = doGet("https://restapi.amap.com/v3/assistant/coordinate/convert", param, null);
            log.info("调用高德坐标转换API成功:" + result);
            JSONObject resultJson = JSONObject.parseObject(result.trim());
            if("1".equals(resultJson.getString("status"))){
                String locations = JSONObject.parseObject(result).getString("locations");
                String lonStr = locations.substring(0, locations.indexOf(","));
                String latStr = locations.substring(lonStr.length()+1);
                json.put("longitude", lonStr);
                json.put("latitude", latStr);
            }
        } catch (Exception e) {
            log.error("高德坐标转换方法异常：", e);
        }

        return json;
    }

    public static String doGet(String url, JSONObject data, Map<String, String> properties) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回结果字符串

        StringBuffer urlNameString = new StringBuffer().append(url).append("?");
        if (data != null) {
            for (String key : data.keySet()) {
                urlNameString.append(key).append("=").append(data.get(key)).append("&");
            }
            url = urlNameString.substring(0, urlNameString.lastIndexOf("&"));
        }

        try {
            // 创建远程url连接对象
            URL httpUrl = new URL(url);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) httpUrl.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：15000毫秒
            connection.setConnectTimeout(15000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            if(null != properties && !properties.isEmpty()){
                for (String key:properties.keySet()){
                    connection.setRequestProperty(key, properties.get(key));
                }
            }
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封装输入流is，并指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放数据
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            connection.disconnect();// 关闭远程连接
        }

        return result;
    }


}
