package com.sckw.core.utils;

import java.io.IOException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sckw.core.model.constant.Global;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class LocUtils {

    static String GD_KEY = "739ace2ede6fe1e2f4ae3bcba890833c";

    /**
     * @param lng 经度
     * @param lat 纬度
     * @desc 通过gps查询位置信息-高德
     * @author zk
     * @date 2023/10/7
     **/
    public static String regeo(String lng, String lat) {
        if (StringUtils.isBlank(lng) || StringUtils.isBlank(lat)) {
            return null;
        }
        StringBuilder requestUrl = new StringBuilder();
        requestUrl.append("https://restapi.amap.com/v3/geocode/regeo?output=json&location="+ lng + Global.COMMA + lat);
        requestUrl.append("&key="+GD_KEY);
        requestUrl.append("&radius=1000&extensions=base");

        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(requestUrl.toString());
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            String responseStr = EntityUtils.toString(entity, "UTF-8");
            JSONObject resultJson = responseStr != null ? JSON.parseObject(responseStr) : null;
            Integer status = resultJson != null ? resultJson.getInteger("status") : null;
            if (status != null && status == Global.NUMERICAL_ONE) {
                JSONObject regeocode = resultJson.getJSONObject("regeocode");
                return regeocode != null ? regeocode.getString("formatted_address") : null;
            }

            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String res = regeo("118.879289", "38.052237");
        System.out.println(res);
    }
}
