package com.ho.common.tools.util;

import com.alibaba.fastjson.JSONObject;
import com.ho.common.tools.entity.MyAddress;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class AddressUntils {

    static String secretKey = "NANBZ-3DNCZ-AFLXD-TZNIK-NI2L7-HOFDO";

    /**
     * @param lat 纬度
     * @param lng 经度
     * @return
     */
    public static MyAddress getAddress(String lat, String lng){
        MyAddress myAddress = null;
        try {
            JSONObject result = getLocationInfo(lat, lng).getJSONObject("result");
            JSONObject jsonObject = JSONObject.parseObject(result.toString());
            Object ad_info = jsonObject.get("ad_info");
            myAddress = JSONObject.parseObject(ad_info.toString(), MyAddress.class);
        }catch (Exception e){
            e.printStackTrace();
            log.error("getAddress error:{}",e.getMessage());
        }
        return myAddress;
    }

    public static JSONObject getLocationInfo(String lat, String lng) throws IOException {
        String urlString = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + lat + "," + lng + "&key=" + secretKey;
        System.out.println("请求经纬度url:" + urlString);
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
        String line;
        String res = "";
        while ((line = in.readLine()) != null) {
            res += line + "\n";
        }
        in.close();
        JSONObject jsonObject = JSONObject.parseObject(res);
        return jsonObject;
    }


    public static void main(String[] args){
        MyAddress address = getAddress("31.331650", "120.673480");
        System.out.println(address);
//        address = getAddress("38.845614", "105.733502");
//        System.out.println(address);
    }

}
