package com.prolog.rdc.tms.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

/**
 *
 * 高德地理编码调用
 *
 * @className    :AMapGeocoding
 * @author       :fanzw
 * @date         :2024/1/19
 * @description  :
 *
 * @version      :1.2.1
 *
 */
@Configuration
public class AMapGeocodingUtil {

    // token地址
    private static String apikey;

    @Value("${prolog.gaode.apikey}")
    private void setApikey(String apikey) {
        AMapGeocodingUtil.apikey = apikey;
    }

    // 地理编码地址
    private static String geocodingUrl;

    @Value("${prolog.gaode.geocodingUrl}")
    private void setGeocodingUrl(String geocodingUrl) {
        AMapGeocodingUtil.geocodingUrl = geocodingUrl;
    }

    public static JSONObject amapGeocodingInfo(String address) {
        try {
            URL url = new URL(String.format(geocodingUrl, apikey, URLEncoder.encode(address, "UTF-8")));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            conn.disconnect();


            return JSON.parseObject(content.toString());
        } catch (Exception e) {
            e.printStackTrace();

            return null;
        }
    }

}
